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

Placing order inside indicator's script that is attached to Market Analyzer

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

    Placing order inside indicator's script that is attached to Market Analyzer

    Hi, I appreciate your help with the below issue:
    I have an indicator that is included as a column in the Market analyzer. Therefore, it can be applied to many instruments at once. The indicator displays a message in the Ninjascript output window when a certain condition is met in any of the instruments. Thus it has no plot and displays nothing in the Market Analyzer window. I need to place an ATM trade (e.g., Buy limit order with a linked stop sell order and sell limit order when the condition is met, such that the trade can be applied to all instruments in the Market Analyzer's list. Is this possible?
    Thank you.

    #2
    Hello MSerag,

    Thank you for your note.

    One option would be to develop a strategy that uses the indicator's signal to enter a trade. A downside of this is that the strategy would have to be added and enabled for each instrument manually rather than being applied to each instrument in the Market Analyzer using the indicator. For more information about using ATM strategies inside of a NinjaScript strategy:Otherwise, you could take more of an add-on approach and use the Account class within your indicator itself. The account class can be used to subscribe to account events and access account-related information, and it also allows you to create and submit orders. This also includes submitting orders with ATM strategies. We have more information at the following links:
    Please let us know if we may be of further assistance.
    Emily C.NinjaTrader Customer Service

    Comment


      #3
      Thanks Emily,
      Would you please let me know how the hierarchy of the indicator's script goes? or Ideally, can you refer to an example of an indicator with an AddOn that uses an account class and submit an ATM order in Sim101 account when a condition inside the indicator is achieved? Your help is highly appreciated.

      Comment


        #4
        Hello MSerag,

        Thank you for your reply.

        To clarify, you would not necessarily be using an add-on; you would be using the Account() class inside of an indicator. Sorry if what I said was confusing; when I said "you could take more of an add-on approach and use the Account class within your indicator itself." I meant an add-on style of approach and not the use of an add-on directly.

        There are some code snippets in the Help Guide that might prove useful to set this up. For example, on the page for the Account class there is an example that shows how to find the desired account and subscribe to AccountStatusUpdate, AccountItemUpdate, and ExecutionUpdate inside of OnStateChange:


        This process sets up an account object in the style of an add-on, though it would allow you to use CreateOrder() inside of your indicator and then you would put StartAtmStrategy() once the indicator condition is met to submit the entry order with the desired ATM strategy attached. I have created a very basic example of how to submit an order from an indicator that has an associated ATM strategy from a saved template called "myAtmStrategy" and you could also add this to the Market Analyzer as an indicator column. This should help with the idea of how to use the Account() class and the methods available from that class to submit orders from any type of NinjaScript object.

        SubmitOrderFromIndicator_NT8.zip

        Please feel free to reach out with any additional questions or concerns.
        Emily C.NinjaTrader Customer Service

        Comment


          #5
          Your help is highly appreciated Emily. I will check it.

          Comment


            #6
            Hello Emily, I guess I am doing a mistake as the order is not triggered. Would you please let me know whether this arbitrary strategy is correct? I set the calculations to be done on bar close. Thank you in advance.

            Code:
            protected override void OnBarUpdate()
            {
            if (State == State.Historical)
            return;
            if (CurrentBar == Count-1) // To run the calculations only on the last bar
            {
            myInstrument = Instrument.GetInstrument(Instrument.FullName);
            if (Close[0] > 0 & orderSubmitted == false && myAccount != null)
            
            {
            double SMA_5=SMA(5)[0]; double Sprd=Close[0]-Open[0];
            
            if (Sprd > Open[0]-SMA_5)
            {
            entryOrder = myAccount.CreateOrder(myInstrument, OrderAction.Buy, OrderType.Market, TimeInForce.Gtc, 1, 0, 0, null, "Entry", null);
            Print(myInstrument + " entryOrder created");
            NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrate gy("myAtmStrategy", entryOrder);
            orderSubmitted = true;
            Print(myInstrument + " StartAtmStrategy");
            }
            
            }
            if (orderSubmitted == false)
            OrderSubmitted[0] = 0;
            else
            OrderSubmitted[0] = 1;
            }
            }

            Comment


              #7
              Hello MSerag,

              Thank you for your reply.

              Do you see your print statements in the NinjaScript Output window when the script is added? If not, try printing the values for SMA_5, Open[0], and Sprd before the condition that creates and submits the entry order and after the values for these variables is set. This will help to understand if the condition Sprd > Open[0]-SMA_5 is being met or not. Here is an example of a print statement you could try:
              Print(String.Format("{0} Sprd: {1} > Open[0]: {2} - SMA_5: {3} Open-SMA: {4}", Time[0], Sprd, Open[0], SMA_5, Open[0] - SMA_5));

              If you are having difficulty understanding the output, you could take a screenshot or right-click in the output window and Save As to a file that you may attach to your response here.

              I appreciate your time and patience. Please let me know if I may be of further assistance.
              Emily C.NinjaTrader Customer Service

              Comment


                #8
                Hi Emily,
                I noticed that the order is triggered if I set the Market Analyzer/Columns/Properties/Setup/Calculate as 'On price change'. However, The order is not triggered when it is set as 'On bar close'. I need the calculations done at the instance the bar is closed then if the condition is satisfied, then the order should be triggered directly. I have also tried to do like below where I changed the value 0 to 1 but this did not trigger the order

                Code:
                double SMA_5=SMA(5)[1]; double Sprd=Close[1]-Open[1];
                if (Sprd > Open[1]-SMA_5)
                Here is also another simpler form that did not work on bar close

                Code:
                        protected override void OnBarUpdate()
                        {
                            if (State == State.Historical)
                                return;
                            if (CurrentBar == Count-1)
                            {
                                Print(CurrentBar+Instrument.FullName);
                            myInstrument = Instrument.GetInstrument(Instrument.FullName);
                            if (Close[0] > 0 & orderSubmitted == false && myAccount != null)
                
                                {
                
                                if (Volume[0] > Volume [1])
                                    {
                                    entryOrder = myAccount.CreateOrder(myInstrument, OrderAction.Buy, OrderType.Market, TimeInForce.Gtc, 1, 0, 0, null, "Entry", null);
                                    Print(myInstrument + " entryOrder created");
                                    NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("myAtmStrategy", entryOrder);
                                    orderSubmitted = true;
                                    Print(myInstrument + " StartAtmStrategy");
                                    }
                
                                }
                            if (orderSubmitted == false)
                                OrderSubmitted[0] = 0;
                            else
                                OrderSubmitted[0] = 1;
                            }
                        }
                Any advice?

                Also when I set it to 'On price change' the order is triggered, but in a subsequent bar when the condition is met again, the order is not triggered. Would you please let me know how to deal with this?
                Thanks in advance.​

                Comment


                  #9
                  Hello MSerag,

                  Thank you for your reply.

                  I suspect this is why the logic is not triggered when the indicator is set to calculate On Bar Close:
                  if (CurrentBar == Count-1)

                  As mentioned on the help guide page, CurrentBar is guaranteed to be less than or equal to Count -1. It won't always be equal to Count - 1, and if you add Print() statements that print the value for CurrentBar and Count - 1 you will see the difference. I tested on an indicator and changed between On Bar Close and On Price Change and noted the different values.

                  Here is the help guide page for Count:


                  You will need to adjust this condition or remove it if it is not needed, as your script is already set to only calculate in real-time since if the state is historical it will return.

                  As for the order only being triggered once, are you resetting the bool orderSubmitted at any point? Once orderSubmitted is true, your script won't get past the following point unless it is set back to false:

                  if (Close[0] > 0 & orderSubmitted == false && myAccount != null)

                  Thank you for your patience. Please let me know if I may be of further assistance.
                  Emily C.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Emily, I appreciate your detailed response. After removing
                    Code:
                    if (CurrentBar == Count-1)
                    I get the following error and still, the order is not triggered
                    Code:
                    Indicator 'TestSubmit on 1 Minute data': Error on calling 'OnBarUpdate' method on bar 0: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.
                    ​
                    In addition and in most strategies you need to partially access the historical data to do some calculations. So one would need to do the calculations as the current bar closes while getting the data from the recent bars. If this is of value, please note that I work on volumetric bars, not normal bars.
                    Would you please continue your kind help?
                    Thanks for Ninjatrader's elite support.

                    Comment


                      #11
                      Hello MSerag,

                      Thank you for your reply.

                      I suspect adding a current bar check as demonstrated on this tip page might help prevent the error:


                      For example, since you are trying to access the Volume from 1 bar ago, you would need at least 2 bars in the series. You could update your first check to return if the state is historical to also include the CurrentBar check:
                      if (State == State.Historical || CurrentBar < 2)
                      return;

                      Please test out adding a CurrentBar check and let me know if I may be of further assistance.​
                      Emily C.NinjaTrader Customer Service

                      Comment


                        #12
                        Good day and thanks again. Somehow and with your advice I was able to make it work. However, it is not clear to me how can I reset the calculation after the order bar closes. I hope that you go through the below code that runs in the Market analyzer and is calculated at each tick. Normally, new orders should be disabled during the same bar as the order bar. But the order resets as the order bar closes. Because I have been in only for one year in NinjaScript, I appreciate your detailed guidance.
                        Also, although the quantity in myAtmStrategy is set at 200 shares for stocks, the simulated order places an order for only 1 share. How can I execute the quantity set in the ATM strategy? Many thanks.

                        Code:
                        protected override void OnBarUpdate()
                        {
                        if (State == State.Historical)
                        return;
                        if (CurrentBar == Count-1)
                        {
                        
                        myInstrument = Instrument.GetInstrument(Instrument.FullName);
                        if (Close[1] > 0 & orderSubmitted == false && myAccount != null)
                        
                        {
                        if (Volume[1] > Volume [2] )
                        
                        {
                        entryOrder = myAccount.CreateOrder(myInstrument, OrderAction.Buy, OrderType.Market, TimeInForce.Gtc, 1, 0, 0, null, "Entry", null);
                        Print(myInstrument + " entryOrder created");
                        NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrate gy("myAtmStrategy", entryOrder);
                        orderSubmitted = true;
                        Print(myInstrument + " StartAtmStrategy");
                        OrderSubmitted[0] = 0;
                        }
                        
                        }
                        if (orderSubmitted == false)
                        OrderSubmitted[0] = 0;
                        else
                        OrderSubmitted[0] = 1;
                        }
                        }

                        Comment


                          #13
                          Hello MSerag,

                          Thank you for your reply.

                          I am not sure what you are referring to when you say "Normally, new orders should be disabled during the same bar as the order bar. But the order resets as the order bar closes." Please describe the behavior you are experiencing vs. the desired behavior so I may better assist you.

                          As for the quantity, that is set in the CreateOrder() method:


                          The snippet you provided has the following line that creates the entryOrder:
                          entryOrder = myAccount.CreateOrder(myInstrument, OrderAction.Buy, OrderType.Market, TimeInForce.Gtc, 1, 0, 0, null, "Entry", null);

                          You may adjust the quantity, which is the bolded 1 in red, to whatever value you'd like. If you want it to be 200, you will need to adjust it to 200.

                          I look forward to your reply.
                          Emily C.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Emily,
                            I would like to clarify my request. For the simple indicator that I previously submitted (calculated at each tick), the indicator calculates and checks for a specific condition (Volume of bar no.2 > Volume of bar no.1) at the start of bar no.3. Currently, bar no.1 is the earliest bar, and bar no.3 is the most recent.

                            I need the indicator to trigger an order only once per bar, so if the condition is met during bar no.3, it should not trigger the order again until the start of bar no.4. At this point, it should trigger the order again if Volume of bar no.3 > Volume of bar no.2. Furthermore, I need the indicator to be able to trigger simultaneously across multiple instruments in the Market Analyzer if the condition is met.
                            ​Thank you for your support.

                            Comment


                              #15
                              Hello MSerag,

                              Thank you for that info.

                              For actions that you want to occur on the start of a bar, you may still have the indicator calculated at each tick and then utilize IsFirstTickOfBar as part of your conditions:


                              If you want an order only once per bar, you could have the bool orderSubmitted set to true so that an order is only submitted once on that bar, then if IsFirstTickOfBar is true you can set the bool back to false to allow the script to check if the other entry conditions also become true again.

                              I recommend that you continue utilizing and adding Print() statements to your script as you are working on it in order to better understand the behavior of your script and fine-tune it so that it behaves in the way you'd like. For more information about using prints:


                              The sample I provided was meant to demonstrate how to submit orders via an indicator and get you started on developing your indicator. We do not provide C# programming education services or one-on-one educational support in our NinjaScript Support department. This is so that we can maintain a high level of service for all of our clients as well as our associates. We are happy to answer any questions you may have about NinjaScript if you decide to continue to code this yourself. We are also happy to assist with finding resources in our help guide as well as simple examples, and we are happy to assist with guiding you through the debugging process to assist you with understanding unexpected behavior.

                              If you have any specific questions about certain methods or properties, please let us know. Additionally, if your script is not behaving in the way you'd expect, please explain the details of how it is behaving vs. how you would like it to behave and as previously mentioned we can guide you through the debugging process to help determine what part or parts of your script may need to be tweaked in order to achieve your desired outcome.

                              Thank you for your time and patience. Please let us know if we may be of further assistance.
                              Emily C.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by trilliantrader, Today, 08:16 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post trilliantrader  
                              Started by AttiM, 02-14-2024, 05:20 PM
                              9 responses
                              174 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by funk10101, Today, 08:14 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post funk10101  
                              Started by adeelshahzad, Today, 03:54 AM
                              1 response
                              13 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by RookieTrader, Today, 07:41 AM
                              1 response
                              6 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Working...
                              X