Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Issues creating first strategy

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

    Issues creating first strategy

    Hi all!

    I am moving over from TD Ameritrade and am having quite a fit with Ninjatrader's interface. Anyway, I have been trying to build a simple strategy I want to backtest (and possibly algo trade) but for the life of me I can't get it to run. I think I finally built it, but after I "Finish"ed the strategy in the Strategy Editor I remember I put the CCIzeroline = 0 User Input as having a minimum value of 1.

    Now I am getting that error complaining it isn't between 1 and two hundred thousand or million something. I tried to redo it in the Strategy Editor (which wouldn't allow it and kept saying I needed to close out all version of the strategy before editing).

    Then I deleted it from my only chart, closed the chart, tried everything I could and the Strategy Editor would open it, but still not let me edit the CCIzeroline User Input. I have no idea why, so since that seemed broken I switched over to opening the code (which disallows using the Strategy Editor anymore, which is kind of stupid).

    I have copied and pasted the code to a text file. Currently it is for stocks and I am using my TD Ameritrade data feed. The strategy is simple right now, nowhere close to the complexity I have completed overall, I just want to test it. The synopsis of what it SHOULD do is:

    CCI(5)
    SMA(8,(High+Low)/2)
    ATR(5,Wilders)

    If *both* CCI crosses above the zeroline and the price closes above the SMA(8), set a stoplimit Buy to Open $0.02 above the bar's High. If *either* CCI crosses below the zeroline or price closes below SMA(8), sell. ATR should be above 3, which is kind of an error.

    My strategy is supposed to be Stoplimit Buy to Open @ High + 0.02 for stocks, or 0.25 for futures. The ATR should be above 3 for futures trading on the 1-minute chart, but will be different for stocks (which I did forget).

    I can post my code, but I am first wondering how to edit this to work.

    Ultimately for stocks I am wanting to pyramid my entries and do a lot of other things, but I am just trying to get started at this point. I do have some C and C++, Python, and Java experience, but I am just starting out in C#. If I can get a handle on the basics it will go much more quickly, but until I can actually get INTO this and have a first working program I can mess around in (so I can tweak things and see cause and effect) it will be a bear to learn. I just need to get my first program working and bells and whistles can come later.

    Long copy and past to follow of my current code. Unfortunately this stupid forum won't permit indentations of tabs OR four spaces, so I am sorry it isn't presenting correctly:

    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class GoldenThrone : Strategy
    {
    private CCI CCI1;
    private ATR ATR1;
    private SMA SMA1;
    private SMA SMA2;
    
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Will add later";
    Name = "GoldenThrone";
    Calculate = Calculate.OnPriceChange;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlatSynchronizeAccount;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.ByStrategyPosition;
    BarsRequiredToTrade = 9;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    CCIperiod = 5;
    SMAperiod = 8;
    ATRperiod = 5;
    CCIzeroline_value = 0;
    ATRminimum_value = 3;
    Quantity = 100;
    Stop_buy_offset = 0.02;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    CCI1 = CCI(Close, Convert.ToInt32(CCIperiod));
    ATR1 = ATR(Close, Convert.ToInt32(ATRperiod));
    SMA1 = SMA(Median, Convert.ToInt32(SMAperiod));
    SMA2 = SMA(Median, Convert.ToInt32(SMAperiod));
    CCI1.Plots[0].Brush = Brushes.DarkOrchid;
    ATR1.Plots[0].Brush = Brushes.DarkCyan;
    AddChartIndicator(CCI1);
    AddChartIndicator(ATR1);
    }
    }
    
    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;
    
    if (CurrentBars[0] < 1)
    return;
    
    // Set 1
    if ((CrossAbove(CCI1, CCIzeroline_value, 1))
    && (ATR1[0] >= ATRminimum_value)
    && (CrossAbove(Close, SMA1, 1)))
    {
    EnterLongStopLimit(Convert.ToInt32(Quantity), (High[0] + (Stop_buy_offset)) , (High[0] + (Stop_buy_offset)) , @"Buy_to_Open");
    }
    
    // Set 2
    if ((CrossBelow(CCI1, CCIzeroline_value, 1))
    || (CrossBelow(Close, SMA2, 1)))
    {
    ExitLong(Convert.ToInt32(Quantity), @"Sell_to_Close", @"Buy_to_Open");
    }
    
    }
    
    #region Properties
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="CCIperiod", Description="CCI period (default: 5)", Order=1, GroupName="Parameters")]
    public int CCIperiod
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="SMAperiod", Description="SMA period (default: 8)", Order=2, GroupName="Parameters")]
    public int SMAperiod
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="ATRperiod", Description="ATR period (default: 5)", Order=3, GroupName="Parameters")]
    public int ATRperiod
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="CCIzeroline_value", Description="The value of the zeroline is... ZERO!", Order=4, GroupName="Parameters")]
    public int CCIzeroline_value
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="ATRminimum_value", Description="ATR minimum value is... 3!", Order=5, GroupName="Parameters")]
    public int ATRminimum_value
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Quantity", Description="Quantity to buy", Order=6, GroupName="Parameters")]
    public int Quantity
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(0, double.MaxValue)]
    [Display(Name="Stop_buy_offset", Description="How far above the bar high to put our stoplimit (Default: 0.02 for stocks, 0.25 for futures)", Order=7, GroupName="Parameters")]
    public double Stop_buy_offset
    { get; set; }
    #endregion
    
    }
    }

    #2
    Hello Mistoffelees,

    Welcome to the NinjaTrader forums!

    Are you getting errors when attempting to run the script on the Log tab of the Control Center?

    If so, what are the full error messages?

    You mention CCIzeroline is an input that may be causing an issue.
    What is the Range allowed for this input in the attribute above the declaration?
    What is the default value assigned to this input in State.SetDefaults?

    As a tip for the future, to export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
    1. Click Tools -> Export -> NinjaScript...
    2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
    3. Click the 'Export' button
    4. Enter a unique name for the file in the value for 'File name:'
    5. Choose a save location -> click Save
    6. Click OK to clear the export location message
    By default your exported file will be in the following location:
    • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
    Below is a link to the help guide on Exporting NinjaScripts.


    Last, below I am providing a link to a forum post with helpful information about getting started with NinjaScript and C#.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hey, been a while. Not sure if I need to create a new post or not.

      I am on a new and more complicated bot, but now I am getting a new-ish error.

      The bot won't enable, like before. But then it DID enable, and now won't again (NO changes whatsoever at any time, either!)

      Also, the error message is slightly different than for what was posted earlier in this thread about the early bot. It says now:

      "Strategy 'HeadAndShouldersStrategyUnlocked': Error on calling 'OnBarUpdate' method on bar 52727: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart."

      What causes the error to shift from bar 1 to bar 52727? If it can load that many bars, why is it pitching a bloody tantrum THIS time?

      Comment


        #4
        Hello Mistoffelees,

        If this is for a new strategy we do suggest making a new post for new questions. The error you are seeing is because you have an error in the OnBarUpdate override. That is not a compile error but a runtime error. The message is a general message letting you know that at that time when you tried to access some data that was not a valid time to do that. We suggest using Print statements to identify which specific line is having an error, once you know which line is having an error if it is not apparent what the problem is please make a new post and include that portion of the code along with any other relevant details such as if you are using a multi timeframe strategy.

        Comment


          #5
          I have started a new post, but my fear is that it is the Ninjatrader software and not my script that is having an error.

          The bottom line is that my script works in all circumstances unless I change the chart to the NQ 12 range specifically, and the error occurs 52,727 Bars in the past.

          There is no way for me to try to find that and visually ascertain exactly what is screwing up.

          Gaby is trying to help me, but she(?) is telling me to do what I’ve already done. So the advice I am receiving is not helpful so far.

          Comment


            #6
            Hello Mistoffelees,

            That error is not based on something the platform is doing, that is specific to the code you used. This is a common error but you need to find the line of code having the error and provide details surrounding how your script was coded so we know how to assist in that unique instance.

            Prints are the way to find the line causing the error, you can add prints in your code and then use the output window to see what the last print was before the error. That will give you the location of the error in your code.

            As you opened a new post please follow up in that post so we don't have multiple people trying to help at once.

            Comment

            Latest Posts

            Collapse

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