Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Bar Open - Close Larger than previous Bars Open - Close

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

    Bar Open - Close Larger than previous Bars Open - Close

    Hey NT Peeps!

    I am writing my strategy and have run into some struggles. I searched the forums and NT help a lot, but all I can find is code for Bar high/Low but I am trying to script Bar Open to Close (size of the Candle/bar excluding the high/low). I have the following script but it does not seem to work when I back test it.

    I am trying to check that the current bar (last closed) is 4x bigger than the previous 2 bars and 2x bigger than the last 15 bars. The bar needs to open above/below the SMA's then it can go long/short. The SMA's should be 24. And 1 SMA on the 15 Minute chart, the other on the 5 Minute chart. The trade will be taken on the 2 Minute chart.

    Any help would be appreciated. Thank you in advanced

    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 MyCustomStrategy : Strategy
        {
            private SMA SMA1;
    
            private SMA SMA2;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "MyCustomStrategy";
                    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;
                }
                else if (State == State.Configure)
                {
                    AddDataSeries("MES 03-23", Data.BarsPeriodType.Minute, 15, Data.MarketDataType.Last);
                    AddDataSeries(Data.BarsPeriodType.Minute, 5);
                    AddDataSeries(Data.BarsPeriodType.Minute, 2);
                }
                else if (State == State.DataLoaded)
                {                
                    SMA1                = SMA(Closes[1], 24);
                    SMA2                = SMA(Closes[2], 24);
                    SetProfitTarget(Convert.ToString((Close[0] * 1.25) ), CalculationMode.Currency, 0);
                    SetStopLoss(Convert.ToString(Open[0]), CalculationMode.Currency, 0, false);
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1
                || CurrentBars[1] < 0
                || CurrentBars[2] < 0
                || CurrentBars[3] < 15)
                    return;
    
                 // Set 1
                if ((Open[1] > SMA2[1])
                     && (Open[1] > SMA1[0])
                     && ((Open[1] - Close[1]) > ((Open[16] - Close[16]) * 2))
                      && ((Open[1] - Close[1]) > ((Open[3] - Close[3]) * 4)))
                {
                    EnterLong(1, @"long");
                }
    
                 // Set 2
                if ((Open[1] < SMA2[1])
                     && (Open[1] < SMA1[0])
                     && ((Open[1] - Close[1]) > ((Open[16] - Close[16]) * 2))
                      && ((Open[1] - Close[1]) > ((Open[3] - Close[3]) * 4)))
                {
                    EnterShort(1, @"short");
                }
    
            }
        }
    }​​

    #2
    Hello TownHoon,

    Thank you for your note.

    You mentioned, "it does not seem to work when I backtest it." What are the results when you backtest it? Do you receive any error messages in the Log tab of the Control Center? Have you tried adding print statements to better understand your script and its behavior? For more information about using prints to debug your NinjaScripts:


    I am trying to check that the current bar (last closed) is 4x bigger than the previous 2 bars and 2x bigger than the last 15 bars.
    First, it is important to clarify that CurrentBar and the last closed bar are not equivalent to each other. Current bar is the currently forming bar, and the last closed bar would be considered to be 1 bar ago. CurrentBar actually returns an int value used for the current bar and should not be confused with a reference to 1 bar ago. For more information about referencing the correct bar, please see the following:



    This could be achieved with for loops where you iterate through the previous 2 and previous 15 bars to check if the absolute value (this will get us the size and ignore if the open - close is positive or negative) of the previously closed bar's (1 bar ago) Open - Close is 2x or 4x greater than the bars in the loop. You could keep track of how many bars this is true for and add to an int variable, then check the value of that int to see if the condition was met for all 15 bars or not. Here is an example of what it looks like without the for loop for the "4x bigger than the previous 2 bars" check (I used a bool and set it to true if the condition is met) and then with a for loop for the "2x bigger than the last 15 bars" portion:
    Code:
    private int twoTimesBigger;
    private double prevCandleBody;
    private bool fourTimes;
    protected override void OnBarUpdate()
    {
    if (CurrentBar < 16)
    return;
    prevCandleBody = Math.Abs(Open[1] - Close[1]);
    if (prevCandleBody > (Math.Abs(Open[2] - Close[2]) * 4) && prevCandleBody > (Math.Abs(Open[3] - Close[3]) * 4))
    fourTimes = true;
    else
    fourTimes = false;
    // set twoTimesBigger to zero before running through the loop
    twoTimesBigger = 0;
    for (int i = 2; i <= 16; i++)
    {
    if (prevCandleBody > (Math.Abs(Open[i] - Close[i]) * 2))
    {
    // add 1 to twoTimesBigger
    twoTimesBigger++;
    }
    }
    ​}
    The bar needs to open above/below the SMA's then it can go long/short. The SMA's should be 24. And 1 SMA on the 15 Minute chart, the other on the 5 Minute chart. The trade will be taken on the 2 Minute chart.
    You can now check the value of the int variable from the previous loop in the condition along with checking for the open to be either above or below the desired SMA:
    Code:
    if (fourTimes == true && twoTimesBigger == 15) // && check for Open[1] > or < the desired SMA
    {
    // EnterLong() or EnterShort()
    }


    When submitting the EnterLong() or EnterShort(), in order to submit the trade on the 2-minute chart, you will need to use the method syntax that includes the barsInProgressIndex:More info about working with multi-instrument and/or time frames:
    I hope this has been useful information. Please let us know if we may be of further assistance.

    Comment


      #3
      Thank you very much. I will have a play around and see how I go. I will update the thread once I have had a chance to work on it more. Thank you once again

      Comment

      Latest Posts

      Collapse

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