Advertisement
Guest User

SampleOnOrderUpdate_NT8.zip

a guest
Aug 20th, 2021
446
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.66 KB | None | 0 0
  1. //
  2. // Copyright (C) 2019, NinjaTrader LLC <www.ninjatrader.com>.
  3. // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
  4. //
  5. #region Using declarations
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.ComponentModel.DataAnnotations;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using System.Xml.Serialization;
  17. using NinjaTrader.Cbi;
  18. using NinjaTrader.Gui;
  19. using NinjaTrader.Gui.Chart;
  20. using NinjaTrader.Gui.SuperDom;
  21. using NinjaTrader.Data;
  22. using NinjaTrader.NinjaScript;
  23. using NinjaTrader.Core.FloatingPoint;
  24. using NinjaTrader.NinjaScript.Indicators;
  25. using NinjaTrader.NinjaScript.DrawingTools;
  26. #endregion
  27.  
  28. // This namespace holds all strategies and is required. Do not change it.
  29. namespace NinjaTrader.NinjaScript.Strategies
  30. {
  31.     public class SampleOnOrderUpdate : Strategy
  32.     {
  33.         private Order entryOrder = null; // This variable holds an object representing our entry order
  34.         private Order stopOrder = null; // This variable holds an object representing our stop loss order
  35.         private Order targetOrder = null; // This variable holds an object representing our profit target order
  36.         private int sumFilled = 0; // This variable tracks the quantities of each execution making up the entry order
  37.  
  38.         protected override void OnStateChange()
  39.         {
  40.             if (State == State.SetDefaults)
  41.             {
  42.                 Description = @"Sample Using OnOrderUpdate() and OnExecution() methods to submit protective orders";
  43.                 Name = "SampleOnOrderUpdate";
  44.                 Calculate = Calculate.OnBarClose;
  45.                 EntriesPerDirection = 1;
  46.                 EntryHandling = EntryHandling.AllEntries;
  47.                 IsExitOnSessionCloseStrategy = true;
  48.                 ExitOnSessionCloseSeconds = 30;
  49.                 IsFillLimitOnTouch = false;
  50.                 MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
  51.                 OrderFillResolution = OrderFillResolution.Standard;
  52.                 Slippage = 0;
  53.                 StartBehavior = StartBehavior.WaitUntilFlat;
  54.                 TimeInForce = TimeInForce.Gtc;
  55.                 TraceOrders = false;
  56.                 RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
  57.                 StopTargetHandling = StopTargetHandling.ByStrategyPosition;
  58.                 BarsRequiredToTrade = 20;
  59.             }
  60.             else if (State == State.Realtime)
  61.             {
  62.                 // one time only, as we transition from historical
  63.                 // convert any old historical order object references
  64.                 // to the new live order submitted to the real-time account
  65.                 if (entryOrder != null)
  66.                     entryOrder = GetRealtimeOrder(entryOrder);
  67.                 if (stopOrder != null)
  68.                     stopOrder = GetRealtimeOrder(stopOrder);
  69.                 if (targetOrder != null)
  70.                     targetOrder = GetRealtimeOrder(targetOrder);
  71.             }
  72.         }
  73.  
  74.         protected override void OnBarUpdate()
  75.         {
  76.             // Submit an entry market order if we currently don't have an entry order open and are past the BarsRequiredToTrade bars amount
  77.             if (entryOrder == null && Position.MarketPosition == MarketPosition.Flat && CurrentBar > BarsRequiredToTrade)
  78.             {
  79.                 /* Enter Long. We will assign the resulting Order object to entryOrder1 in OnOrderUpdate() */
  80.                 EnterLong(1, "MyEntry");
  81.             }
  82.  
  83.             /* If we have a long position and the current price is 4 ticks in profit, raise the stop-loss order to breakeven.
  84.             We use (7 * (TickSize / 2)) to denote 4 ticks because of potential precision issues with doubles. Under certain
  85.             conditions (4 * TickSize) could end up being 3.9999 instead of 4 if the TickSize was 1. Using our method of determining
  86.             4 ticks helps cope with the precision issue if it does arise. */
  87.             if (Position.MarketPosition == MarketPosition.Long && Close[0] >= Position.AveragePrice + (7 * (TickSize / 2)))
  88.             {
  89.                 // Checks to see if our Stop Order has been submitted already
  90.                 if (stopOrder != null && stopOrder.StopPrice < Position.AveragePrice)
  91.                 {
  92.                     // Modifies stop-loss to breakeven
  93.                     stopOrder = ExitLongStopMarket(0, true, stopOrder.Quantity, Position.AveragePrice, "MyStop", "MyEntry");
  94.                 }
  95.             }
  96.         }
  97.  
  98.         protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
  99.         {
  100.             // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
  101.             // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
  102.             // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting
  103.             if (order.Name == "MyEntry")
  104.             {
  105.                 entryOrder = order;
  106.  
  107.                 // Reset the entryOrder object to null if order was cancelled without any fill
  108.                 if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
  109.                 {
  110.                     entryOrder = null;
  111.                     sumFilled = 0;
  112.                 }
  113.             }
  114.         }
  115.  
  116.         protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
  117.         {
  118.             /* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
  119.             which ensures your strategy has received the execution which is used for internal signal tracking. */
  120.             if (entryOrder != null && entryOrder == execution.Order)
  121.             {
  122.                 if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
  123.                 {
  124.                     // We sum the quantities of each execution making up the entry order
  125.                     sumFilled += execution.Quantity;
  126.  
  127.                     // Submit exit orders for partial fills
  128.                     if (execution.Order.OrderState == OrderState.PartFilled)
  129.                     {
  130.                         stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
  131.                         targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + 8 * TickSize, "MyTarget", "MyEntry");
  132.                     }
  133.                     // Update our exit order quantities once orderstate turns to filled and we have seen execution quantities match order quantities
  134.                     else if (execution.Order.OrderState == OrderState.Filled && sumFilled == execution.Order.Filled)
  135.                     {
  136.                         // Stop-Loss order for OrderState.Filled
  137.                         stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
  138.                         targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + 8 * TickSize, "MyTarget", "MyEntry");
  139.                     }
  140.  
  141.                     // Resets the entryOrder object and the sumFilled counter to null / 0 after the order has been filled
  142.                     if (execution.Order.OrderState != OrderState.PartFilled && sumFilled == execution.Order.Filled)
  143.                     {
  144.                         entryOrder = null;
  145.                         sumFilled = 0;
  146.                     }
  147.                 }
  148.             }
  149.  
  150.             // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
  151.             if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
  152.             {
  153.                 if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
  154.                 {
  155.                     stopOrder = null;
  156.                     targetOrder = null;
  157.                 }
  158.             }
  159.         }
  160.     }
  161. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement