Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ATM strategy auto enrty

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

    ATM strategy auto enrty

    Hello,

    I would like to know if it would be possible to use an ATM strategy in ninjatrader editor, but that enters positions automatically and uses the set parameters by the user for the normal use of an ATM strategy just like tin the picture below ?
    Click image for larger version

Name:	image.png
Views:	321
Size:	36.7 KB
ID:	1302362

    #2
    Hello Salahinho99,

    You can use AtmStrategy methods from a NinjaScript Strategy to submit orders with an AtmStrategy attached.

    Included with NinjaTrader is the SampleAtmStrategy with example code.

    Note, using AtmStrategy methods will not cause the Order override methods to update and this will not affect the strategy position.

    "Executions from ATM Strategies will not have an impact on the hosting NinjaScript strategy position and PnL - the NinjaScript strategy hands off the execution aspects to the ATM, thus no monitoring via the regular NinjaScript strategy methods will take place (also applies to strategy performance tracking)"

    Below is a link to the help guide on the AtmStrategy methods.

    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hey,

      Is it also possible to use a strategy X that enters positions on a certain condition and then simultaniously use the sampleATMstrategy that is provided by ninjatrader to perform on the entries ? basically will the ATMstrategy be performed on the automatic entries from my other strategy ?

      Comment


        #4
        Hello Salahinho99,

        Unfortunately, no. Your custom NinjaScript strategy has to submit the order with AtmStrategyCreate() or the Atm cannot be attached.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hey,

          How can i attach my ATM strategy that i saved to my custom entry strategy ? This is teh code i have at the moment. I saw somewhere that you can attach the atmstrategy by using the same name as the one created in the user interface which in my case is "atmstrategytemplate"


          public class ATMConcept : Strategy
          {
          private Bollinger bollinger;
          private Stochastics stochastics;
          private string atmStrategyId = string.Empty;
          private string orderId = string.Empty;
          private bool isAtmStrategyCreated = false;

          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"Enter the description for your new custom Strategy here.";
          Name = "ATMConcept";
          Calculate = Calculate.OnBarClose;
          EntriesPerDirection = 1;
          EntryHandling = EntryHandling.AllEntries;
          IsExitOnSessionCloseStrategy = true;
          ExitOnSessionCloseSeconds = 30;
          IsFillLimitOnTouch = false;
          MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
          OrderFillResolution = OrderFillResolution.Standard;
          Slippage = 0;
          StartBehavior = StartBehavior.WaitUntilFlat;
          TimeInForce = TimeInForce.Gtc;
          TraceOrders = true; // Enable order tracing for debugging
          RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
          StopTargetHandling = StopTargetHandling.PerEntryExecution;
          BarsRequiredToTrade = 20;
          IsInstantiatedOnEachOptimizationIteration = true;
          stoPeriodD = 3;
          stoPeriodK = 14;
          stoSmooth = 3;
          bbStdDev = 2;
          bbPeriod = 14;
          bfMinPct = 0;
          bfMaxPct = 100.0;
          }
          else if (State == State.Configure)
          {
          AddDataSeries("NQ JUN24", Data.BarsPeriodType.Minute, 5, Data.MarketDataType.Last);
          bollinger = Bollinger(bbStdDev, bbPeriod);
          stochastics = Stochastics(stoPeriodD, stoPeriodK, stoSmooth);
          }
          else if (State == State.DataLoaded)
          {
          AddChartIndicator(bollinger);
          AddChartIndicator(stochastics);
          }
          }

          protected override void OnBarUpdate()
          {
          // Only proceed if we are in real-time state
          if (State != State.Realtime)
          return;

          if (Position.MarketPosition == MarketPosition.Flat)
          {
          CheckEntryConditions();
          }

          // Ensure ATM strategy was created before checking other properties
          if (!isAtmStrategyCreated)
          return;

          // Check for a pending entry order
          if (!string.IsNullOrEmpty(orderId))
          {
          string[] status = GetAtmStrategyEntryOrderStatus(orderId);

          // If the status call can't find the order specified, the return array length will be zero, otherwise it will hold elements
          if (status.Length > 0)
          {
          // Print out some information about the order to the output window
          Print("Order ID: " + orderId);
          Print("The entry order average fill price is: " + status[0]);
          Print("The entry order filled amount is: " + status[1]);
          Print("The entry order order state is: " + status[2]);

          // If the order state is terminal, reset the order id value
          if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
          {
          Print("Resetting orderId because the order state is terminal: " + status[2]);
          orderId = string.Empty;
          }
          }
          }
          // If the strategy has terminated, reset the strategy id
          else if (!string.IsNullOrEmpty(atmStrategyId) && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
          {
          Print("Resetting atmStrategyId because the ATM strategy market position is flat.");
          atmStrategyId = string.Empty;
          }

          // Check if the ATM strategy ID is valid and if the strategy is active
          if (!string.IsNullOrEmpty(atmStrategyId))
          {
          // You can change the stop price
          if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
          {
          Print("Changing stop price.");
          AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
          }

          // Print some information about the strategy to the output window
          Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
          Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
          Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId)) ;
          Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId)) ;
          }
          }

          private void CheckEntryConditions()
          {
          // Ensure we have enough bars for the Bollinger Bands calculation
          if (CurrentBar < 20)
          return;




          // Entry conditions for long and short positions
          bool longEntryCondition = "some condition"

          bool shortEntryCondition = "some condition"

          if (longEntryCondition)
          {
          isAtmStrategyCreated = false; // reset atm strategy created check to false
          atmStrategyId = GetAtmStrategyUniqueId();
          orderId = GetAtmStrategyUniqueId();

          // Submit an ATM strategy order
          AtmStrategyCreate(OrderAction.Buy, OrderType.Limit, Close[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", 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;
          else
          Print("Error creating ATM strategy: " + atmCallbackErrorCode + ", ID: " + atmCallBackId);
          });

          Print(Time[0].ToString("yyyy-MM-dd HH:mm:ss") + " - ATM LONG ENTRY ORDER SUBMITTED");
          Draw.ArrowUp(this, "buySignal" + CurrentBar, false, 0, Low[0] - TickSize * 5, Brushes.Green);
          }

          if (shortEntryCondition)
          {
          isAtmStrategyCreated = false; // reset atm strategy created check to false
          atmStrategyId = GetAtmStrategyUniqueId();
          orderId = GetAtmStrategyUniqueId();

          // Submit an ATM strategy order
          AtmStrategyCreate(OrderAction.Sell, OrderType.Limit, Close[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", 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;
          else
          Print("Error creating ATM strategy: " + atmCallbackErrorCode + ", ID: " + atmCallBackId);
          });

          Print(Time[0].ToString("yyyy-MM-dd HH:mm:ss") + " - ATM SHORT ENTRY ORDER SUBMITTED");
          Draw.ArrowDown(this, "sellSignal" + CurrentBar, false, 0, High[0] + TickSize * 5, Brushes.Red);
          }
          }

          [NinjaScriptProperty]
          [Display(Name = "Number of Std Deviations", Description = "", Order = 10, GroupName = "Bollinger")]
          public double bbStdDev { get; set; }

          [NinjaScriptProperty]
          [Display(Name = "Period", Description = "", Order = 20, GroupName = "Bollinger")]
          public int bbPeriod { get; set; }

          [NinjaScriptProperty]
          [Display(Name = "Period D", Description = "", Order = 10, GroupName = "Stochastics")]
          public int stoPeriodD { get; set; }

          [NinjaScriptProperty]
          [Display(Name = "Period K", Description = "", Order = 20, GroupName = "Stochastics")]
          public int stoPeriodK { get; set; }

          [NinjaScriptProperty]
          [Display(Name = "Smooth", Description = "", Order = 30, GroupName = "Stochastics")]
          public int stoSmooth { get; set; }

          [NinjaScriptProperty]
          [Display(Name = "Backfill minimum percentage", Description = "", Order = 30, GroupName = "Backfill percentage")]
          public double bfMinPct { get; set; }

          [NinjaScriptProperty]
          [Display(Name = "Backfill maximum percentage", Description = "", Order = 30, GroupName = "Backfill percentage")]
          public double bfMaxPct { get; set; }
          }



          this what i have in my user interface

          Click image for larger version

Name:	image.png
Views:	433
Size:	137.9 KB
ID:	1302987

          Comment


            #6
            Hello Salahinho99,

            That is correct, call AtmStrategyCreate() with the name of the Atm template as it appears in the Atm templates window as the string strategyTemplateName parameter. (This string will be case sensitive)
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7

              Hey Chelsea,

              When using the code you sent, the first order is processing, but it doesn't seem to be utilizing the saved string "AtmStrategyTemplate". In picture one, you can see that the stop loss is being placed based on the atmStrategyCreate method, not the ATM strategy template I saved in the user interface. It appears to be creating new ATM strategy templates, despite having my own saved template, as shown in the dropdown. The last one in the list is the one I saved manually.

              If I understood you correctly, it should be possible to attach my saved template to the code using the atmStrategyCreate method with the exact same name as the manually saved template as parameter. Have I done something wrong, or am I missing something in the code above? Could you help me with this? I can't find any information on how to attach the ATM strategy to my custom entry strategy. I have also put the prints i got below.

              Thanks ! ​

              picture 1:
              Click image for larger version

Name:	image.png
Views:	312
Size:	128.4 KB
ID:	1303316

              Manually saved atm strategy:
              Click image for larger version

Name:	image.png
Views:	277
Size:	18.1 KB
ID:	1303317


              This is the print i got:
              Submitting ATM SHORT ENTRY ORDER with Template: AtmStrategyTemplate
              2024-05-06 21:55:00 - ATM SHORT ENTRY ORDER SUBMITTED
              Order ID: a52988904c424b8e983aed300ba1c514
              The entry order average fill price is: 0
              The entry order filled amount is: 0
              The entry order order state is: Working
              The current ATM Strategy market position is: Flat
              The current ATM Strategy position quantity is: 0
              The current ATM Strategy average price is: 0
              The current ATM Strategy Unrealized PnL is: 0​

              ​​

              Comment


                #8
                Hey chelsea,

                One more question, could it be possible to find the code of the saved ATM strategy i made ?
                Because in that strategy i added trailing, a breakeven + the stoploss but when i look in the documentation i cannot find how to add trailing or brekaeven to the atm strategy create method

                Comment


                  #9
                  Hello Salahinho99,

                  AtmStrategyCreate() will be using the settings saved in the template file.

                  Below is a link to a video that demonstrates.



                  "One more question, could it be possible to find the code of the saved ATM strategy i made ?"

                  Atm templates are saved in .xml text files. These are located in Documents\NinjaTrader 8\templates\AtmStrategy


                  "Because in that strategy i added trailing, a breakeven + the stoploss but when i look in the documentation i cannot find how to add trailing or brekaeven to the atm strategy create method"

                  There are no documented or supported methods for this in NinjaScript, as the atm will be using the settings of the saved Atm template only. The breakeven or trailing in the stop strategy would have to be saved in the template.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Appreciate you passing along the video, ChelseaB. Found it quite enlightening.

                    The demonstration in the video covered setups with fixed take profit and stop loss, and even one without a profit target. It got me thinking, if we integrate a stop strategy into our ATM strategy, would it execute seamlessly?

                    Furthermore, suppose we scale in on various price targets while employing the ATM strategy from the initial entry point. How would they align?
                    Thanks for your insights and assistance.

                    Comment


                      #11
                      Hello trimpy,

                      The atm will have all of the behavior saved in the atm template, including the stop strategy.

                      Unfortunately, there are no supported methods to scale in to an existing atm strategy from NinjaScript. A workaround of submitting an order to the account to adjust the position and then modify the stop and target has been suggested.
                      I have an AddOn that extends Chart Trader with custom order entry buttons. The entry buttons use StartAtmStrategy and uses the currently selected ATM Strategy. This is working as expected. The AddOn also has custom buttons to partially exit a position. Using the Account CreateOrder method, the exit buttons will partially
                      Chelsea B.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                      0 responses
                      633 views
                      0 likes
                      Last Post Geovanny Suaza  
                      Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                      0 responses
                      364 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by Mindset, 02-09-2026, 11:44 AM
                      0 responses
                      105 views
                      0 likes
                      Last Post Mindset
                      by Mindset
                       
                      Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                      0 responses
                      567 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by RFrosty, 01-28-2026, 06:49 PM
                      0 responses
                      568 views
                      1 like
                      Last Post RFrosty
                      by RFrosty
                       
                      Working...
                      X