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

I really don't know how limit orders worked!

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

    I really don't know how limit orders worked!

    Didn't the limitPrice in EnterLongLimit and EnterShortLimit means the target price in which the order going to be executed!?

    If the price didn't reach the target, shouldn't the order never be placed!?

    I tried to EnterShortLimit right after EnterLongLimit. But the output showed me only the long trade. I thought it's because the limitPrice was set too low! I then rise the limitPrice to some ridiculous number such as High[0]+2000000*TickSize. So theoretically the long order should never be placed!

    And what do you know!? The output from the chart was STILL the long order!!!

    What's going on here!?!?!? Could somebody explain it for me PLEASE!?

    Thank you very VERY much for your help! God bless you!!!

    #2
    Hello YoutingChu,

    To confirm, you are entering a long position with EnterLongLimit() and then attempting to flip the position from long to short with an EnterShortLimit() called on a later bar, is this correct?

    Are you ensuring that the Position.MarketPosition is MarketPosition.Long before allowing the EnterShortLimit to be called?

    Set TraceOrders to true in State.Configure and re-run the script. Are there are orders being ignored or other messages appearing in the output window?
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      No... I just want to understand how those orders worked! And how OnOrderUpdate and OnExecutionUpdate respond to them!

      I thought the orders will be always there until canceled! Take my post as an example, shouldn't both long and short orders pending over there!? Even though the long order was placed first, when the market comes down and hit the limitPrice in short order, shouldn't the short order be placed also right away!?

      But it seems like once the long order was placed, any other orders are ignored and canceled!

      And if the long order was never placed, shouldn't the next available order (short) kicks in!?

      What's even more crazy is, the long order will still be placed no matter how ridiculously high I set my limitPrice at!!!

      I'm REALLY at lost here! I have ABSOLUTELY no idea how those things works!!!

      PLEASE be so kind and help me out!!! God bless you!!!

      PS. I'm currently at work now, so I'm afraid i can not test it out as you instructed! Sorry!

      Comment


        #4
        Originally posted by YoutingChu View Post
        No... I just want to understand how those orders worked! And how OnOrderUpdate and OnExecutionUpdate respond to them!

        I thought the orders will be always there until canceled!
        No. If that is what you want, then you have to explicitly code it that way.

        ref: https://ninjatrader.com/support/help...ders_alive.htm
        Take my post as an example, shouldn't both long and short orders pending over there!? Even though the long order was placed first, when the market comes down and hit the limitPrice in short order, shouldn't the short order be placed also right away!?

        But it seems like once the long order was placed, any other orders are ignored and canceled!
        Yes, that is documented.

        ref: https://ninjatrader.com/support/help...d_approach.htm
        And if the long order was never placed, shouldn't the next available order (short) kicks in!?
        Yes. But is that really what you coded, or is that just what you think that you coded?
        What's even more crazy is, the long order will still be placed no matter how ridiculously high I set my limitPrice at!!!
        Of course. That is what a Limit Order is supposed to do. A Limit Order will fill at the stated price or better. If you state a really high price, then of course, just about every price will be better and so fill.
        I'm REALLY at lost here! I have ABSOLUTELY no idea how those things works!!!

        PLEASE be so kind and help me out!!! God bless you!!!

        PS. I'm currently at work now, so I'm afraid i can not test it out as you instructed! Sorry!

        Comment


          #5
          Hello YoutingChu,

          No, a second method to enter in the opposite direction cannot be used while an entry method is active (meaning working or accepted).

          From the help guide:
          Methods that generate orders to enter a position will be ignored if:
          The strategy position is flat and an order submitted by an enter method (EnterLongLimit() for example) is active and the order is used to open a position in the opposite direction

          Below is a public link to the help guide.


          If you are trying to bracket the market price with two entry orders, you will need to use the unmanaged approach.

          Below is a public link to an example.
          Support for the development of custom automated trading strategies using NinjaScript.



          The Enter methods like EnterLongLimit / EnterShortStop, etc, are meant to flip your position from long to short or short to long.


          Orders will not remain alive until cancelled unless submitted with the isLiveUntilCancelled bool as true or they are resubmitted.

          Below is a public link to a forum post on isLiveUntilCancelled.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Dear Chelsea,

            Thank you very much for your great sample codes!

            But when I tried to run your code, the whole thing stopped at Exit on session close! All the bars after that have absolutely no trades!!!

            Could you teach me how to fix that, please!? Appreciated!
            Last edited by YoutingChu; 07-16-2018, 08:22 PM.

            Comment


              #7
              Dear koganam,

              Thank you very much for your answer!

              But I have one question:

              Originally posted by koganam View Post
              Of course. That is what a Limit Order is supposed to do. A Limit Order will fill at the stated price or better. If you state a really high price, then of course, just about every price will be better and so fill.
              In the case of long orders, shouldn't "fill at the stated price or better" means the prices higher then the limitPrice you set!? So when I set my limitPrice ridiculously high, shouldn't the market price never be able to get higher than that therefore the order should never be placed!? Did I misunderstand what limitPrice is!?

              Comment


                #8
                Originally posted by YoutingChu View Post
                In the case of long orders, shouldn't "fill at the stated price or better" means the prices higher then the limitPrice you set!? So when I set my limitPrice ridiculously high, shouldn't the market price never be able to get higher than that therefore the order should never be placed!?
                No, this is incorrect.

                Originally posted by YoutingChu View Post
                Did I misunderstand what limitPrice is!?
                Yes.

                For Long entries, the LimitPrice means the maximum price you're willing to pay (to buy). Thus the 'stated price or better' means your order will be filled at your LimitPrice, or at any price lower than LimitPrice (since any price lower than your LimitPrice is considered 'better' for you when you're going long, right?).

                Ok, so when you set a LimitPrice ridiculously high when going Long, the order fills immediately because any price less than your LimitPrice is better for you when initiating your Long position. The exchange has saved you money, for ex, you told them you were willing to pay $100 per contract for 10 contracts of oil (LimitPrice=100) but the exchange found you 10 contracts at the current market price of $72.34 -- saving you money -- thus $72.34 is regarded as a better price than $100 -- get it?

                Your thinking is wrong in terms of direction.

                If you want to set up a Long entry order that never fills, use a ridiculously low LimitPrice -- because that means price will have to drop a huge amount to reach your LimitPrice, remember the LimitPrice for long entry is the maximum price you're willing to pay. For example, if oil is currently at $72.56 per contract, and you specify LimitPrice=$25 ... well, my word, price has to drop a huge amount to $25 per barrel before your LimitPrice is reached and your long order is filled. Say it with me: When going Long, LimitPrice is the maximum price you're willing to pay to buy the instrument.

                If you want to set up a Long entry order that fills immediately, use a ridiculously high LimitPrice -- because the current Market price is considered better than the LimitPrice, so you get filled instantly, remember for longs better means 'better price for your initial position', which is defined as lower than the LimitPrice.

                What's happening is: you're telling the exchange you're willing to pay a really high price (LimitPrice is the maximum you're willing to pay) to buy the instrument, but the exchange fills you immediately under the implicit assumption it found you a lower price (and therefore a better price) than that lofty amount you were willing to pay ... the idea is that 'better' means 'saves you money'.

                When going short, LimitPrice is the minimum price you're willing to sell. So, selling short is a slightly different discussion, which you should be able to infer yourself. The explanations are analogous to each other.
                Last edited by bltdavid; 07-16-2018, 09:45 PM.

                Comment


                  #9
                  Originally posted by YoutingChu View Post
                  Dear Chelsea,

                  Thank you very much for your great sample codes!

                  But when I tried to run your code, the whole thing stopped at Exit on session close! All the bars after that have absolutely no trades!!!

                  Could you teach me how to fix that, please!? Appreciated!
                  The issue is that the Order variables were not being set to null when the exit on close is triggered. I've corrected the scripts and re-uploaded.

                  Support for the development of custom automated trading strategies using NinjaScript.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Dear Chelsea,

                    Thank you very much for your code.

                    I tried to modify it so I can flip positions if it hit the StopLoss using EnterLong and EnterShort. But it told me some objects are not assigned and crash the whole program!

                    Could you please be so kind and teach me how to properly flip the positions please!?

                    I'm sorry for bugging you so much! Thank you very VERY much for your help! God bless you!!!

                    Comment


                      #11
                      Hello YoutingChu,

                      Attached is a very simple script that demonstrates checking the position to be long and then changing the reversing the position using limit orders with a valid limit price using the managed approach.


                      If you want to detect when an exit order has filled, detect the signal name of the order in OnExecution or OnOrderUpdate. Then trigger an action such as setting a bool or submitting a new order.

                      Below is a link to an example that demonstrates trailing a stop that resets all variables to null once the stop order has filled (and the target is cancelled or the target is filled and the stop is cancelled).
                      Attached Files
                      Last edited by NinjaTrader_ChelseaB; 07-18-2018, 08:53 AM.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Dear Chelsea,

                        Thank you very much for your code.

                        But can you teach me how to flip position in YOUR CODE please!?

                        Because I find out you can NOT use EnterLong or EnterShort in a unmanaged strategies. And if I just use SubmitOrderUnmanaged, it just buy me EXTRA ORDERS!!! So the whole strategy actually become a chaos!!!

                        So could you PLEASE be so kind and teach me how do I flip position in your strategy, please!?

                        Thank you very VERY much! God bless you!!!

                        Comment


                          #13
                          Hello YoutingChu,

                          The example I have provided is to demonstrate basic concepts like creating a new OCO string for each entry pair and assigning order objects to order variables from OnOrderUpdate.

                          The managed approach is reserved for advanced programmers. Your inquiry is about how to write the logic to reverse a position.

                          Unfortunately, in the support department at NinjaTrader it is against our policy to create, debug, or modify, custom code or logic for our clients. This is so that we can maintain a high level of service for all of our clients as well as our partners.

                          That said, I am happy to answer any questions you may have about NinjaScript if you decide to code this yourself.

                          This thread will also remain open for any community members that would like to build you this custom script as a conveience to you.

                          You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like our business development follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request.


                          That said, the concept is similar to the example I have posted. You can use a variable to know when to flip the position after the position is taken.
                          When the position is flipped place a sell order instead of a buy order and vice versa. Ensure the protective exit orders are buy orders and are placed at valid prices.

                          I was able to find another example of the forum you may find helpful.
                          Last edited by NinjaTrader_ChelseaB; 07-23-2018, 11:02 AM.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #14
                            I've got an idea. How about you post your code and let the forum help you?


                            We've got no idea what you've actually coded, and therefore can't help you.


                            I have to assume you actually DO have all the proper code to complete the operation, and if that's the case then a called object not being assigned at the right time is due to an order of operations issue. Remember, all code is executed from top to bottom and left to right inside of a code block (such as OnBarUpdate or OnExecutionUpdate).


                            Also, yes, it seems you have misunderstood the concept of a limit order. A long limit order will clear at any price up to and including the limit price. A short limit order will execute at any price above and including the limit price.


                            A little independent research on the help page and/or in the forum would probably help you better than asking questions without providing any information.


                            If I were you, I would do something like this, but I can't promise this will work because I don't know how the rest of your code works:


                            Code:
                            private string stopaction
                            
                            ......................................
                            
                            protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                            {
                            if (execution.OrderAction == OrderAction.Sell)
                            {
                            
                            stopaction = execution.OrderAction
                            }
                            if (execution.OrderAction == OrderAction.BuyToCover
                            {
                            stopaction = execution.OrderAction
                            }
                            
                            
                            protected override void OnBarUpdate
                            {
                            
                            
                            if (BarsSinceExitExecution == 0
                            && stopaction == OrderAction.BuyToCover)
                            {
                            EnterLong(etc. etc.)
                            if (BarsSinceExitExecution("Stop loss") == 0
                            && stopaction == OrderAction.Sell)
                            {
                            EnterShort(etc etc)
                            }
                             }
                            Note this code MUST BE RUN OnEachTick if the strategy is intended to flip immediately.
                            Last edited by liquid150; 07-24-2018, 06:33 AM.

                            Comment


                              #15
                              Dear liquid150,

                              Thank you very much for your help!

                              This is a snippet from Chelsea's code, due to the size of the code, I'm not going to paste the whole code, if you want to see the whole code, please download it from here.

                              protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity,
                              Cbi.MarketPosition marketPosition, string orderId, DateTime time)
                              {
                              try
                              {
                              if (longStopEntry != null && execution.Order == longStopEntry)
                              {
                              ocoString = string.Format("unmanageexitdoco{0}", DateTime.Now.ToString("hhmmssffff"));
                              SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit, 1, (High[0] + 10*P * TickSize), 0, ocoString, "longProfitTarget");
                              SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket, 1, 0, (Low[0] - 10*S * TickSize), ocoString, "longStopLoss");
                              }
                              else if (shortStopEntry != null && execution.Order == shortStopEntry)
                              {
                              ocoString = string.Format("unmanageexitdoco{0}", DateTime.Now.ToString("hhmmssffff"));
                              SubmitOrderUnmanaged(0, OrderAction.BuyToCover, OrderType.Limit, 1, (Low[0] - 10*P * TickSize), 0, ocoString, "shortProfitTarget");
                              SubmitOrderUnmanaged(0, OrderAction.BuyToCover, OrderType.StopMarket, 1, 0, (High[0] + 10*S * TickSize), ocoString, "shortStopLoss");
                              }
                              else if (execution.Name == "longProfitTarget" || execution.Name == "longStopLoss" || execution.Name == "shortProfitTarget" || execution.Name == "shortStopLoss")
                              {
                              longStopEntry = null;
                              shortStopEntry = null;
                              if( execution.Name == "longStopLoss") SubmitOrderUnmanaged(0, OrderAction.SellShort, OrderType.Limit, 1, (Low[0] - 500 * TickSize), 0, DateTime.Now.ToString("hhmmssffff"), "longStopEntry");
                              if(execution.Name == "shortStopLoss") SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Limit, 1, (High[0] + 500 * TickSize), 0, DateTime.Now.ToString("hhmmssffff"), "shortStopEntry");

                              }
                              }
                              catch(Exception e)
                              {
                              Print("OnExcutionUpdate: "+e.Message);
                              }
                              }
                              I had added the bold part in the OnExecutionUpdate. The idea is if the StopLoss orders are executed, then enter an opposite order. But it actually buy me extra orders!!!
                              And if I just use EnterLong or EnterShort, it just crash the whole program!!!

                              I have NO~ idea what do I miss! I had a feeling that it might be because the execution of OnExecutionUpdate and OnOrderUpdate are mingled! But I have no idea how to fix it!!!

                              PLEASE be so kind and teach me, thank you very VERY much! God bless you!!!
                              Last edited by YoutingChu; 07-26-2018, 12:47 AM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by maybeimnotrader, Today, 05:46 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post maybeimnotrader  
                              Started by quantismo, Today, 05:13 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post quantismo  
                              Started by AttiM, 02-14-2024, 05:20 PM
                              8 responses
                              166 views
                              0 likes
                              Last Post jeronymite  
                              Started by cre8able, Today, 04:22 PM
                              0 responses
                              8 views
                              0 likes
                              Last Post cre8able  
                              Started by RichStudent, Today, 04:21 PM
                              0 responses
                              5 views
                              0 likes
                              Last Post RichStudent  
                              Working...
                              X