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

Can I set the order ATM Order Quantity from AtmStrategyCreate()???

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

    Can I set the order ATM Order Quantity from AtmStrategyCreate()???

    QUESTION: How to set the number of shares when calling Strategy.AtmStrategyCreate()??


    My understanding is that I need to use Atm strategies in order to place orders in my strategy because....

    ** #1. I get errors with EnterShortStopLimit(quantity, orderPrice, orderPrice + (DefaultStopTicks * TickSize), ...

    Specifically, "Sell stop or sell stop limit orders can't be placed above the market."

    Everything works with the atm strategy and AtmStrategyCreate() because I only specify the limit order price and all is good with the stop riding nicely in the atm strategy.


    ** #2. Orders placed with EnterLongLimit() are placed with targets but I can't edit the targets by hand with chart trader and I need flexibility. I tried SubmitOrderUnmanaged() but it didn't work on the first pass and requires more investigation.


    ** #3. I want to set the number of shares because I want to calculate how much margin I have left so that I don't try to place an order that's past my limits.

    Code:
    int maxQuantity = (int)(double)Math.Floor(Strategy.Account.Get(AccountItem.[B]ExcessInitialMargin[/B], Currency.UsDollar) / Strategy.MarginEntryRequirement);
    
    int quantity = Math.Min(Strategy.DefaultQuantity, maxQuantity);

    ** #4. I also want to use the same strategy for 5 different markets and change the share price (and maybe stop amounts) on the fly.

    The problem is that the number of shares is set and fixed in the strategy.


    Thanks in advance for any comments or suggestions or other ways to do any part of this.

    I mentioned 4 different apis that I tried....
    • AtmStrategyCreate
    • EnterShortStopLimit
    • EnterLongLimit
    • SubmitOrderUnmanaged

    #2
    Hello ntdev,

    With AtmStrategyCreate you cannot set the number of shares. That system is pretty limited and can only start ATM strategies and get basic info about them while their are running. You could look at using the addon framework and its StartATMStrategy method which takes an Order object. That would allow for a entry quantity to be specified with the order but does not work with any of the strategy based ATM methods. You would need to see the addon section of the help guide: https://ninjatrader.com/support/help...tmstrategy.htm

    #1 You don't specifically need to use the ATM system to submit orders, it seems that from the error you just created an invalid price for the type of order being submitted.

    #2.Generally if you need to work with orders manually you would need to use the addon framework to observe the account directly. Strategies are a really only good at watching events they make, they are not looking for any manual changes to happen with the orders. You can add something like custom buttons to the strategy if you wanted to have the strategy update the order in some way.

    #3, I am not certain I understand the question here. Are you asking about a part of the code in the code block?


    #4, there are various ways to make parameters able to be changed while the script runs. You would generally need to look at using a custom button or other WPF element to change a variable. https://ninjatrader.com/support/help...ub=usercontrol

    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Thanks Jesse. You've got me 90% of the way there but StartATMStrategy isn't working exactly for me. Maybe I'm doing something wrong?

      I have done so many iterations that I've now confused myself but I thought that the code below was working but these are my current issues with it.


      New #5. Stop and Target for CustomAtm1 (below) are not being added to the order.

      It seems pretty straight forward... Do you see anything that I'm doing wrong? Or can you point me to a working example?
      • order1 = Account.CreateOrder(....
      • atm1 = new CustomAtm1(....
      • AtmStrategy.StartAtmStrategy(atm1, order1);

      I can inspect the atm in the Visual Studio debugger and everything looks good. Also, it's taking the order count from Account.CreateOrder().

      Maybe I shouldn't be trying to set the stop and target by creating a Bracket? But this is what the object looked like when I paused and inspected the ATM strategy that was created with the UI.

      Maybe I needed to override the Name property in CustomAtm1?

      I'm lost.


      New #6. CustomAtm1 is not being hooked to the strategy so the strategy thinks that it's flat.

      ?? Is there a way to hook the atm and order to the strategy??

      Answers to the previous dialog below....

      Originally posted by NinjaTrader_Jesse View Post
      You could look at using the addon framework and its StartATMStrategy method which takes an Order object. That would allow for a entry quantity to be specified with the order but does not work with any of the strategy based ATM methods.
      Cool. I derived from AtmStrategy and set all the parameters.

      Code:
      public class CustomAtm1 : AtmStrategy
      {
          public CustomAtm1()
          {
          }
          public CustomAtm1(string atmId, double tickSize, int contracts = 10, int stopTicks = 15, int profitTicks = 100)
          {
              UseStopLimitForStopLossOrders = false;
              ModifyNearestBracket = true;
              UseMitForProfit = false;
              // OnBehalfOf = "";
              ReverseAtStopStrategyId = -1;
              ReverseAtTargetStrategyId = -1;
              ShadowStrategyStrategyId = -1;
              ShadowTemplate = "";
              AtmSelector = atmId; // GetAtmStrategyUniqueId();
              CalculationMode = CalculationMode.Ticks;
              Bracket br1 = new Bracket() { Quantity = contracts, StopLoss = stopTicks, Target = profitTicks /* , StopStrategy = null */ };
              Brackets = new Bracket[] { br1 };
              // public override string DisplayName { get; }
              EntryQuantity = contracts;
              // public Order InitialEntryOrder { get; }
              InitialTickSize = tickSize;
              IsChase = false;
              IsChaseIfTouched = IsChase = false;
              IsTargetChase = IsChase = false;
              ReverseAtStop = IsChase = false;
              ReverseAtTarget = false;
              ChaseLimit = 0;
              // ModifyInnerBracket = true;
              StopTargetHandling = StopTargetHandling.PerEntryExecution;
          }
      }
      Then I used it like this...

      Code:
      d.ActiveOrder = Account.CreateOrder(Instrument,
          OrderAction.SellShort,
          OrderType.Limit,    // DOES NOT WORK: OrderType.StopLimit,
          OrderEntry.Manual, TimeInForce.Gtc, quantity,
          orderPrice,
          0,          // DOES NOT WORK stopPrice,
          null,
          "Entry", Core.Globals.MaxDate, null
      );
      CustomAtm1 atm1 = new CustomAtm1(GetAtmStrategyUniqueId(), TickSize, quantity, DefaultStopTicks, DefaultProfitTargetTicks);
      
      d.ActiveAtmStrategy = AtmStrategy.StartAtmStrategy(atm1, d.ActiveOrder);
      
      //Account.Submit(new[] { d.ActiveOrder });
      EDIT: The order is placed and stops can be manually added & moved in the chart trader but the target and stops are missing.

      Originally posted by NinjaTrader_Jesse View Post
      #1 You don't specifically need to use the ATM system to submit orders, it seems that from the error you just created an invalid price for the type of order being submitted.
      If that's true then I don't understand why because specifying a stop price at the same time that I place the order returns the error I mentioned earlier.

      Here's an example: (valid as far as I can see -- sell short at $1869 with a stop $2 / 20 ticks above) -- the last trade was $1869.2 with bid/ask jumping all around -- yes, they can be 50 ticks apart in very fast moving times.

      2020-12-09 07:44:06:823 (Playback Connection) Cbi.Account.OrderUpdateCallback: realOrderState=Rejected orderId='9d285ef30266479b9e36dec02aa3a935' account='Playback101' name='23' orderState=Rejected instrument='GC 02-21' orderAction=SellShort limitPrice=1869 stopPrice=1871 quantity=4 orderType='Stop Limit' filled=0 averageFillPrice=0 time='2020-12-09 03:40:48' statementDate='2020-12-09' error=OrderRejected comment='Sell stop or sell stop limit orders can't be placed above the market.' nr=-1
      I don't have the "years" of experience that this angry guy has but I think that he's explaining the same issue...

      https://ninjatrader.com/support/foru...t-get-rejected

      ?? Maybe the ATM works differently? Is the stop order sitting at the broker or is it not triggered until my NT workstation sees that it was triggered then it places a Market order???

      Would that mean that I won't get stopped out if I lose my internet connection?

      ** Looking at the order history, it looks like this is what's happening but I'd love to get confirmation on that one.


      #3, I am not certain I understand the question here. Are you asking about a part of the code in the code block?
      I was just giving an example of calculating how many contracts that I can buy based on my available margin.

      The reason that I pointed this out is because it seems like a common thing to do so I was wonder if there was a built-in facility to handle lowering the number of shares if you don't have enough money to place the order.
      Last edited by ntdev; 12-11-2020, 12:17 AM.

      Comment


        #4
        Originally posted by ntdev View Post
        I get errors with EnterShortStopLimit(quantity, orderPrice, orderPrice + (DefaultStopTicks * TickSize), ...

        Specifically, "Sell stop or sell stop limit orders can't be placed above the market."
        Can you attach a small fully-working example script that illustrates your problem?

        Comment


          #5
          Hello ntdev,

          New #5. Stop and Target for CustomAtm1 (below) are not being added to the order.

          It seems pretty straight forward... Do you see anything that I'm doing wrong? Or can you point me to a working example?
          • order1 = Account.CreateOrder(....
          • atm1 = new CustomAtm1(....
          • AtmStrategy.StartAtmStrategy(atm1, order1);
          Please clarify the problem here. What specifically is happening? You submit the ATM and the targets defined in the ATM template are not being submitted?

          New #6. CustomAtm1 is not being hooked to the strategy so the strategy thinks that it's flat.

          ?? Is there a way to hook the atm and order to the strategy??
          See my next comment.

          Cool. I derived from AtmStrategy and set all the parameters.
          Creating an ATM object directly is not something we have any documentation for so I am not aware if that would work correctly or what properties would need set. That overload is intended for use with the WPF ATM selector control, theres an example of that in the following page: https://ninjatrader.com/support/help...ub=AtmStrategy
          Code:
          AtmStrategy selectedAtmStrategy = args.AddedItems[0] as AtmStrategy;
          The addon ATM method is otherwise intended to load an ATM template by name and use the platforms built in mechanism for loading it and creating the AtmStrategy object. I would suggest to create an ATM using the chart trader or superdom and then test using the platforms normal loading. If you see that not working correctly I would likely need a very simple example that demonstrates the problem and the associated .xml atm template file.

          ?? Maybe the ATM works differently? Is the stop order sitting at the broker or is it not triggered until my NT workstation sees that it was triggered then it places a Market order???
          I am not certain what you are asking here in relation to where the stop order resides but the error you received is from playback and based on the prices used with the order type.

          A sell stop limit type order can't be placed above the market. The playback simulation had seen the order price was not valid for the order type at the time of submission. You would get a similar rejection if you placed an order with an invalid price to a realtime broker.



          I look forward to being of further assistance.
          JesseNinjaTrader Customer Service

          Comment


            #6
            Thank you both for the help and for pointing me in the right direction.

            The bottom line was that I was unable to build an AtmStrategy on the fly, populate the object and then have it be controlled by my strategy so that I could override the callbacks to implement my desired behavior. [Yes, I know, undocumented...]

            New Approach: unmanaged orders

            SO.... I ended up coding everything by hand using SubmitOrderUnmanaged() and then after some part of the order is filled I create and/or update the bracket orders manually in my OnExecutionUpdate() callback.

            Code:
            protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity,
            Cbi.MarketPosition marketPosition, string orderId, DateTime time)
            ...
            SubmitOrderUnmanaged(0,
            d.IsShortTrade ? OrderAction.BuyToCover : OrderAction.Sell,
            OrderType.StopMarket,
            d.CurrentOpenContracts, 0, stopPrice, newOcoName, d.GetStoplossName());
            
            SubmitOrderUnmanaged(0,
            d.IsShortTrade ? OrderAction.BuyToCover : OrderAction.Sell,
            OrderType.Limit,
            d.CurrentOpenContracts, targetPrice, 0, newOcoName, d.GetTargetName());
            -----------

            It is mostly running just as I would want but there are some limitations of using unmanaged orders (hopefully because of my level of understanding).

            (I leave my questions in the same thread but they are unrelated to the original topic)

            ISSUE #10... Changing the chart scale kills my bracket orders and disables my strategy.

            ChelseaB - I have read your posts about using StartBehavior.ImmediatelySubmitSynchronizeAccount but I don't think that applies to my case.

            REPRO: If I'm in the middle of trade (open position) that was entered by my strategy then changing the chart scale from 5 minutes to 1 minute will leave my order open and remove the bracket orders that I created.

            Side Concern #10.1 - what if the strategy crashes? will it leave me in a long position without a stop?

            >> QUESTION #11. Is there a way or a right way to keep my strategy running in this case where there was an open position and the user changed the bar scale?

            The list of orders in the Strategy object is still valid so I could rebuild my bracket orders but the strategy is disabled at this point.

            I also see "Syncing account position on starting strategy" in the debugging log.

            Maybe I missed something in my implementation -- I actually don't start placing any SubmitOrderUnmanaged orders until I'm realtime -- maybe I was supposed to be making this call while reprocessing Historical data?


            >> QUESTION #12. Maybe you have an example of using history with SubmitOrderUnmanaged?

            [For me, I just used the historical data to make calculations but didn't act (call SubmitOrderUnmanaged) until there was a point to it.]

            Comment


              #7
              Hello ntdev,

              ISSUE #10... Changing the chart scale kills my bracket orders and disables my strategy.

              ChelseaB - I have read your posts about using StartBehavior.ImmediatelySubmitSynchronizeAccount but I don't think that applies to my case.

              REPRO: If I'm in the middle of trade (open position) that was entered by my strategy then changing the chart scale from 5 minutes to 1 minute will leave my order open and remove the bracket orders that I created.
              Right, in this case you are not just changing the scale but the underlying DataSeries which the strategy is attached to. If you want to avoid that you need to either apply the strategy in a different chart which will not be changed or use the control center strategies tab to apply it in the background. The Start Behavior would be related here because its used when restarting the strategy on the new timeframe. It would also be likely that with the change of the series that will alter the overall outcome preventing it from retaining orders or syncing positions and also may lead to cancelled orders.


              Side Concern #10.1 - what if the strategy crashes? will it leave me in a long position without a stop?
              If your code has an error which disabled the strategy then yes that would leave any positions or open orders in place. We always suggest to monitor the strategy when being used to ensure it is working properly while live trading. Testing the scripts you create in all the situations you use then to ensure they operate normally is a crucial step.



              >> QUESTION #11. Is there a way or a right way to keep my strategy running in this case where there was an open position and the user changed the bar scale?
              I believe that was answered above, either a secondary chart could be used or apply the strategy to the control center instead. When you change the data series from the chart that will reload any indicators or strategies applied there to use that new series. With strategies that will affect it by recalculating the indicators and historical backtest. That may lead to different positions or orders being submitted which contradict what you had going on previously.


              >> QUESTION #12. Maybe you have an example of using history with SubmitOrderUnmanaged?
              You could try the samples listed in the following post, I see that works historically: https://ninjatrader.com/support/foru...ing#post802269



              I look forward to being of further assistance.
              JesseNinjaTrader Customer Service

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by bmartz, 03-12-2024, 06:12 AM
              4 responses
              32 views
              0 likes
              Last Post bmartz
              by bmartz
               
              Started by Aviram Y, Today, 05:29 AM
              4 responses
              12 views
              0 likes
              Last Post Aviram Y  
              Started by algospoke, 04-17-2024, 06:40 PM
              3 responses
              28 views
              0 likes
              Last Post NinjaTrader_Jesse  
              Started by gentlebenthebear, Today, 01:30 AM
              1 response
              8 views
              0 likes
              Last Post NinjaTrader_Jesse  
              Started by cls71, Today, 04:45 AM
              1 response
              7 views
              0 likes
              Last Post NinjaTrader_ChelseaB  
              Working...
              X