Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Using a Variable as an input in SMA

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

    Using a Variable as an input in SMA

    The current error I am receiving is:
    "The name 'SMA1' does not exist in the current context CS0103 "

    I've gone about as a far as I can with the Strategy Builder and Google searches. I have been trying to translate ThinkScript (ThinkOrSwim) into NinjaScript (NinjaTrader) with limited coding experience.

    Any thoughts?

    Here is what the actual code looks like so far, with trouble area in bold.

    namespace NinjaTrader.NinjaScript.Strategies

    {

    public class DAY2test : Strategy

    {

    private double HourPlus;

    private double HourMinus;

    private double HourBullishZone;

    private double HourBearishZone;

    private double HourNeutralZone;

    private double HourHighDifference;

    private double HourLowDifference;

    private double HourPlusDM;

    private double HourMinusDM;

    private int ZERO;


    private SMA SMA1;


    protected override void OnStateChange()

    {

    if (State == State.SetDefaults)

    {

    Description = @"Enter the description for your new custom Strategy here.";

    Name = "LearningALGObasics";

    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 = 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;

    HourPlus = 1;

    HourMinus = 1;

    HourBullishZone = 1;

    HourBearishZone = 1;

    HourNeutralZone = 1;

    HourHighDifference = 1;

    HourLowDifference = 1;

    HourPlusDM = 1;

    HourMinusDM = 1;

    ZERO = 0;

    }

    else if (State == State.Configure)

    {

    }

    else if (State == State.DataLoaded)

    {

    SMA1 = SMA(Close, 14);


    }

    }

    protected override void OnBarUpdate()

    {

    if (BarsInProgress != 0)

    return;


    if (CurrentBars[0] < 1)

    return;



    {

    HourHighDifference = (High[0] - High[1]);

    }


    {

    HourLowDifference = (Low[1] - Low[0]);

    }



    if (HourHighDifference > HourLowDifference

    && HourHighDifference > ZERO);

    {

    HourPlusDM = 1;

    }



    if (HourLowDifference > HourHighDifference

    && HourLowDifference > ZERO);

    {



    HourMinusDM = 1;

    }



    if (SMA1(HourPlusDM,0)[0]);

    {

    HourPlus = 1;

    }



    if (SMA1(HourMinusDM,0)[0]);

    {

    HourMinus = 1;

    }



    if (HourPlus > HourMinus)

    {

    HourBullishZone = 1;

    }


    if (HourPlus < HourMinus)

    {

    HourBearishZone = 1;

    }



    if ((HourBullishZone != Close[0])

    && (HourBearishZone != Close[0]));

    {

    HourNeutralZone = 1;

    }



    if (HourBullishZone >= Close[0])

    {

    EnterLong(Convert.ToInt32(DefaultQuantity), "");

    }


    if ((HourNeutralZone == Close[0])

    || (HourBearishZone == Close[0]))

    {

    ExitLong(Convert.ToInt32(DefaultQuantity), "", "");

    }


    if (HourBearishZone <= Close[0])

    {

    EnterShort(Convert.ToInt32(DefaultQuantity), "");

    }


    if ((HourBullishZone == Close[0])

    || (HourNeutralZone == Close[0]))

    {

    ExitShort(Convert.ToInt32(DefaultQuantity), "", "");

    }

    }

    }


    }
    Original ThinkOrSwim code

    input price = close;
    input averageType = AverageType.SIMPLE;
    input length = 14;

    def HourPlus;
    def HourMinus;
    def HourBullishZone;
    def HourBearishZone;
    def HourNeutralZone;
    def HourHiDiff;
    def HourLoDiff;
    def HourPlusDM;
    def HourMinusDM;

    HourHiDiff = high - high[1];
    HourLoDiff = low[1] - low;
    HourPlusDM = if HourHiDiff > HourLoDiff and HourHiDiff > 0 then HourHiDiff else 0;
    HourMinusDM = if HourLoDiff > HourHiDiff and HourLoDiff > 0 then HourLoDiff else 0;
    HourPlus = MovingAverage(averageType, HourPlusDM, length);
    HourMinus = MovingAverage(averageType, HourMinusDM, length);

    HourBullishZone = HourPlus > HourMinus;
    HourBearishZone = HourPlus < HourMinus;
    HourNeutralZone = !HourBullishZone and !HourBearishZone;


    AddOrder(OrderType.BUY_TO_OPEN, hourbullishzone,close, 1);

    AddOrder(OrderType.SELL_TO_CLOSE, HourNeutralZone or HourBearishZone, close, 1);

    #2
    Welcome to the forums Bradruss86!

    The Strategy Builder will instantiate indicators in State.DataLoaded, and then use the instantiated indicator in OnBarUpdate.

    SMA1 is instantiated as an SMA in State.DataLoaded, and then in OnBarUpdate, it is referenced as SMA1[BarsAgo]

    Calling SMA(14)[0] would calculate a new SMA with a period of 14 bars.

    System indicator methods with example snippets can also be referenced from the Help Guide.

    https://ninjatrader.com/support/help...indicators.htm

    If you are new to C# and are struggling with compile errors, I do recommend to create simple conditions with the Strategy Builder (try the conditions and actions examples) clicking the View Code button after each change. This can help to see exactly how the Strategy Builder generates code. You can then test making conditions with separate indicators, and see how the code is generated, and this can better illustrate how the different indicators get instantiated and used.

    Conditions examples - https://ninjatrader.com/support/help...on_builder.htm
    Actions examples - https://ninjatrader.com/support/help...t8/actions.htm

    Publicly available resources like the one below can also be helpful for understanding C# syntax.



    We look forward to assisting.

    Comment


      #3
      Thank you for the fast response.

      I understand that Calling SMA(14)[0] would calculate a new SMA with a period of 14 bars. I can also see from a previous post on these forums that it is possible to input a preloaded study as an input for one of the variables. https://ninjatrader.com/support/foru...ble#post497166 I have been able to replicate this in the Strategy Builder prior to unlocking the code, however my custom variable requires math which cannot be done without unlocking the code.


      I am wondering how to input a custom user variable (specifically "HourPlusDM" i.e. the difference between previous candle highs and lows) as an input as it is instructed in "valid input data for indicator methods" > 'series double'



      Do I need to create a separate method and then 'get' the output? Do I need to include the SMA formula in 'OnStateChange ()" instead of 'OnBarUpdate'? Anything you could do here to point me in the right direction beyond hyperlinks to general information would really help me out.

      Thanks again for your assistance!


      Attached Files

      Comment


        #4
        Hello Bradruss86,

        If you want to provide custom input for an indicator, you will need to create a Series<double>, assign values to the Series<double>, and supply that Series<double> to the indicator. You can actually do this in the Strategy Builder. I have attached an example.

        We also have a coding reference sample that demonstrates creating a Series<double> to use as input to an indicator as well. Please see below.

        https://ninjatrader.com/support/help...taseries_o.htm

        The key to understand with Series<double>'s is that they hold a value for each bar in the data series. We would assign values of the Series<double> in OnBarUpdate. Then we can use that Series<double> as input for an indicator.


        Attached Files

        Comment


          #5
          Oh wow, this seems like exactly what I need. I presume it's possible to create "Series<double>'s" inception? Where you can use the outcome of a formula that contains a Series<double> as a new Series<double> for yet another formula?

          Comment


            #6
            Hello Bradruss86,

            Yes, it is possible to use a Series as input for another Series, and to use that Series as input to an indicator.

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by NullPointStrategies, Today, 05:17 AM
            0 responses
            50 views
            0 likes
            Last Post NullPointStrategies  
            Started by argusthome, 03-08-2026, 10:06 AM
            0 responses
            126 views
            0 likes
            Last Post argusthome  
            Started by NabilKhattabi, 03-06-2026, 11:18 AM
            0 responses
            69 views
            0 likes
            Last Post NabilKhattabi  
            Started by Deep42, 03-06-2026, 12:28 AM
            0 responses
            42 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