public void FromNT_OnOrderUpdate(IOrder order, IExecution exec) { try { if (order == null) return; OrderFixBridge nt7fb; ExecStatus current_exec_status; lock (locker_) { nt7fb = m_orders.AddOrGet(order, string.Empty, null); if (exec != null) nt7fb.AddExec(exec); current_exec_status = nt7fb.GetExecStatus(); } if (exec == null) SendExecutionReport(nt7fb, order.Instrument.FullName, double.NaN, double.NaN, "execution on order occured"); else SendExecutionReport(nt7fb, order.Instrument.FullName, exec.Quantity, exec.Price, "execution on order occured"); }catch(Exception e) { m_logger.Info("[QuickFixApp.FromNT_OnOrderUpdate]", e.ToString()); } }
public void OnExecutionStopped(IExecution execution) { if (!execution.CurrentNode.OutgoingTransitions.Any()) { KillExecution(execution); } }
public void Execute(IExecution execution) { execution.Stop(); int incomingTransitionCount = execution.CurrentNode.IncomingTransitions.Count(); if (incomingTransitionCount > 1) { var root = execution.GetConcurrentRoot(); var executionCollector = new ExecutionCollector(e => !e.IsActive && e.CurrentNode == execution.CurrentNode); root.Accept(executionCollector); int joinedTransitionCount = executionCollector.Result.DistinctBy(e => e.IncomingTransition).Count(); if (incomingTransitionCount > joinedTransitionCount) { Logger.InfoFormat("Cannot join in node '{0}' yet. Joined: {1}, To join: {2}. Waiting...", execution.CurrentNode.Identifier, joinedTransitionCount, incomingTransitionCount); execution.Wait(); return; } root.Split(execution.CurrentNode); } else { execution.Split(execution.CurrentNode); } }
public void Visit(IExecution execution) { if (predicate(execution)) { result.Add(execution); } }
public ViewModel(IExrinContainer exrinContainer, IVisualState visualState, [CallerFilePath] string caller = nameof(ViewModel)) { if (exrinContainer == null) throw new ArgumentNullException(nameof(IExrinContainer)); _applicationInsights = exrinContainer.ApplicationInsights; _displayService = exrinContainer.DisplayService; _navigationService = exrinContainer.NavigationService; _errorHandlingService = exrinContainer.ErrorHandlingService; VisualState = visualState; if (VisualState != null) Task.Run(() => visualState.Init()) .ContinueWith((task) => { if (task.Exception != null) _applicationInsights.TrackException(task.Exception); }); Execution = new Execution() { HandleTimeout = TimeoutHandle, NotifyOfActivity = NotifyActivity, NotifyActivityFinished = NotifyActivityFinished, HandleResult = HandleResult }; }
protected override void OnExecution(IExecution execution) { // Remember to check the underlying IOrder object for null before trying to access its properties if (execution.Order != null && execution.Order.OrderState == OrderState.Filled) { Print(Time + " - " + execution.ToString()); } }
protected override void OnOrderExecution(IExecution execution) { if (execution.PositionType == PositionType.Flat) { _orderentershort = null; _orderenterlong = null; } }
public void Dispose() { if (executionInterface != null) { executionInterface.ReleaseContext(contextHandle); executionInterface = null; } }
/// <summary> /// Handle a sql string and check it with the engine /// </summary> /// <param name="actual">SQL string</param> /// <returns>true, if the query defined in parameter is executed in less that expected else false</returns> public bool doMatch(IExecution actual) { Result = actual.Run(); return ( Result.TimeElapsed.TotalMilliseconds < maxTimeMilliSeconds ); }
protected override void OnExecution(IExecution execution) { ThreadPool.QueueUserWorkItem(new WaitCallback(obj => { lock (locker_) NinjaTrader_FixBridge.QuickFixStaticAcceptor.FromNT_OnOrderUpdate(execution.Order, execution); })); }
public virtual void testNonInterruptingUnderProcessDefinitionScope() { IProcessInstance processInstance = runtimeService.StartProcessInstanceByKey("process"); // the process instance must have a message event subscription: IExecution execution = runtimeService.CreateExecutionQuery() /*.MessageEventSubscriptionName("newMessage")*/.First(); Assert.NotNull(execution); Assert.AreEqual(1, CreateEventSubscriptionQuery().Count()); Assert.AreEqual(2, runtimeService.CreateExecutionQuery().Count()); // if we trigger the usertask, the process terminates and the event subscription is removed: ITask task = taskService.CreateTaskQuery().First(); Assert.AreEqual("task", task.TaskDefinitionKey); taskService.Complete(task.Id); AssertProcessEnded(processInstance.Id); Assert.AreEqual(0, CreateEventSubscriptionQuery().Count()); Assert.AreEqual(0, runtimeService.CreateExecutionQuery().Count()); // ###################### now we start a new instance but this time we trigger the event subprocess: processInstance = runtimeService.StartProcessInstanceByKey("process"); runtimeService.CorrelateMessage("newMessage"); Assert.AreEqual(2, taskService.CreateTaskQuery().Count()); Assert.AreEqual(1, CreateEventSubscriptionQuery().Count()); // now let's first complete the task in the main flow: task = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task").First(); taskService.Complete(task.Id); // we still have 2 executions (one for process instance, one for subprocess Scope): Assert.AreEqual(2, runtimeService.CreateExecutionQuery().Count()); // now let's complete the task in the event subprocess task = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "eventSubProcessTask").First(); taskService.Complete(task.Id); // Done! AssertProcessEnded(processInstance.Id); Assert.AreEqual(0, runtimeService.CreateExecutionQuery().Count()); // #################### again, the other way around: processInstance = runtimeService.StartProcessInstanceByKey("process"); runtimeService.CorrelateMessage("newMessage"); Assert.AreEqual(2, taskService.CreateTaskQuery().Count()); task = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "eventSubProcessTask").First(); taskService.Complete(task.Id); // we still have 2 executions (usertask in main flow is Scope): Assert.AreEqual(2, runtimeService.CreateExecutionQuery().Count()); task = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task").First(); taskService.Complete(task.Id); // Done! AssertProcessEnded(processInstance.Id); Assert.AreEqual(0, runtimeService.CreateExecutionQuery().Count()); }
protected override void OnExecution(IExecution execution) { if (execution.Order != null && execution.Order.OrderState == OrderState.Filled) { //log("Execution:"+execution.ToString()); if (ex.entryOrder != null && ex.entryOrder == execution.Order) { trade.entry = execution.Order.AvgFillPrice; trade.enteredBar = bar; trade.enteredContracts += execution.Quantity; log("EXECUTION: ENTERED[" + execution.Quantity + "] at " + trade.entry + ";totalEntered=" + trade.enteredContracts); //trade.pending=false; //ex.pendingShortEntry=false; } else { lock (thisLock){ if (execution.Order.OrderAction.CompareTo(OrderAction.Sell) == 0) { ex.pendingLongExit = true; ex.pendingShortExit = false; } else { ex.pendingShortExit = true; ex.pendingLongExit = false; } trade.enteredContracts -= execution.Quantity; double currentExit = execution.Order.AvgFillPrice; //double gain=0; if (ex.pendingLongExit) { trade.gain = (currentExit - trade.entry); } else if (ex.pendingShortExit) { trade.gain = (trade.entry - currentExit); } double net_gain = (trade.gain * 4 * 12.5 - 4) * execution.Quantity; gainTotal += net_gain; log("EXITED{" + execution.Name + "}[" + execution.Quantity + "] at " + currentExit + ";$$$$$$ gain=" + trade.gain + ";net=" + net_gain.ToString("C") + "; $$$$$ total=" + gainTotal.ToString("C")); if (ex.stopOrder != null && execution.Order != ex.stopOrder) { CancelOrder(ex.stopOrder); } else if (ex.exitOrder != null && execution.Order == ex.exitOrder) { CancelOrder(ex.exitOrder); } ex.exitOrder = null; ex.stopOrder = null; } } } }
public IExecutionBuilder Configure(IExecution execution) { if (first == execution) { return(this); } return(new Listed(new[] { first, execution })); }
public void Persist(IExecution execution) { if (executions.ContainsKey(execution.Identifier)) { executions.Remove(execution.Identifier); } executions.Add(execution.Identifier, execution); }
public IExecutionBuilder Configure(IExecution execution) { if (executions.Contains(execution)) { return(this); } return(new Listed(executions.Append(execution))); }
protected internal ExecutionTree(IExecution execution, IList <ExecutionTree> children) { this.WrappedExecution = execution; this.Children = children; foreach (ExecutionTree child in children) { child.parent = this; } }
protected override void OnExecution(IExecution execution) { string kObj = "OnExecution"; if (scalpEntry == execution.Order || swingEntry == execution.Order) { // set breakeven and last entry price to make mfe breakeven stop calculation easier mfeStopPrice = 9999; lastEntryPrice = entryPrice = breakevenPrice = execution.Order.AvgFillPrice; kLog(kObj, "EXE", execution.Order.ToString()); } if (scalpEntry != null && scalpEntry == execution.Order && (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && OrderState.Filled > 0))) { scalpStopLoss = ExitShortStop(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice + orgStopPxInTicks * TickSize), scalpStopName, scalpEntryName); scalpProfitTarget = ExitShortLimit(0, true, execution.Order.Filled, scalpTarget, scalpProfitName, scalpEntryName); scalpEntry = null; } if (swingEntry != null && swingEntry == execution.Order && (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && OrderState.Filled > 0))) { swingStopLoss = ExitShortStop(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice + orgStopPxInTicks * TickSize), swingStopName, swingEntryName); swingProfitTarget = ExitShortLimit(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice - orgProfitPxInTicks * TickSize), swingProfitName, swingEntryName); swingEntry = null; } if (scalpProfitTarget == execution.Order && scalpProfitTarget.OrderState == OrderState.Filled) { try { // set swing position to breakeven on successful scalph fill. Move Stop to Market - 1 tick if breakeven stop order cannot be placed successfully if (Close[0] < entryPrice) { swingStopLoss = ExitShortStop(0, true, swingStopLoss.Quantity, entryPrice, swingBreakevenName, swingEntryName); } else if (Close[0] >= entryPrice) { ExitShortStop(0, true, swingStopLoss.Quantity, Close[0] + 1 * TickSize, swingBreakevenName + " MKT", swingEntryName); } kLog(kObj, "ORD", swingStopLoss.ToString()); kLog(kObj, "ORD", String.Format("Move swing position to breakeven price {0}", entryPrice)); } catch (Exception ex) { kLog(kObj, "ERROR", "Exception caused by moving swing stop loss position" + Environment.NewLine + ex.ToString()); } entryPrice = 0; } if (scalpStopLoss == execution.Order && scalpStopLoss.OrderState == OrderState.Filled || scalpProfitTarget == execution.Order && scalpProfitTarget.OrderState == OrderState.Filled) { ClearScalpEntryInfo(); } if (swingStopLoss == execution.Order && swingStopLoss.OrderState == OrderState.Filled || swingProfitTarget == execution.Order && swingProfitTarget.OrderState == OrderState.Filled) { ClearSwingEntryInfo(); } }
public void LogWarning( IExecution execution, string warningMessage, string overrideClassName = null, string overrideMethodName = null, string className = null, string methodName = null) { }
/// <summary> /// Initializes a new instance of the <see cref="PlatformServices" /> class /// </summary> /// <param name="authorizationService">The Authorization service</param> /// <param name="repositoryService">The repository service</param> /// <param name="executionService">The execution service</param> /// <param name="org">The current service owner</param> /// <param name="service">The current service</param> public PlatformServices(IAuthorization authorizationService, IRepository repositoryService, IExecution executionService, string org, string service) { _authorization = authorizationService; _repository = repositoryService; _execution = executionService; Org = org; Service = service; }
public void LogError( IExecution execution, string errorMessage, string overrideClassName = null, string overrideMethodName = null, string className = null, string methodName = null) { }
protected override void OnExecution(IExecution execution) { _execInProgress = false; NtGetUnrealizedQuantity(Account, Instrument, ref _totalPositionQuantity, ref _marketPosition); //if (!BackTest) //{ // NtGetUnrealizedQuantity(Account, Instrument, ref _totalPositionQuantity, ref _marketPosition); //} }
/// <summary> /// Initializes a new instance of the <see cref="MethodAdviceRecord"/> class. /// </summary> /// <param name="name">Name of the advice call.</param> /// <param name="context"><see cref="IExecutionContext"/> parameter.</param> /// <param name="execution"><see cref="IExecution"/> parameter.</param> /// <param name="exception">System.Exception parameter.</param> /// <param name="rReturn"><see cref="IReturn"/> parameter.</param> /// <param name="hasException">HasException parameter.</param> public MethodAdviceRecord(string name, IExecutionContext context, IExecution execution, Exception exception, IReturn rReturn, bool?hasException) { Name = name; Context = context; Execution = execution; Exception = exception; Return = rReturn; HasException = hasException; }
public void Push(IExecution exe) { if (Executions.Count == Constants.MAX_EXE_DEPTH) { throw new BoundaryException(); } Executions.Push(exe); }
/// <inheritdoc/> public IService Configure(IExecution execution) { if (execution is null) { throw new ArgumentNullException(nameof(execution)); } return(new Service(originationBuilder, terminationBuilder, executionBuilder.Configure(execution), spanBuilder)); }
/// <summary> /// Add a execution to our statistic (e.g. for backtesting). /// </summary> /// <param name="tradingmanager"></param> /// <param name="nameofthestrategy"></param> /// <param name="execution"></param> public void Add(ITradingManager tradingmanager, string nameofthestrategy, IExecution execution) { //Statistic stat = new Statistic(tradingmanager, nameofthestrategy, execution); //if (stat.IsValid) //{ // this.List.Add(stat); //} this.List.Add(new Statistic(tradingmanager, nameofthestrategy, execution)); }
public virtual void testWaitStateBehavior() { IProcessInstance pi = runtimeService.StartProcessInstanceByKey("receiveTask"); IExecution execution = runtimeService.CreateExecutionQuery(c => c.ProcessInstanceId == pi.Id && c.ActivityId == "waitState").First(); Assert.NotNull(execution); runtimeService.Signal(execution.Id); AssertProcessEnded(pi.Id); }
protected override void OnExecution(IExecution execution) { if (scalpEntry != null && scalpEntry == execution.Order && (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && OrderState.Filled > 0))) { scalpStopLoss = ExitShortStop(0, true, execution.Order.Filled, Math.Max(Math.Max(High[0], High[1]), High[2]), "SL", "ENTRY"); scalpProfitTarget = ExitShortLimit(0, true, execution.Order.Filled, scalpEntry.AvgFillPrice - 2 * Math.Abs(Math.Max(Math.Max(High[0], High[1]), High[2]) - scalpEntry.AvgFillPrice), "PT", "ENTRY"); scalpEntry = null; } }
public void LogError( IExecution execution, Exception exception, string overrideClassName = null, string overrideMethodName = null, string className = null, string methodName = null) { throw new NotImplementedException(); }
public void LogInformation( IExecution execution, string informationMessage, string overrideClassName = null, string overrideMethodName = null, string detailedInformationMessage = null, string className = null, string methodName = null) { }
public virtual void testNonInterruptingEventInCombinationWithReceiveTaskInsideSubProcess() { // given IProcessInstance instance = runtimeService.StartProcessInstanceByKey("process"); string ProcessInstanceId = instance.Id; // when (1) runtimeService.CorrelateMessage("firstMessage"); // then (1) IActivityInstance activityInstance = runtimeService.GetActivityInstance(instance.Id); ActivityInstanceAssert.That(activityInstance).HasStructure(ActivityInstanceAssert.DescribeActivityInstanceTree(instance.ProcessDefinitionId) .BeginScope("subProcess").Activity("task1").BeginScope("innerSubProcess").Activity("receiveTask").Done()); Assert.AreEqual(1, taskService.CreateTaskQuery().Count()); ITask task1 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task1").First(); Assert.NotNull(task1); IExecution task1Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "task1").First(); Assert.IsFalse(ProcessInstanceId.Equals(((ExecutionEntity)task1Execution).ParentId)); // when (2) runtimeService.CorrelateMessage("secondMessage"); // then (2) Assert.AreEqual(2, taskService.CreateTaskQuery().Count()); task1 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task1").First(); Assert.NotNull(task1); task1Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "task1").First(); Assert.IsFalse(ProcessInstanceId.Equals(((ExecutionEntity)task1Execution).ParentId)); ITask task2 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task2").First(); Assert.NotNull(task2); IExecution task2Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "task1").First(); Assert.IsFalse(ProcessInstanceId.Equals(((ExecutionEntity)task2Execution).ParentId)); Assert.True(((ExecutionEntity)task1Execution).ParentId.Equals(((ExecutionEntity)task2Execution).ParentId)); Assert.AreEqual(0, runtimeService.CreateEventSubscriptionQuery().Count()); taskService.Complete(task1.Id); taskService.Complete(task2.Id); AssertProcessEnded(ProcessInstanceId); }
protected override void OnExecution(IExecution execution) { double limitPrice = 0; double stopPrice = 0; if (execution.Order == null) { //Print(Time + " -->> OnExecution.Order is null"); return; } if (execution.Order.OrderState == OrderState.Filled) { enableTrade = false; // limit 1 trade / day if (execution.Order.OrderAction == OrderAction.Buy) { stopPrice = orb.LongStop[0]; limitPrice = orb.LongTarget1[0]; if (UseTarget2 == 1) { limitPrice = orb.LongTarget2[0]; } //DrawDot(CurrentBar + "limitPrice", false, 0, limitPrice, Color.Green); SubmitOrder(0, OrderAction.Sell, OrderType.Limit, execution.Order.Quantity, limitPrice, 0, "closeDayTrade", "Close Long Limit"); if (EnableStops == 1) { SubmitOrder(0, OrderAction.Sell, OrderType.Stop, execution.Order.Quantity, 0, stopPrice, "closeDayTrade", "Close Long Stop"); } } if (execution.Order.OrderAction == OrderAction.Sell) { stopPrice = orb.ShortStop[0]; limitPrice = orb.ShortTarget1[0]; if (UseTarget2 == 1) { limitPrice = orb.ShortTarget2[0]; } //DrawDot(CurrentBar + "limitPrice", false, 0, limitPrice, Color.Green); SubmitOrder(0, OrderAction.BuyToCover, OrderType.Limit, execution.Order.Quantity, limitPrice, 0, "closeDayTrade", "Close Short Limit"); if (EnableStops == 1) { SubmitOrder(0, OrderAction.BuyToCover, OrderType.Stop, execution.Order.Quantity, 0, stopPrice, "closeDayTrade", "Close Short Stop"); } } } else { Print(Time + " execution.Order: " + execution.Order.ToString()); } }
public virtual void testNonInterruptingWithUserTaskAndBoundaryEvent() { // given string ProcessInstanceId = runtimeService.StartProcessInstanceByKey("process").Id; // when (1) runtimeService.CorrelateMessage("firstMessage"); // then (1) Assert.AreEqual(2, taskService.CreateTaskQuery().Count()); ITask task1 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task1").First(); Assert.NotNull(task1); IExecution task1Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "task1").First(); Assert.AreEqual(ProcessInstanceId, ((ExecutionEntity)task1Execution).ParentId); ITask task2 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "innerTask").First(); Assert.NotNull(task2); IExecution task2Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "innerTask").First(); Assert.IsFalse(ProcessInstanceId.Equals(((ExecutionEntity)task2Execution).ParentId)); // when (2) taskService.Complete(task2.Id); // then (2) Assert.AreEqual(2, taskService.CreateTaskQuery().Count()); task1 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task1").First(); Assert.NotNull(task1); task1Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "task1").First(); Assert.AreEqual(ProcessInstanceId, ((ExecutionEntity)task1Execution).ParentId); task2 = taskService.CreateTaskQuery(c => c.TaskDefinitionKey == "task2").First(); Assert.NotNull(task2); task2Execution = runtimeService.CreateExecutionQuery(c => c.ActivityId == "tasks").First(); Assert.AreEqual(ProcessInstanceId, ((ExecutionEntity)task1Execution).ParentId); Assert.AreEqual(0, runtimeService.CreateEventSubscriptionQuery().Count()); taskService.Complete(task1.Id); taskService.Complete(task2.Id); AssertProcessEnded(ProcessInstanceId); }
/// <summary> /// The OnExecution() method is called on an incoming execution. An execution /// is another name for a fill of an order. /// </summary> /// <param name="execution"></param> protected override void OnExecution(IExecution execution) { // Remember to check the underlying IOrder object for null before trying to // access its properties if (execution.Order != null && execution.Order.OrderState == OrderState.Filled) { // Print(execution.ToString()); //tradesInSession++; //enableTrade = false; } }
public virtual void testSendSignalToStartEventWithVariables() { Deployment(signalStartProcess("signalStart")); IDictionary <string, object> variables = ESS.FW.Bpm.Engine.Variable.Variables.CreateVariables().PutValue("var1", "a").PutValue("var2", "b"); runtimeService.CreateSignalEvent("signal").SetVariables(variables).Send(); IExecution execution = runtimeService.CreateExecutionQuery().First(); Assert.That(runtimeService.GetVariables(execution.Id), Is.EqualTo(variables)); }
protected override void OnExecution(IExecution execution) { if (scalpEntry != null && scalpEntry == execution.Order && (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && OrderState.Filled > 0))) { entryPrice = scalpEntry.AvgFillPrice; Print(string.Format("[{0}] Short the Market {1}", Bars.BarsSinceSession, entryPrice)); scalpStopLoss = ExitShortStop(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice + orgStopPxInTicks * TickSize), scalpStopName, scalpEntryName); scalpProfitTarget = ExitShortLimit(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice - orgProfitPxInTicks * TickSize), scalpProfitName, scalpEntryName); scalpEntry = null; } if (swingEntry != null && swingEntry == execution.Order && (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && OrderState.Filled > 0))) { swingStopLoss = ExitShortStop(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice + orgStopPxInTicks * TickSize), swingStopName, swingEntryName); swingProfitTarget = ExitShortLimit(0, true, execution.Order.Filled, Instrument.MasterInstrument.Round2TickSize(execution.Order.AvgFillPrice - 3 * orgProfitPxInTicks * TickSize), swingProfitName, swingEntryName); swingEntry = null; } if (scalpProfitTarget == execution.Order && scalpProfitTarget.OrderState == OrderState.Filled) { try { Print(string.Format("[{0}] breakeven price: {1} close: {2}", Bars.BarsSinceSession, entryPrice, Close[0])); // set swing position to breakeven on successful scalph fill. Move Stop to Market - 1 tick if breakeven stop order cannot be placed successfully if (Close[0] < entryPrice) { swingStopLoss = ExitShortStop(0, true, swingStopLoss.Quantity, entryPrice, swingBreakevenName, swingEntryName); } else if (Close[0] >= entryPrice) { ExitShortStop(0, true, swingStopLoss.Quantity, Close[0] + 1 * TickSize, swingBreakevenName + " MKT", swingEntryName); } Print("Moving swing stop to breakeven"); } catch (Exception ex) { Print("Exception caused by moving swing stop loss position" + Environment.NewLine + ex.ToString()); } //entryPrice = 0; } if (scalpStopLoss == execution.Order && scalpStopLoss.OrderState == OrderState.Filled || scalpProfitTarget == execution.Order && scalpProfitTarget.OrderState == OrderState.Filled) { scalpStopLoss = scalpProfitTarget = null; Print(execution.Order.ToString()); } if (swingStopLoss == execution.Order && swingStopLoss.OrderState == OrderState.Filled || swingProfitTarget == execution.Order && swingProfitTarget.OrderState == OrderState.Filled) { swingStopLoss = swingProfitTarget = null; Print(execution.Order.ToString()); } }
/// <summary> /// Returns the standard text for emails on order execution. /// </summary> /// <param name="execution"></param> /// <param name="strategyname"></param> /// <returns></returns> public static string GetEmailText(IExecution execution, string strategyname) { StringBuilder str = new StringBuilder(); str.AppendLine("Strategy: " + strategyname); str.AppendLine("Order " + execution.Name + " on instrument " + execution.Instrument.Name + " was executed."); str.AppendLine("Position: " + execution.MarketPosition.ToString()); str.AppendLine("Quantity: " + (execution.Order.Quantity).ToString("F2")); str.AppendLine("Price: " + (execution.Order.Price).ToString("F2")); str.AppendLine("Investment: " + (execution.Order.Quantity * execution.Order.Price).ToString("F2")); return(str.ToString()); }
private static void InitializeDependencyInjection() { var kernel = new StandardKernel(); var modules = new List <INinjectModule> { new CommonIOCRegistrationModule(), new WebSiteScanerIOCRegistrationModule(), }; kernel.Load(modules); _engine = kernel.Get <IExecution>(); }
// TODO: builder public Execution(IExecution parent, INode currentNode, bool isActive, bool isFinished, IDictionary<string, object> data, string incomingTransition, string identifier, string workflowInstanceIdentifier, IExecutionPlan executionPlan, IList<IExecution> children, IWorkflowDefinition workflowDefinition) : this(identifier, workflowInstanceIdentifier, workflowDefinition, executionPlan) { Parent = parent; IncomingTransition = incomingTransition; CurrentNode = currentNode; IsActive = isActive; Data = data; Children = children; IsFinished = isFinished; }
public void Persist(IExecution execution) { using (var session = sessionFactory.OpenSession()) { using (var txn = session.BeginTransaction()) { var entity = executionTransformer.Transform(execution); session.SaveOrUpdate(entity); session.Flush(); txn.Commit(); } } }
public void Persist(IExecution execution) { var findRoot = FindRoot(execution); var query = graphClient.Cypher .Match("(e:Execution {Identifier: {id}})") .OptionalMatch("(e)-[t:EXECUTES]->()") .Delete("t"); if (execution.CurrentNode != null) { query.Match("(n:Node {Identifier: {currentNodeId}})") .Merge("(e)-[:EXECUTES]->(n)"); } else { query.Merge("(e:Execution {Identifier: {id}})"); } query.Set("e = {execution}") .WithParams(new { execution = new ExecutionModel { Identifier = findRoot.Identifier, WorkflowInstanceIdentifier = findRoot.WorkflowInstanceIdentifier, IsActive = findRoot.IsActive, IsFinished = findRoot.IsFinished, Data = objectSerializer.Serialize(execution.Data), IncomingTransition = findRoot.IncomingTransition }, id = findRoot.Identifier, currentNodeId = execution.CurrentNode == null ? null : execution.CurrentNode.Identifier }) .ExecuteWithoutResults(); graphClient.Cypher .Match("(e:Execution {Identifier: {id}})") .Match("(wf:WorkflowDefinition {Identifier: {wfId}})") .Merge("(e)-[:REFERENCES]->(wf)") .WithParams(new { id = findRoot.Identifier, wfId = findRoot.WorkflowDefinition.Identifier }).ExecuteWithoutResults(); PersistChildExecutions(findRoot, graphClient); }
public TestChannelsDialog(EventSequence sequence, IExecution executionInterface, bool constrainToGroup) { InitializeComponent(); _executionInterface = executionInterface; _channels = constrainToGroup ? sequence.Channels : sequence.FullChannels; if (_channels != null) { // ReSharper disable CoVariantArrayConversion listBoxChannels.Items.AddRange(_channels.ToArray()); // ReSharper restore CoVariantArrayConversion } _actualLevels = ((ISystem) Interfaces.Available["ISystem"]).UserPreferences.GetBoolean("ActualLevels"); trackBar.Maximum = _actualLevels ? Utils.Cell8BitMax : Utils.Cell8BitMax.ToPercentage(); _channelLevels = new byte[sequence.FullChannelCount]; _executionContextHandle = _executionInterface.RequestContext(false, true, null); _executionInterface.SetAsynchronousContext(_executionContextHandle, sequence); BringToFront(); trackBar.Value = trackBar.Maximum; }
private void PopulateExecutionModel(ExecutionModel model, ExecutionModel transformedParent, IExecution execution) { model.Identifier = execution.Identifier; model.WorkflowInstanceIdentifier = execution.WorkflowInstanceIdentifier; model.WorkflowDefinitionIdentifier = execution.WorkflowDefinition.Identifier; model.IsActive = execution.IsActive; model.IsFinished = execution.IsFinished; model.IncomingTransition = execution.IncomingTransition; model.CurrentNodeIdentifier = execution.CurrentNode == null ? null : execution.CurrentNode.Identifier; model.Parent = transformedParent; model.Children = execution.Children.Select(c => (ExecutionModel) CreateExecutionModel((dynamic) c, model)).ToList(); model.Variables = execution.Data.Select(entry => new ExecutionVariableModel { VariableKey = entry.Key, SerializedValue = serializer.Serialize(entry.Value), ValueType = entry.Value.GetType().AssemblyQualifiedName }).ToList(); }
public TestConsoleDialog(EventSequence sequence, IExecution executionInterface, bool constrainToGroup) { InitializeComponent(); _sequence = sequence; _executionInterface = executionInterface; _executionContextHandle = _executionInterface.RequestContext(false, true, null); _executionInterface.SetAsynchronousContext(_executionContextHandle, sequence); _channelLevels = new byte[_sequence.FullChannelCount]; var channels = new Channel[constrainToGroup ? _sequence.ChannelCount + 1 : _sequence.FullChannelCount + 1]; channels[0] = new Channel(Resources.Unassigned, Color.Gainsboro, 0); for (var channel = 1; channel <= channels.Length - 1; channel++) { channels[channel] = constrainToGroup ? _sequence.Channels[channel - 1] : _sequence.FullChannels[channel - 1]; } foreach (var trackBar in groupBox2.Controls.Cast<object>().OfType<ConsoleTrackBar>().Where(trackBar => trackBar.Master != null)) { trackBar.TextStrings = channels; trackBar.ResetIndex = 0; _channelControls.Add(trackBar); } }
public void Proceed(IExecution execution, INode node) { if (!execution.CurrentNode.OutgoingTransitions.Any()) { KillExecution(execution); return; } var operation = operationResolver.Resolve(node.Operation); if (operation == null) { throw new InvalidOperationException(string.Format("'{0}' is not an operation", node.Operation.FullName)); } Type genericOperationInterface = operation.GetType() .GetInterfaces() .FirstOrDefault( i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof (IOperation<>)); if ( genericOperationInterface != null) { Type genericType = genericOperationInterface.GetGenericArguments() .First(t => t.HasAttribute<WorkflowDataAttribute>()); object dataContext = DataMapper.CreateProxyFor(genericType, execution.Data); operation.GetType().GetMethod("Execute", new[] {typeof (IExecution), genericType}) .Invoke(operation, new[] {execution, dataContext}); } else { operation.Execute(execution); } }
public TestExecutionBuilder WithChild(IExecution child) { children.Add(child); return this; }
public TestExecutionBuilder WithParent(IExecution parent) { this.parent = parent; return this; }
public void Visit(IExecution execution) { action(execution); }
protected override void OnExecution(IExecution execution) { if (entryOrder != null && entryOrder == execution.Order) SendMail("*****@*****.**", "*****@*****.**", "BigDropSmallTargets", execution.ToString()); }
private IExecution FindRoot(IExecution execution) { if (execution.Parent == null) { return execution; } return FindRoot(execution.Parent); }
public void Execute(IExecution execution) { }
public static void FromNT_OnOrderUpdate(IOrder order, IExecution exec) { m_app.FromNT_OnOrderUpdate(order, exec); }
public void Execute(IExecution execution) { execution.Proceed(); }
protected void OnExecution(IExecution execution) { ThreadPool.QueueUserWorkItem(new WaitCallback(obj => { lock (locker_) NinjaTrader_FixBridge.QuickFixStaticAcceptor.FromNT_OnOrderUpdate(execution.Order, execution); })); }
protected override void OnExecution(IExecution execution) { if (execution.Order != null && execution.Order.OrderState == OrderState.Filled){ //log("Execution:"+execution.ToString()); if (ex.entryOrder != null && ex.entryOrder == execution.Order){ trade.entry=execution.Order.AvgFillPrice; trade.enteredBar=bar; log("EXECUTION: ENTERED at "+trade.entry); } else{ if(execution.Order.OrderAction.CompareTo(OrderAction.Sell)==0){ ex.pendingLongExit=true; ex.pendingShortExit=false; } else{ ex.pendingShortExit=true; ex.pendingLongExit=false; } double currentExit=execution.Order.AvgFillPrice; double gain=0; if(ex.pendingLongExit){ gain=(currentExit-trade.entry); }else if(ex.pendingShortExit){ gain=(trade.entry-currentExit); } double net_gain=gain*4*12.5-4; gainTotal+=net_gain; log("EXITED at "+currentExit+";$$$$$$ gain="+gain+";net="+net_gain.ToString("C")+"; $$$$$ total="+gainTotal.ToString("C")); if(ex.exitOrder==null){ log("EXECUTION: RESET WATCH"); processRangeEvent(RANGE_EVENT.END); range.active=false; } ex.exitOrder=null; } } }
private void PersistChildExecutions(IExecution execution, IGraphClient client) { foreach (var child in execution.Children) { if (child.IsFinished) { client.Cypher.Match("(child:Execution {Identifier: {childId}})") .OptionalMatch("()-[from]->(child)") .OptionalMatch("(child)-[to]->()") .OptionalMatch("(child)-[]->(e:Execution)") .OptionalMatch("(e)-[t]->()") .Delete("child, from, to, t, e") .WithParam("childId", child.Identifier) .ExecuteWithoutResults(); continue; } var query = client.Cypher .Merge("(parent:Execution {Identifier: {parentId}})") .Merge("(parent)-[:PARENT_OF]->(child:Execution {Identifier: {childId}})"); query.Set("child = {execution}") .WithParams(new { execution = new ExecutionModel { Identifier = child.Identifier, WorkflowInstanceIdentifier = child.WorkflowInstanceIdentifier, IsActive = child.IsActive, IsFinished = child.IsFinished, Data = objectSerializer.Serialize(execution.Data), IncomingTransition = child.IncomingTransition }, parentId = execution.Identifier, childId = child.Identifier }) .ExecuteWithoutResults(); client.Cypher .Match("(child:Execution {Identifier: {childId}})") .OptionalMatch("(child)-[t:EXECUTES]->()") .WithParam("childId", child.Identifier) .Delete("t").ExecuteWithoutResults(); if (child.CurrentNode != null) { client.Cypher .Match("(child:Execution {Identifier: {childId}})") .Match("(n:Node {Identifier: {currentNodeId}})") .Merge("(child)-[:EXECUTES]->(n)") .WithParam("childId", child.Identifier) .WithParam("currentNodeId", child.CurrentNode.Identifier) .ExecuteWithoutResults(); } PersistChildExecutions(child, client); } }
public override void Execute(IExecution execution, IExecutionPlan executionPlan) { action(true); base.Execute(execution, executionPlan); }
public void AddExec(IExecution iexec) { if(iexec!=null) m_executions.Add(iexec); }
protected override void OnExecution(IExecution execution) { // Remember to check the underlying IOrder object for null before trying to access its properties if (execution.Order != null && execution.Order.OrderState == OrderState.Filled){ //log("Execution:"+execution.ToString()); if (entryOrder != null && entryOrder == execution.Order){ currentEntry=execution.Order.AvgFillPrice; log("ENTERED at "+currentEntry); enteredBar=CurrentBars[0]; } else{ if(execution.Order.OrderAction.CompareTo(OrderAction.Sell)==0){ pendingLongExit=true; pendingShortExit=false; } else{ pendingShortExit=true; pendingLongExit=false; } double currentExit=execution.Order.AvgFillPrice; double gain=0; if(pendingLongExit){ gain=(currentExit-currentEntry); }else if(pendingShortExit){ gain=(currentEntry-currentExit); } double net_gain=gain*4*12.5-4; gainTotal+=net_gain; log("EXITED at "+currentExit+";$$$$$$ gain="+gain+";net="+net_gain.ToString("C")+"; $$$$$ total="+gainTotal.ToString("C")); if(exitOrder==null){ log("RESET WATCH"); watch=false; bounceTriggered=false; } exitOrder=null; } } }
protected bool doMatch(IExecution actual) { Result = actual.Run(); return Result.IsSuccess; }
private void FillChildren(IExecution parent, List<IExecution> children, IExecutionPlan executionPlan, IWorkflowDefinition workflowDefinition) { var result = graphClient.Cypher .Match("(root:Execution {Identifier: {id}})") .Match("(root)-[:PARENT_OF]->(child:Execution)") .OptionalMatch("(child)-[:EXECUTES]->(currentNode:Node)") .WithParam("id", parent.Identifier) .Return((child, currentNode) => new { Child = child.As<ExecutionModel>(), CurrentNode = currentNode.As<NodeModel>() }); foreach (var r in result.Results) { Dictionary<string, object> data = (Dictionary<string, object>) objectSerializer.Deserialize(r.Child.Data, typeof (Dictionary<string, object>)); var childExecutions = new List<IExecution>(); var e = new Execution(parent, r.CurrentNode == null ? null : workflowDefinition.Nodes.First(n => n.Identifier == r.CurrentNode.Identifier), r.Child.IsActive, r.Child.IsFinished, data, r.Child.IncomingTransition, r.Child.Identifier, r.Child.WorkflowInstanceIdentifier, executionPlan, childExecutions, workflowDefinition); children.Add(e); FillChildren(e, childExecutions, executionPlan, workflowDefinition); } }