Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

How to call OnExecutionUpdate for ATM strategy

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to call OnExecutionUpdate for ATM strategy

    Hi there,

    I am placing pending orders using ATM strategy and I am trying to print order execution time when order get executed.

    I am using simple code:
    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class ExampleAtmStrategyCancelEntryOrder : Strategy
    {
    
    private string atmStrategyId = string.Empty;
    private string orderId = string.Empty;
    private bool isAtmStrategyCreated = false;
    private int OrderCreatedOnBar;
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = NinjaTrader.Custom.Resource.NinjaScriptStrategyDes criptionSampleATMStrategy;
    Name = "ExampleAtmStrategyCancelEntryOrder";
    // This strategy has been designed to take advantage of performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = false;
    }
    }
    
    protected override void OnBarUpdate()
    {
    if (CurrentBar < BarsRequiredToTrade)
    return;
    
    // HELP DOCUMENTATION REFERENCE: Please see the Help Guide section "Using ATM Strategies" under NinjaScript--> Educational Resources--> http://ninjatrader.com/support/helpGuides/nt8/en-us/using_atm_strategies.htm
    
    // Make sure this strategy does not execute against historical data
    if(State == State.Historical)
    return;
    
    // Submits an entry limit order at the current low price to initiate an ATM Strategy if both order id and strategy id are in a reset state
    // **** YOU MUST HAVE AN ATM STRATEGY TEMPLATE NAMED 'AtmStrategyTemplate' CREATED IN NINJATRADER (SUPERDOM FOR EXAMPLE) FOR THIS TO WORK ****
    if (orderId.Length == 0 && atmStrategyId.Length == 0 && Close[0] > Open[0])
    {
    isAtmStrategyCreated = false; // reset atm strategy created check to false
    atmStrategyId = GetAtmStrategyUniqueId();
    orderId = GetAtmStrategyUniqueId();
    AtmStrategyCreate(OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "ATM 1", atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
    //check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback
    if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
    isAtmStrategyCreated = true;
    // keep track of what bar the order is submitted on so we can cancel if more than three bars pass without a fill
    OrderCreatedOnBar = CurrentBar;
    });
    }
    
    // Check that atm strategy was created before checking other properties
    if (!isAtmStrategyCreated)
    return;
    }
    protected override void OnPositionUpdate(Cbi.Position position, double averagePrice, int quantity, Cbi.MarketPosition marketPosition)
    {
    Print("OnPositionUpdate");
    }
    protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
    {
    Print("OnOrderUpdate");
    }
    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
    Print("OnExecutionUpdate");
    }
    }
    }
    P.S. I am using all types of updates I mean OnPositionUpdate, OnOrderUpdate, OnExecutionUpdate but non of them is printing so this means I couldn't call any of those 3 functions and I am wondering why. Please help me.

    waiting for your reply. Thank you in advanced
    Last edited by Revazi123; 02-10-2021, 05:32 AM.

    #2
    Hello Revazi123,

    Thanks for your post.

    ATM strategies that are started from NinjaScript strategies are separate strategies. You will not see overridden OnOrderUpdate, OnExecutionUpdate, or OnPositionUpdate events for the ATM strategies because the overridden methods are relevant to the NinjaScript strategy, not the ATM strategies that are started by it.

    You could subscribe to account level OrderUpdates, ExecutionUpdates and PositionUpdates from the Account object of the NinjaScript strategy, and you can see the all of these events from the account.

    You can then observe the OrderUpdate events on the account to find the ATM strategy Entry order that matches the instrument, price and order type you have submitted from the NinjaScript strategy. Once you have that Order object, you can check for its execution in the account level OnExecutionUpdate event method, and see if the executing order matches the Order object you captured.

    I have attached an example indicator that demonstrates subscribing to account level events. Please see below for documentation on the Account class. You will not need to add an Account object in the strategy, and you can just use the Account that is provided. My example adds an Account because it is in an indicator.

    Account class - https://ninjatrader.com/support/help...ount_class.htm

    We look forward to assisting.
    Attached Files
    JimNinjaTrader Customer Service

    Comment


      #3
      Thank you Jim you really helped.

      Comment


        #4
        Hello Jim,

        I have implemented code in my bot what you suggestion and now its works like this, when new order is opened and OnExecutionUpdate update is called all orders are closed and pending orders are also deleted but currently executed orders stop loss and take profit also got deleted and this is now my issue.
        I am using this code:
        Code:
        private void OnExecutionUpdate(object sender, ExecutionEventArgs e)
        {
        if (e.Execution.Name != "Close" && e.Execution.Order.Name != "Stop1" && e.Execution.Order.Name != "Target1")
        {
        foreach (string strategyId in atmStrategyIdList)
        {
        if (strategyId.Length > 0)
        {
        if (strategyId != e.OrderId &&
        strategyId != e.ExecutionId &&
        strategyId != e.Execution.OrderId &&
        strategyId != e.Execution.ExecutionId)
        {
        if (!AtmStrategyClose(strategyId))
        {
        Print("AtmStrategyClose Error");
        }
        }
        }
        }
        }
        }
        I even tried to filter by execution order name but still it is deleting stoploss and takeprofit of currently opened order.

        Please let me know what am I doing exactly wrong.
        Waiting for your reply. Thank you in advanced

        Comment


          #5
          Hello Revazi123,

          If you call AtmStrategyClose on an AtmStrategyId, that Atm strategy will be closed out and orders cancelled. If you just want to cancel pending entry orders and leave open positions open and protected, I suggest using AtmStrategyCancelEntryOrder with the orderID's of the entry orders you want to cancel.

          Atm Strategy Methods can be references here - https://ninjatrader.com/support/help...gy_methods.htm

          We look forward to assisting.
          JimNinjaTrader Customer Service

          Comment


            #6
            Hello Jim,

            Thanks for reply. What I am trying to do is that OnExecutionUpdate I am closing opened positions and also delete all orders. This code what I have attached here doing it well and it also leave currently executed order in market but it deletes currently executed order's stop loss and take profit. Thats my only issue.
            Code:
            e.Execution.Order.Name != "Stop1" && e.Execution.Order.Name != "Target1"
            I used that code to make it filtered so stop loss and take profit wouldn't be deleted but it got deleted anyways.

            Waiting for your reply. Thanks
            Last edited by Revazi123; 02-11-2021, 09:57 AM.

            Comment


              #7
              Hello Revazi123,

              Your code is looking for the execution of orders with those names and then calling AtmStrategyClose on all of the Atm strategies in your list. All of the ATM strategies that you call with AtmStrategyClose will have their orders canceled and positions closed. This means that the stop loss and profit target will be cancelled for those Atm strategies.

              If you goal is to cancel entry orders that have not filled, and leave active positions open with their stops in targets in place, you should use AtmStrategyCancelEntryOrder providing the orderID's of the Atm strategies you want to cancel the entry order. Have you tried this?

              What I am trying to do is that OnExecutionUpdate I am closing opened positions and also delete all orders.
              I used that code to make it filtered so stop loss and take profit wouldn't be deleted but it got deleted anyways.
              The two statements above sound contradictory: If you want to close all open positions and remove all orders, you will want to have the target and stop removed and have that position closed with a market order. This is what AtmStrategyClose does. Are you mentioning that you see the AtmStrategyClose method is not closing the Atm strategy's position but is removing the target and stop orders?

              Also keep in mind the first note above where I mention your code is looking for the execution of orders of that name and then calls AtmStrategyClose on all of your Atm strategies in your list. It is not filtering which Atm Strategies get closed. If that is your issue, I suggest modifying the code so you only call AtmStrategyClose on the positions you want closed with target/stop cancelled, and that you call AtmStrategyCancelEntryOrder for any entry orders that you want cancelled.

              If matters are still unclear, could you attach some screenshots to show us exactly what you are looking at?

              I look forward to assisting.
              JimNinjaTrader Customer Service

              Comment


                #8
                Hi Jim,

                Thanks for reply.
                No there is misunderstood. Okay let me explain again. I want to close all positions and also delete all pending orders instead of currently executed. I mean for example I have I have 1 buy positions and 2 pending orders Buy stop and Sell stop when 1 of those pending orders for example sell is executed I want to close buy positions and also delete buy stop order so there will be only 1 sell position in market which just got executed.

                Hope now I have explained it better.
                Waiting for your reply. Thanks

                Comment


                  #9
                  Hello Revazi123,

                  It's not exactly clear. Let's use the following vocabulary so we are not confusing ourselves.

                  Positions can be Long, Short or Flat

                  Orders can be Buy or Sell in addition to their order type (Market, Stop Market, Limit, etc.)

                  An Atm strategy could be open, where the entry order is filled/executed and a target and stop protecting the position.

                  If an Atm strategy is closed it would mean the stop and target are either filled or cancelled and the position the stop and target were protecting is closed.

                  When you mention "Buy position" I am not sure if you mean a pending order to enter a Long position, or that you are in a Long position.

                  When you mention pending orders, I am not sure if you are referring to profit target/stop loss orders or pending entry orders.

                  Could you clarify your question using these terms, and could you also be very clear in regards to pending entry orders and exit orders?

                  Screenshots can help as well to help us overcome a language barrier. If you walk through your example with screenshots and point out what you mean specifically, I can better understand.

                  Attaching a Screenshot

                  To send a screenshot with Windows 7 or newer I would recommend using Window's Snipping Tool.

                  Click here for instructions

                  Alternatively to send a screenshot press Alt + PRINT SCREEN to take a screenshot of the selected window. Then go to Start--> Accessories--> Paint, and press CTRL + V to paste the image. Lastly, save as a jpeg file and send the file as an attachment.

                  Click here for detailed instruction

                  I look forward to assisting.
                  JimNinjaTrader Customer Service

                  Comment


                    #10
                    Hi Jim,

                    Thanks for reply.
                    Sorry I am moving from MQL to NinjaScript(C#) and still use MQL terminology.
                    In my screenshots you can see what I mean:
                    Position Long which is placed with Target1 and Stop1 ---> I call it Buy position in my previous post.
                    Sell Stop Market which is placed ---> I call it Sell stop order in my previous post.
                    Buy Stop Market which is placed ---> I call it Buy stop order in my previous post.

                    So what I want is that when any of those Buy or Sell Stop Market orders got executed(which I described as Buy stop / Sell stop orders in my previous post) let say for example Buy Stop Market got executed I want to close previous Long position what is opened and also delete remaining Sell Stop Market order. So then I will have only Long position left with its own Stop1 and Target1 orders.
                    My main issue is that when it happens code do everything correctly but it also deletes Stop1 and Target1 Orders of currently executed Buy Stop Market Order which became Long Positions.


                    I hope my screenshots will make it more clear.

                    Thank you very much and I am waiting for your reply
                    Attached Files

                    Comment


                      #11
                      Thanks very much, I think I follow you now.
                      1. You have a Long Position with Target and stop and two additional Stop orders placed outside of the target and stop
                      2. You want to move one of the Stop orders close to the market price to have it fill before the target or stop loss
                      3. When one of the Stop orders fills, you want to close out the current ATM strategy, and use the Stop order as the entry for a new position (You are not trying to scale in.)
                      To accomplish, the Stop orders should be submitted with AtmStrategyCreate so they are entry orders for new ATM strategies.

                      In the account level OnExecutionUpdate event, look for the execution of these orders specifically. Look for the price of the order you submitted to, the order type and the instrument. I.E. check the following:

                      if (e.Execution.Order.OrderType == OrderType.StopMarket && e.Execution.Order.StopPrice == X && e.Execution.Order.Instrument == Instrument)

                      Then call AtmStrategyClose ONLY for the active ATM strategy and AtmStrategyCancelEntryOrder to cancel the other Stop order.

                      I may suggest commenting out the AtmStrategyClose code as you are testing so you can be sure new targets and stops are being created, and the other Stop Market order is cancelled, and then to uncomment and ensure you are only calling AtmStrategyClose for that single active Atm strategy.

                      So essentially, the 2nd Buy Stop would fill, putting you at a 2 Long Position, and we will have two sets of profit targets and stop losses, and the other Sell Stop order as well. Calling AtmStrategyClose only for the first ATM strategy will reduce the position to 1L and remove the first Profit Target and Stop Loss. Calling AtmStrategyCancelEntryOrder only for the remaining Sell Stop Market order will then leave you 1 Long with the new Profit Target and Stop Loss.

                      We look forward to assisting.

                      JimNinjaTrader Customer Service

                      Comment


                        #12
                        Thanks for reply.

                        Yes I have tried to first use AtmStrategyCancelEntryOrder. Below is my code for it but my main issue is that AtmStrategyClose deletes newly opened long position's Stop1 and Target1.

                        Code:
                        if (e.Execution.Name != "Close" && e.Execution.Order.Name != "Stop1" && e.Execution.Order.Name != "Target1")
                        {
                        foreach (string strategyOrderId in atmStrategyOrderIdList)
                        {
                         if (!AtmStrategyCancelEntryOrder(strategyOrderId))
                         {
                         Print("AtmStrategyCancelEntryOrder Error");
                         }
                        }
                        foreach (string strategyId in atmStrategyIdList)
                        {
                        if (strategyId.Length > 0)
                        {
                        if (strategyId != e.OrderId &&
                        strategyId != e.ExecutionId &&
                        strategyId != e.Execution.OrderId &&
                        strategyId != e.Execution.ExecutionId)
                        {
                        if (!AtmStrategyClose(strategyId))
                        {
                        Print("AtmStrategyClose Error");
                        }
                        }
                        }
                        }
                        }

                        Comment


                          #13
                          Hello Revazi123,

                          You are looping through a list of AtmStrategies so it is quite likely that you are trying to close multiple ATM strategies.

                          My recommendation from post #11 remains: first focus on having a new protected position opened with your Sell Stop and Buy Stop orders, then focus on making sure you are cancelling the other order with AtmStrategyCancelEntryOrder, then finally focus on calling AtmStrategyClose ONLY for that last active ATM strategy.

                          It can be helpful to use prints and keep note of the ATM strategy ID's when you create them and add them to your list, and then to also print them off when you want to call AtmStrategyClose so you can check your work and make sure you are only calling AtmStrategyClose for that one specific ATM strategy.

                          We look forward to assisting.
                          JimNinjaTrader Customer Service

                          Comment


                            #14
                            I am trying to do it but didn't succeed

                            Can you please give me code example. I am trying to make it almost 1 week.

                            Please help me.

                            Comment


                              #15
                              Hello Revazi123,

                              This is more of a request for specific functionality than a small educational example. The steps I suggested will lead you to a on a clear path to get each piece working. If you need further assistance or would like a piece of code written for you that accomplishes your specific task, you could consider enlisting the services of a NinjaScript Consultant. If that interests you, please let me know and I can have a colleague reply with more information.

                              We look forward to assisting.
                              JimNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by yertle, Yesterday, 12:24 PM
                              1 response
                              10 views
                              0 likes
                              Last Post yertle
                              by yertle
                               
                              Started by Mr Bread, Today, 04:25 AM
                              2 responses
                              9 views
                              0 likes
                              Last Post Mr Bread  
                              Started by kandise, Today, 09:41 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post kandise
                              by kandise
                               
                              Started by Mubeen Haider, Today, 09:41 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post Mubeen Haider  
                              Started by nicbizz, Today, 09:02 AM
                              0 responses
                              7 views
                              0 likes
                              Last Post nicbizz
                              by nicbizz
                               
                              Working...
                              X