Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to code MACD based on Open Prices in Ninjascript?

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

    How to code MACD based on Open Prices in Ninjascript?

    I'm not sure how I would go about doing this, is it even possible? In the code there's only CalculateOnBarClose. And I'm not sure if I can specify for EMA to calculate based on Open.

    Here is my code for reference.

    macdLine[0] = EMA(12)[0] - EMA(26)[0];
    signalLine[0] = EMA(9)[0] - macdLine[0];
    macdHist[0] = macdLine[0] - signalLine[0];​

    #2
    Hello,

    it is possible to calculate the MACD based on the open prices instead of the close prices in NinjaScript. To achieve this, you will need to explicitly specify that the EMA should be calculated based on the open prices rather than the default close prices.

    Here’s how you can modify your code to calculate the MACD based on the open prices:
    1. Create a Custom EMA Calculation: Specify the input series as the open prices.
    2. Calculate the MACD Line and Signal Line: Use the custom EMA calculations.
    3. Calculate the MACD Histogram: Subtract the signal line from the MACD line.
    Modified MACD Calculation Based on Open Prices


    Below is a complete example of how to calculate the MACD based on open prices in NinjaScript:

    Code:
    #region Using declarations
    using System;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript.Strategy;
    using NinjaTrader.NinjaScript.Indicators;
    #endregion
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class MACDOpenPriceStrategy : Strategy
        {
            private Series<double> macdLine;
            private Series<double> signalLine;
            private Series<double> macdHist;
            private EMA ema12;
            private EMA ema26;
            private EMA ema9;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description = @"MACD based on Open Prices.";
                    Name = "MACDOpenPriceStrategy";
                    Calculate = Calculate.OnEachTick;
                    IsOverlay = false;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    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;
                    IsInstantiatedOnEachOptimizationIteration = true;
                }
                else if (State == State.Configure)
                {
                    // Add the primary data series
                    AddDataSeries(Data.BarsPeriodType.Minute, 1);
                }
                else if (State == State.DataLoaded)
                {
                    macdLine = new Series<double>(this);
                    signalLine = new Series<double>(this);
                    macdHist = new Series<double>(this);
    
                    // Initialize EMAs with Open prices
                    ema12 = EMA(Open, 12);
                    ema26 = EMA(Open, 26);
                    ema9 = EMA(macdLine, 9);
                }
            }
    
            protected override void OnBarUpdate()
            {
                // Ensure we have enough bars
                if (CurrentBars[0] < Math.Max(ema12.Period, ema26.Period))
                    return;
    
                // Calculate MACD Line
                macdLine[0] = ema12[0] - ema26[0];
    
                // Ensure we have enough bars for Signal Line
                if (CurrentBars[0] < ema26.Period + ema9.Period)
                    return;
    
                // Calculate Signal Line
                signalLine[0] = ema9[0];
    
                // Calculate MACD Histogram
                macdHist[0] = macdLine[0] - signalLine[0];
    
                // Example trade logic based on MACD
                if (CrossAbove(macdLine, signalLine, 1))
                {
                    EnterLong("MACDLong");
                }
                else if (CrossBelow(macdLine, signalLine, 1))
                {
                    EnterShort("MACDShort");
                }
            }
    
            protected override void OnTermination()
            {
                // Cleanup
            }
        }
    }
    ​
    Explanation
    1. State.SetDefaults:
      • Sets the default properties for the strategy.
    2. State.Configure:
      • Adds the primary data series.
    3. State.DataLoaded:
      • Initializes the Series<double> objects for the MACD line, signal line, and histogram.
      • Initializes the EMAs to use the open prices with ema12 = EMA(Open, 12); and ema26 = EMA(Open, 26);.
    4. OnBarUpdate:
      • Checks if there are enough bars to calculate the EMAs.
      • Calculates the MACD line using the EMAs based on open prices.
      • Checks if there are enough bars to calculate the signal line.
      • Calculates the signal line using an EMA of the MACD line.
      • Calculates the MACD histogram.
      • Contains example trade logic that enters a long position if the MACD line crosses above the signal line, and enters a short position if the MACD line crosses below the signal line.

    This approach ensures that the MACD calculation is based on the open prices rather than the default close prices, and that trades are placed based on this custom MACD calculation.

    Comment


      #3
      Originally posted by NinjaTrader_RyanS View Post
      Hello,

      it is possible to calculate the MACD based on the open prices instead of the close prices in NinjaScript. To achieve this, you will need to explicitly specify that the EMA should be calculated based on the open prices rather than the default close prices.

      Here’s how you can modify your code to calculate the MACD based on the open prices:
      1. Create a Custom EMA Calculation: Specify the input series as the open prices.
      2. Calculate the MACD Line and Signal Line: Use the custom EMA calculations.
      3. Calculate the MACD Histogram: Subtract the signal line from the MACD line.
      Modified MACD Calculation Based on Open Prices


      Below is a complete example of how to calculate the MACD based on open prices in NinjaScript:

      Code:
      #region Using declarations
      using System;
      using NinjaTrader.Cbi;
      using NinjaTrader.Gui.Tools;
      using NinjaTrader.NinjaScript;
      using NinjaTrader.Data;
      using NinjaTrader.NinjaScript.Strategy;
      using NinjaTrader.NinjaScript.Indicators;
      #endregion
      
      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class MACDOpenPriceStrategy : Strategy
      {
      private Series<double> macdLine;
      private Series<double> signalLine;
      private Series<double> macdHist;
      private EMA ema12;
      private EMA ema26;
      private EMA ema9;
      
      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"MACD based on Open Prices.";
      Name = "MACDOpenPriceStrategy";
      Calculate = Calculate.OnEachTick;
      IsOverlay = false;
      IsExitOnSessionCloseStrategy = true;
      ExitOnSessionCloseSeconds = 30;
      EntriesPerDirection = 1;
      EntryHandling = EntryHandling.AllEntries;
      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;
      IsInstantiatedOnEachOptimizationIteration = true;
      }
      else if (State == State.Configure)
      {
      // Add the primary data series
      AddDataSeries(Data.BarsPeriodType.Minute, 1);
      }
      else if (State == State.DataLoaded)
      {
      macdLine = new Series<double>(this);
      signalLine = new Series<double>(this);
      macdHist = new Series<double>(this);
      
      // Initialize EMAs with Open prices
      ema12 = EMA(Open, 12);
      ema26 = EMA(Open, 26);
      ema9 = EMA(macdLine, 9);
      }
      }
      
      protected override void OnBarUpdate()
      {
      // Ensure we have enough bars
      if (CurrentBars[0] < Math.Max(ema12.Period, ema26.Period))
      return;
      
      // Calculate MACD Line
      macdLine[0] = ema12[0] - ema26[0];
      
      // Ensure we have enough bars for Signal Line
      if (CurrentBars[0] < ema26.Period + ema9.Period)
      return;
      
      // Calculate Signal Line
      signalLine[0] = ema9[0];
      
      // Calculate MACD Histogram
      macdHist[0] = macdLine[0] - signalLine[0];
      
      // Example trade logic based on MACD
      if (CrossAbove(macdLine, signalLine, 1))
      {
      EnterLong("MACDLong");
      }
      else if (CrossBelow(macdLine, signalLine, 1))
      {
      EnterShort("MACDShort");
      }
      }
      
      protected override void OnTermination()
      {
      // Cleanup
      }
      }
      }
      ​
      Explanation
      1. State.SetDefaults:
        • Sets the default properties for the strategy.
      2. State.Configure:
        • Adds the primary data series.
      3. State.DataLoaded:
        • Initializes the Series<double> objects for the MACD line, signal line, and histogram.
        • Initializes the EMAs to use the open prices with ema12 = EMA(Open, 12); and ema26 = EMA(Open, 26);.
      4. OnBarUpdate:
        • Checks if there are enough bars to calculate the EMAs.
        • Calculates the MACD line using the EMAs based on open prices.
        • Checks if there are enough bars to calculate the signal line.
        • Calculates the signal line using an EMA of the MACD line.
        • Calculates the MACD histogram.
        • Contains example trade logic that enters a long position if the MACD line crosses above the signal line, and enters a short position if the MACD line crosses below the signal line.

      This approach ensures that the MACD calculation is based on the open prices rather than the default close prices, and that trades are placed based on this custom MACD calculation.
      Thank you so much! Just added it to my code and it's working so far.
      Last edited by unpronounceable1700; 05-30-2024, 09:21 AM.

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by NullPointStrategies, Yesterday, 05:17 AM
      0 responses
      55 views
      0 likes
      Last Post NullPointStrategies  
      Started by argusthome, 03-08-2026, 10:06 AM
      0 responses
      132 views
      0 likes
      Last Post argusthome  
      Started by NabilKhattabi, 03-06-2026, 11:18 AM
      0 responses
      73 views
      0 likes
      Last Post NabilKhattabi  
      Started by Deep42, 03-06-2026, 12:28 AM
      0 responses
      45 views
      0 likes
      Last Post Deep42
      by Deep42
       
      Started by TheRealMorford, 03-05-2026, 06:15 PM
      0 responses
      49 views
      0 likes
      Last Post TheRealMorford  
      Working...
      X