Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Find price difference between front and back month futures, and backtest successfully

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

    Find price difference between front and back month futures, and backtest successfully

    Hi there! In my strategy, I want to calculate the difference between the front and back month future for a particular instrument. For example, the price difference between GC Aug-24 and GC Dec-24.

    I've managed to add the back month contract as a secondary data series in OnStateChange().

    Code:
       AddDataSeries("GC DEC24", Data.BarsPeriodType.Minute, 240, Data.MarketDataType.Last);
    ​
    I've also got it working dynamically as such, but I've read that this may not be the recommended approach.

    Code:
      AddDataSeries($"{base_symbol} {next_expiry.ToString("MM-yy")}", BarsPeriodType.Minute, 240);
    In playback, I've successfully had both approaches fetch the back month price and appropriately calculate the difference. However, I can't seem to get this working in backtests through the Strategy Analyzer, where the difference between the front and back month is always 0.

    Am I missing something in my settings, or is there another recommended approach here?

    Any guidance would be much appreciated.

    #2
    Hello PhillyCheese,

    Welcome the NinjaTrader forums!

    Unfortunately, dynamically adding series by using variables in AddDataSeries() or putting this in a branching command is not supported.

    From the help guide:
    "Arguments supplied to AddDataSeries() should be hardcoded and NOT dependent on run-time variables which cannot be reliably obtained during State.Configure (e.g., Instrument, Bars, or user input). Attempting to add a data series dynamically is NOT guaranteed and therefore should be avoided. Trying to load bars dynamically may result in an error similar to: Unable to load bars series. Your NinjaScript may be trying to use an additional data series dynamically in an unsupported manner.​"


    These values will have to be hardcoded.

    Further, you will likely need to use the DoNotMerge merge policy.

    Chelsea B.NinjaTrader Customer Service

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by Mindset, 04-21-2026, 06:46 AM
    0 responses
    87 views
    0 likes
    Last Post Mindset
    by Mindset
     
    Started by M4ndoo, 04-20-2026, 05:21 PM
    0 responses
    128 views
    0 likes
    Last Post M4ndoo
    by M4ndoo
     
    Started by M4ndoo, 04-19-2026, 05:54 PM
    0 responses
    65 views
    0 likes
    Last Post M4ndoo
    by M4ndoo
     
    Started by cmoran13, 04-16-2026, 01:02 PM
    0 responses
    117 views
    0 likes
    Last Post cmoran13  
    Started by PaulMohn, 04-10-2026, 11:11 AM
    0 responses
    67 views
    0 likes
    Last Post PaulMohn  
    Working...
    X