Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Can I embed ATM Strategy within NinjaScript Editor Strategy

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

    Can I embed ATM Strategy within NinjaScript Editor Strategy

    I have a NinjaScript strategy that I wrote in my editor (Lets call it the MASingleCross) and I have an ATM Strategy "NQ1" that has the following parameters:
    • 200 tick initial stop loss (50pts)
    • Auto breakeven at 200 ticks
    • Incremental trailing stop of 50pts every 50 additional points achieved.
    Click image for larger version

Name:	image.png
Views:	131
Size:	25.3 KB
ID:	1333575

    How can I use this ATM with Stop Strategy within my MASingleCross in NinjaScript editor? Is this doable?

    Thank you,

    Steve​

    #2
    Hello eleximp224,

    ATM's can be used in manual coded strategies, there is a sample called SampleATMStrategy that comes with NinjaTrader and shows the correct syntax/logic to use. You can view that in the NinjaScript editor.

    Comment


      #3
      Thank you. This is helpful but I still am unsure where in my MASingleCross strategy I enter the 'sample ATM Strategy' components. I do have an ATM strategy created called 'AtmStrategyTemplate' per the instructions below.

      Currently I enter it in the OnBarUpdate() section after some other system vars I create. Then further down, the end of the ATM strategy is here, followed by an if (BarsInProgress != 0) which is when my sample strategy starts:

      Code:
      protected override void OnBarUpdate()
              //protected override void OnOrderUpdate()
              {
                  //double totalTradesToday = 0;
                              //Check for new day to reset trade counter
                  bool newDay = Bars.IsFirstBarOfSession;
                  if (newDay == true)
                  {
                      totalTradesToday = 0;
                      Print(String.Format("totalTradesToday = {0} when newDay at time: {1}", totalTradesToday, Time[0]));
                      // Store the strategy's prior cumulated realized profit and number of trades
                      priorTradesCount = SystemPerformance.AllTrades.Count;
                      priorTradesCumProfit = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
      
                  }
                  
              //Start SampleATMStrategy here??
                  
                  if (CurrentBar < BarsRequiredToTrade)
                      return;
      
                  // 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, "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;
                      });
                  }
      
                  // Check that atm strategy was created before checking other properties
                  if (!isAtmStrategyCreated)
                      return;
      
                  // Check for a pending entry order
                  if (orderId.Length > 0)
                  {
                      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.GetLength(0) > 0)
                      {
                          // Print out some information about the order to the output window
                          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")
                              orderId = string.Empty;
                      }
                  } // If the strategy has terminated reset the strategy id
                  else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                      atmStrategyId = string.Empty;
      
                  if (atmStrategyId.Length > 0)
                  {
                      // You can change the stop price
                      if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
                          AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
      
                      // Print some information about the strategy to the output window, please note you access the ATM strategy specific position object here
                      // the ATM would run self contained and would not have an impact on your NinjaScript strategy position and PnL
                      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));
                  }
              //End ATM Sample here
      
                  //Start strategy execution here
                  if (BarsInProgress != 0)
                      return;
                  
                  //Check if RTH
                  bool market_open = ToTime(Time[0]) >= 110000 && ToTime(Time[0]) <= 150000;
                  //bool market_open = ToTime(Time[0]) >= 093000 && ToTime(Time[0]) <= 150000;
                  
                  // Moving Average
                  bool cross_above = CrossAbove(Close[0], EMA(SlowMA), 1);
                  bool cross_below = CrossBelow(Close[0], EMA(SlowMA), 1);    
                  
                  Values[0][0] = EMA(FastMA)[0];
                  Values[1][0] = EMA(SlowMA)[0];
                  
                  Print(String.Format("At Time {1} - DailyProfit: {0}", DailyProfit, Time[0],DailyProfit));    
      
                  if (market_open)
                  {
                      if (Close[0] >= EMA(SlowMA)[0])
                      {
                      EnterLong(Convert.ToInt32(DefaultQuantity), "");
                          totalTradesToday = totalTradesToday + 1;
                          if (Close[0] <= EMA(SlowMA)[0])
                          {
                              ExitLong();
                          }
                      }​
      When I try to enable it or run it in strategy analyzer, it doesn't show anything. I must be putting something in the wrong position but cannot logically figure out why this would be anywhere else than it is...


      Comment


        #4
        Hello eleximp224,

        ATM's cannot be tested in the analyzer, they are realtime only tools. The sample is essentially a complete script that shows how to use an atm fully while using a strategy however that needs to be run in realtime to use it. If you wanted to start using atms I would suggest making a full copy of that script by right clicking in its code and doing a save as, then go through the code to make sure you understand each part before changing it. The entry condition can then be edited to do what you want to submit the atm.

        Comment


          #5
          Interesting. That explains it. Thank you, I will test and see what happens

          Comment


            #6
            I am back again. Have tested all morning, and got my ATM strategy to execute from code.

            This works if it is a simple entry like current bar is greater than previous bar.

            My issue is when trying to scan to see if price is currently above a certain MA. If price> EMA(183) then enter long, for example.

            In this case it says my variable SlowMA is not called in this context:
            Click image for larger version

Name:	image.png
Views:	173
Size:	9.9 KB
ID:	1333671

            Am I doing something wrong here? What context should it be located in. I call it in the OnStateChange() section as I did in my previous code.

            Can EMA not be used within ATM?

            My full code for this simplified sample is below:

            Code:
            namespace NinjaTrader.NinjaScript.Strategies
            {
                public class MAPriceCrossv2 : Strategy
                {
            
                    private string  atmStrategyId            = string.Empty;
                    private string  orderId                    = string.Empty;
                    private bool    isAtmStrategyCreated    = false;
            
                    protected override void OnStateChange()
                    {
                        if (State == State.SetDefaults)
                        {
                            Description    = "MAPriceCrossv2"; //NinjaTrader.Custom.Resource.NinjaScriptStrategyDescriptionSampleATMStrategy;
                            Name        = "MAPriceCrossv2"; //NinjaTrader.Custom.Resource.NinjaScriptStrategyNameSampleATMStrategy;
                            // This strategy has been designed to take advantage of performance gains in Strategy Analyzer optimizations
                            Calculate                                    = Calculate.OnBarClose;
                            EntriesPerDirection                            = 1;
                            EntryHandling                                = EntryHandling.AllEntries;
                            IsExitOnSessionCloseStrategy                = true;
                            ExitOnSessionCloseSeconds                    = 30;
                            IsFillLimitOnTouch                            = false;
                            MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                            OrderFillResolution                            = OrderFillResolution.Standard;
                            Slippage                                    = 1;
                            StartBehavior                                = StartBehavior.WaitUntilFlat;
                            TimeInForce                                    = TimeInForce.Gtc;
                            TraceOrders                                    = false;
                            RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                            StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                            BarsRequiredToTrade                            = 20;
                            // Disable this property for performance gains in Strategy Analyzer optimizations
                            // See the Help Guide for additional information
                            //IsInstantiatedOnEachOptimizationIteration    = true;
                            SlowMA                    = 183;
                            AddPlot(Brushes.Goldenrod, "SlowMA"); //Stored as plots[1] and values[1]
                            IsInstantiatedOnEachOptimizationIteration = false;
                                        }
                        else if (State == State.Configure)
                        {
                        }
                    }
            
                    protected override void OnBarUpdate()
                    {
                        if (CurrentBar < BarsRequiredToTrade)
                            return;
            
                        // Make sure this strategy does not execute against historical data
                        if(State == State.Historical)
                            return;
            
                        if (BarsInProgress != 0)
                            return;    
            
                        //Check if RTH
                        bool market_open = ToTime(Time[0]) >= 110000 && ToTime(Time[0]) <= 150000;
                        
                        Values[0][0] = EMA(SlowMA)[0];
                        
                        // 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] >= EMA(SlowMA)[0])
                        {
                            isAtmStrategyCreated = false;  // reset atm strategy created check to false
                            atmStrategyId = GetAtmStrategyUniqueId();
                            orderId = GetAtmStrategyUniqueId();
                            AtmStrategyCreate(OrderAction.Buy, OrderType.Market, Low[0], 0, TimeInForce.Day, orderId, "NQ2", 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;
                            });
                        }
            
                        // Check that atm strategy was created before checking other properties
                        if (!isAtmStrategyCreated)
                            return;
            
                        // Check for a pending entry order
                        if (orderId.Length > 0)
                        {
                            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.GetLength(0) > 0)
                            {
                                // Print out some information about the order to the output window
                                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")
                                    orderId = string.Empty;
                            }
                        } // If the strategy has terminated reset the strategy id
                        else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                            atmStrategyId = string.Empty;
            
                        if (atmStrategyId.Length > 0)
                        {
                            // You can change the stop price
                            if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
                                AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
            
                            // Print some information about the strategy to the output window, please note you access the ATM strategy specific position object here
                            // the ATM would run self contained and would not have an impact on your NinjaScript strategy position and PnL
                            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));
                        }
                    }
                }
            }​

            Comment


              #7
              Hello eleximp224,

              You are missing variables, if you are trying to do a ma crossover I would suggest looking at the SampleMACrossOver and how the variables are defined. You need public input properties like the following.

              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(Name = "SlowMA", GroupName = "NinjaScriptStrategyParameters", Order = 1)]
              public int SlowMA
              { get; set; }​

              Comment


                #8
                Oh man, I feel like a dummy! That is so obvious, I forgot to copy over the "properties" section at the bottom from my other strategy which creates the SlowMA.

                Thank you Thank you!

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by NullPointStrategies, Today, 05:17 AM
                0 responses
                52 views
                0 likes
                Last Post NullPointStrategies  
                Started by argusthome, 03-08-2026, 10:06 AM
                0 responses
                130 views
                0 likes
                Last Post argusthome  
                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                0 responses
                70 views
                0 likes
                Last Post NabilKhattabi  
                Started by Deep42, 03-06-2026, 12:28 AM
                0 responses
                44 views
                0 likes
                Last Post Deep42
                by Deep42
                 
                Started by TheRealMorford, 03-05-2026, 06:15 PM
                0 responses
                48 views
                0 likes
                Last Post TheRealMorford  
                Working...
                X