Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Getting wrong values when using SMA when subracting from a variable

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

    Getting wrong values when using SMA when subracting from a variable

    Hi, I'm new at at this. I've been trying to figure out on how to get the correct value when I use the SMA to calculate a condition from the current bar. I looked at the output and it gives weird numbers. For example: If the current bar's open is over the SMA, then take the barOpen and subract from the SMA to get a value and the opposite if the the bar open is below. For example: 2 points(8ticks) for a rule to enter a trade. Thanks.

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class reversion : Strategy
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "reversion";
    Calculate = Calculate.OnEachTick;
    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;
    //ProfitTarget = 3;
    //StopLoss = 1.50;
    //EnterRule = 1.25;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {
    AddDataSeries("MES", Data.BarsPeriodType.Minute, 3, Data.MarketDataType.Last);
    }
    else if (State == State.DataLoaded)

    {


    }
    }



    protected override void OnBarUpdate()
    {
    double MovAvgValue = SMA(Close, 3)[0];
    double barOpen = Bars.GetOpen(0);
    double getCurrentBar = Bars.GetBid(0);
    //double _ProfitTarget = 3;
    //double _StopLoss = 1.50;
    //double _EnterRule = 1;


    if (BarsInProgress != 0) return;

    if (Position.MarketPosition == MarketPosition.Flat){

    if((barOpen- MovAvgValue) >= _EnterRule && barOpen> MovAvgValue && getCurrentBar > MovAvgValue){
    //Print("The current Enter Rule value is " + average.ToString());
    EnterShort(1);
    SetProfitTarget(CalculationMode.Ticks, 10 );
    SetStopLoss(CalculationMode.Ticks,5);
    } else
    if(barOpen < MovAvgValue && (MovAvgValue - barOpen) >= _EnterRule && getCurrentBar < MovAvgValue){
    EnterLong(1);
    SetProfitTarget(CalculationMode.Ticks, 10 );
    SetStopLoss(CalculationMode.Ticks,5);
    }
    }



    //Add your custom strategy logic here.

    }
    private void EnterLong(){
    //not using

    }
    private void EnterShort(){
    //not using
    }
    }
    }








    #2
    Hello egar1234,

    Thanks for your post and welcome to the NinjaTrader forums!

    I would not use Bars.Get... as these methods require you to provide the absolute bar index to get the bar of. 0 (zero) would be the number of the very first historical bar and that is likely why the values are not as expected.

    Try using Open[0] - SMA(3)[0] The price series Open uses a "Bars ago" index so [0] in this case would represent the current bar. The SMA indicator will automatically default to use the Close Price series so you can specify it as you did or as I have done.

    Here are some reference links that will help:





    Please note that a script (Strategy/indicator/etc) will start with the very first historical bar, 0, and execute the OnBarUpdate() method, it will then increment to the next bar, 1, and again execute, and this process will repeat all the way to the currently forming bar. So your script will process on all historical bars in order. The system bar counter CurrentBar holds the be number that the OnBarUpdate() is working on. Reference: https://ninjatrader.com/support/help...currentbar.htm

    As a suggestion, for the use of Set methods (SetStopLoss and SetProfitTarget), if you are using the same stop and target, you can set these in State.DataLoaded and they will then apply to every Entry order and thus no need to repetitively code/call them in OnBarUpdate().
    References:


    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Thanks for the reply. Now it's calculating the correct values. Now I have another problem. When I try to reference the previous bar nothing happens. SMA(3)[1]. My strategy doesn't run. I get this error:

      " Error on calling 'OnBarUpdate' method on bar 0: 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."
      Last edited by egar1234; 10-20-2021, 03:33 PM.

      Comment


        #4
        Hello egar1234,

        Thanks for your reply.

        This is part of the answer, "Please note that a script (Strategy/indicator/etc) will start with the very first historical bar, 0, and execute the OnBarUpdate() method, it will then increment to the next bar, 1, and again execute, and this process will repeat all the way to the currently forming bar. So your script will process on all historical bars in order. The system bar counter CurrentBar holds the be number that the OnBarUpdate() is working on."

        So what is happening is that when the script loads the first bar and then tries to access a previous bar [1] that does not exist, you will get that error. You will need to review your script and see if you have any other bars ago that you are checking that are a further bar. Once you know that then you need to add code to your script to prevent the processing of your script that access the bars ago until that many (or more) bars have been processed by the script. The easiest way to do this is to check if the CurrentBar (systems bar counter) is less than your worst-case bars ago and if so to simply "return". For example:

        if (CurrentBar < 20) return; // do not process below this line until CurrentBar is greater than or equal to 20.

        You would place that line above all of your code in the OnBarUpdate(). I used 20 as a common example because indicators that plot will not show their plot for the first 20 bars, you can of course make the number any value you wish.

        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Thanks for the response. My strategy's logic seems good but it executes on the wrong bar. I have it set to each tick. For example: In the picture, it should go long on the open of the green bar after the big red bar. I'm missing something or its implementation is wrong. Thanks.
          Attached Files

          Comment


            #6
            Hello egar1234,

            Thanks for your reply.

            "In the picture, it should go long on the open of the green bar after the big red bar."

            In the picture, it went Short on the Green bar after the big Red Bar. That would suggest that something is backward in your logic.

            To debug your strategy I recommend using print statements to print out the values of the variables used in the decision. The Print() method will send its output to the New>Ninjascript Output window. You would want the window open before enabling the strategy.

            Also, when in the create/debug process, keep an eye on the Ninjatrader control centers "Log" tab as this will show any errors.

            References:



            Here is a link to further debugging tips: https://ninjatrader.com/support/help...script_cod.htm
            Paul H.NinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by maybeimnotrader, Today, 05:46 PM
            0 responses
            6 views
            0 likes
            Last Post maybeimnotrader  
            Started by quantismo, Today, 05:13 PM
            0 responses
            6 views
            0 likes
            Last Post quantismo  
            Started by AttiM, 02-14-2024, 05:20 PM
            8 responses
            166 views
            0 likes
            Last Post jeronymite  
            Started by cre8able, Today, 04:22 PM
            0 responses
            8 views
            0 likes
            Last Post cre8able  
            Started by RichStudent, Today, 04:21 PM
            0 responses
            5 views
            0 likes
            Last Post RichStudent  
            Working...
            X