Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Converting Tradingview to Ninjascript, can someone help me?

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

    Converting Tradingview to Ninjascript, can someone help me?

    Code:
    [CODE]strategy("Steven Primo Bollinger Band", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, process_orders_on_close=true, max_labels_count=500)
    // Constants
    var TRANSP = 5
    var LONG = strategy.direction.long
    var SHORT = strategy.direction.short
    var ALL = strategy.direction.all
    var S_BOLLINGER = "Bollinger settings"
    var S_SETUP = "Setup settings"
    // Inputs
    src = math.log(input.source(close, "Price source", group=S_BOLLINGER))
    var bollingerLength = input.int(20, "Bollinger length", minval=3, group=S_BOLLINGER, inline=S_BOLLINGER)
    var mult = input.float(0.382, "Standard deviation", minval=0.0, step=0.1, group=S_BOLLINGER, inline=S_BOLLINGER)
    var orderDirection = input.string(LONG, "Order direction", options=[LONG, SHORT, ALL], group=S_SETUP)
    var useTrailingStop = input.bool(false, "Use trailing stop", group=S_SETUP)
    var consecutiveCloses = input.int(5, "Consecutive closes for the setup", minval=1, group=S_SETUP, inline=S_SETUP)
    var extension = input.int(100, "Extension (%)", minval=100, group=S_SETUP, inline=S_SETUP) / 100.0
    // Getting the BB
    [middle, upper, lower] = ta.bb(src, bollingerLength, mult)
    middle := math.exp(middle)
    upper := math.exp(upper)
    lower := math.exp(lower)
    // Plotting the BB
    var colorAtTheLimits = color.new(color.yellow, TRANSP)
    var colorAtTheMiddle = color.new(color.blue, TRANSP)
    plot(middle, "Middle band", colorAtTheMiddle, display=display.none)
    plot(upper, "Upper band", colorAtTheLimits)
    plot(lower, "Lower band", colorAtTheLimits)
    // MA setup
    
    // BB setup
    longComparison() => close >= upper
    shortComparison() => close <= lower
    var countLong = 0
    var countShort = 0
    incCount(count, comparison) =>
    if comparison
    if count == 0 and comparison[1]
    0
    else
    count + 1
    else
    0
    countLong := incCount(countLong, longComparison())
    countShort := incCount(countShort, shortComparison())
    // Pivot setup
    pivotHigh = ta.pivothigh(1, 1)
    pivotLow = ta.pivotlow(1, 1)
    pivotInRange(pivot, count) => ta.barssince(pivot) < count
    pvHighInRange = pivotInRange(pivotHigh, countLong)
    pvLowInRange = pivotInRange(pivotLow, countShort)
    // Entry price
    epLong = fixnan(pivotHigh) + syminfo.mintick
    epShort = fixnan(pivotLow) - syminfo.mintick
    // Stop price
    getRange(currentPrice, pivot, cond, tickMod) =>
    if cond
    currentPrice
    else
    fixnan(pivot) + syminfo.mintick * tickMod
    var stopLong = 0.0
    var stopShort = 0.0
    stopLong := epShort
    stopShort := epLong
    
    // Target price
    getTarget(stopPrice, entryPrice) =>
    totalTicks = (entryPrice - stopPrice) * extension
    entryPrice + totalTicks
    var targetLong = 0.0
    var targetShort = 0.0
    targetLong := getTarget(stopLong, epLong)
    targetShort := getTarget(stopShort, epShort)
    // Entry condition
    canBuy = countLong >= consecutiveCloses and pvHighInRange and high < epLong
    canSell = countShort >= consecutiveCloses and pvLowInRange and low > epShort
    // Entry orders
    inMarket = strategy.opentrades != 0
    var plotTarget = 0.0
    var plotStop = 0.0
    strategy.risk.allow_entry_in(orderDirection)
    if not inMarket
    if canBuy
    plotTarget := targetLong
    plotStop := stopLong
    strategy.entry("long", strategy.long, stop=epLong, comment="Entry long")
    else if canSell
    plotTarget := targetShort
    plotStop := stopShort
    strategy.entry("short", strategy.short, stop=epShort, comment="Entry short")
    else
    strategy.cancel("long")
    strategy.cancel("short")
    
    // Exit orders
    strategy.exit("long", "long", stop=stopLong, limit=targetLong, comment="Exit long")
    strategy.exit("short", "short", stop=stopShort, limit=targetShort, comment="Exit short")
    else
    countLong := 0
    countShort := 0
    // Trailing stop
    if useTrailingStop and inMarket
    if strategy.position_entry_name == "long"
    strategy.exit("long", "long", stop=stopLong, limit=plotTarget, comment="Exit long", when=stopLong > plotStop)
    plotStop := stopLong
    else
    strategy.exit("short", "short", stop=stopShort, limit=plotTarget, comment="Exit short", when=stopShort < plotStop)
    plotStop := stopShort
    // Plot exit
    plotCond(price) => inMarket ? price : inMarket[1] ? price[1] : na
    plot(plotCond(plotStop), "Stop loss", color.red, style=plot.style_linebr)
    plot(plotCond(plotTarget), "Target", color.teal, style=plot.style_linebr)
    ​​
    [/CODE]
    Last edited by Babbou72; 02-15-2025, 08:41 PM.

    #2
    Hello,

    Thank you for your post.

    While our support does not provide conversion services, if you have a specific question about how to accomplish something in NinjaScript we can assist.

    This thread will also remain open for any members of the community who may want to covert this on your behalf.

    Comment


      #3
      Thank you, I just started doing it, I have only a problem detecting the last pivot high or low after getting 5 closes. I can share the code achieved here if you can help me.

      Comment


        #4




        Code:
        [HASHTAG="t3322"]region[/HASHTAG] Using declarations
        using System;
        using System.Windows.Media;
        using NinjaTrader.Cbi;
        using NinjaTrader.Data;
        using NinjaTrader.NinjaScript;
        using NinjaTrader.NinjaScript.Indicators;
        using NinjaTrader.NinjaScript.Strategies;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using NinjaTrader.NinjaScript.DrawingTools;
        using NinjaTrader.Gui.Chart;
        #endregion
        
        namespace NinjaTrader.NinjaScript.Indicators
        {
        public class CustomBollingerV1 : Indicator
        {
        private int consecutiveAboveUpper = 0;
        private int consecutiveBelowLower = 0;
        private double stdDev, middle, upper, lower;
        private int lastPivotHighBarIndex = -1;
        private int lastPivotLowBarIndex = -1;
        
        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        Description = "Bandes de Bollinger personnalisées avec options d'affichage et alertes";
        Name = "CustomBollingerV1";
        Calculate = Calculate.OnBarClose;
        IsOverlay = true;
        DisplayInDataBox = true;
        DrawOnPricePanel = true;
        
        Period = 20;
        Multiplier = 0.382;
        EnableAlert = true;
        AlertSoundPath = NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav";
        
        ShowUpperBand = true;
        ShowMiddleBand = true;
        ShowLowerBand = true;
        
        AddPlot(new SolidColorBrush(Colors.Cyan), "UpperBand");
        AddPlot(new SolidColorBrush(Colors.Red), "MiddleBand");
        AddPlot(new SolidColorBrush(Colors.GreenYellow), "LowerBand");
        }
        }
        
        protected override void OnBarUpdate()
        {
        if (CurrentBar < Period)
        return;
        
        stdDev = StdDev(Close, Period)[0];
        if (double.IsNaN(stdDev) || stdDev == 0)
        return;
        
        middle = SMA(Close, Period)[0];
        upper = middle + (stdDev * Multiplier);
        lower = middle - (stdDev * Multiplier);
        
        Values[0][0] = ShowUpperBand ? upper : double.NaN;
        Values[1][0] = ShowMiddleBand ? middle : double.NaN;
        Values[2][0] = ShowLowerBand ? lower : double.NaN;
        
        // Gestion des clôtures consécutives et réinitialisation
        if (Close[0] > upper)
        {
        consecutiveAboveUpper++;
        consecutiveBelowLower = 0;
        }
        else if (Close[0] < lower)
        {
        consecutiveBelowLower++;
        consecutiveAboveUpper = 0;
        }
        else
        {
        // Colorer en jaune la bougie qui réinitialise le compteur
        if (consecutiveAboveUpper > 0 || consecutiveBelowLower > 0)
        {
        BarBrush = Brushes.Yellow;
        CandleOutlineBrush = Brushes.Yellow;
        }
        
        consecutiveAboveUpper = 0;
        consecutiveBelowLower = 0;
        }
        
        // Détection du dernier pivot haut (3 bougies)
        if (High[1] > High[0] && High[1] > High[2])
        {
        lastPivotHighBarIndex = CurrentBar - 1;
        Draw.Dot(this, $"PivotHigh{lastPivotHighBarIndex}", true, 1, High[1] + TickSize * 5, Brushes.Blue);
        }
        
        // Affiche le dernier pivot haut par rapport ŕ la bougie actuelle
        if (lastPivotHighBarIndex != -1)
        {
        Draw.Text(this, $"LastPivotLabel{CurrentBar}", $"Dernier Pivot Haut: Bar {lastPivotHighBarIndex}", 0, High[lastPivotHighBarIndex] + TickSize * 10, Brushes.Green);
        }
        
        // Détection du dernier pivot bas (3 bougies)
        if (Low[1] < Low[0] && Low[1] < Low[2])
        {
        lastPivotLowBarIndex = CurrentBar - 1;
        Draw.Dot(this, $"PivotLow{lastPivotLowBarIndex}", true, 1, Low[1] - TickSize * 5, Brushes.Red);
        }
        
        // Affiche le dernier pivot bas par rapport ŕ la bougie actuelle
        if (lastPivotLowBarIndex != -1)
        {
        Draw.Text(this, $"LastPivotLabel{CurrentBar}", $"Dernier Pivot Bas: Bar {lastPivotLowBarIndex}", 0, Low[lastPivotLowBarIndex] - TickSize * 10, Brushes.Orange);
        }
        
        // Affiche le dernier pivot haut par rapport ŕ la bougie actuelle
        if (lastPivotHighBarIndex != -1)
        {
        Draw.Text(this, $"LastPivotLabel{CurrentBar}", $"Dernier Pivot Haut: Bar {lastPivotHighBarIndex}", 0, High[lastPivotHighBarIndex] + TickSize * 10, Brushes.Green);
        }
        
        
        
        
        // Affichage et alerte lors de 5 clôtures consécutives
        if (consecutiveAboveUpper == 5)
        {
        Draw.Text(this, "AboveUpper" + CurrentBar, "5", 0, High[0] + TickSize * 10, Brushes.Green);
        
        if (EnableAlert && !string.IsNullOrEmpty(AlertSoundPath))
        {
        Alert("AboveUpperAlert", Priority.High, "5 clôtures consécutives au-dessus de la bande supérieure", AlertSoundPath, 10, Brushes.Green, Brushes.White);
        }
        }
        
        if (consecutiveBelowLower == 5)
        {
        Draw.Text(this, "BelowLower" + CurrentBar, "5", 0, Low[0] - TickSize * 10, Brushes.Red);
        
        if (EnableAlert && !string.IsNullOrEmpty(AlertSoundPath))
        {
        Alert("BelowLowerAlert", Priority.High, "5 clôtures consécutives en dessous de la bande inférieure", AlertSoundPath, 10, Brushes.Red, Brushes.White);
        }
        }
        }
        
        protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
        {
        base.OnRender(chartControl, chartScale);
        
        // Correction de l'erreur en utilisant Plots.Length au lieu de Plots.Count
        for (int i = 0; i < Plots.Length; i++)
        {
        Plots[i].Width = 2; // Épaisseur de 2 pour toutes les bandes
        }
        }
        
        [HASHTAG="t3322"]region[/HASHTAG] Properties
        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name = "Période", Description = "Nombre de barres pour le calcul", Order = 1, GroupName = "Paramčtres")]
        public int Period { get; set; }
        
        [NinjaScriptProperty]
        [Range(0, double.MaxValue)]
        [Display(Name = "Multiplicateur", Description = "Multiplicateur de l'écart type", Order = 2, GroupName = "Paramčtres")]
        public double Multiplier { get; set; }
        
        [NinjaScriptProperty]
        [Display(Name = "Activer les alertes", Description = "Active ou désactive les alertes sonores", Order = 3, GroupName = "Alertes")]
        public bool EnableAlert { get; set; }
        
        [NinjaScriptProperty]
        [Display(Name = "Chemin du son d'alerte", Description = "Chemin du fichier son utilisé pour l'alerte", Order = 4, GroupName = "Alertes")]
        public string AlertSoundPath { get; set; }
        
        [NinjaScriptProperty]
        [Display(Name = "Afficher la bande supérieure", Description = "Active ou désactive l'affichage de la bande supérieure", Order = 5, GroupName = "Affichage")]
        public bool ShowUpperBand { get; set; }
        
        [NinjaScriptProperty]
        [Display(Name = "Afficher la bande médiane", Description = "Active ou désactive l'affichage de la bande médiane", Order = 6, GroupName = "Affichage")]
        public bool ShowMiddleBand { get; set; }
        
        [NinjaScriptProperty]
        [Display(Name = "Afficher la bande inférieure", Description = "Active ou désactive l'affichage de la bande inférieure", Order = 7, GroupName = "Affichage")]
        public bool ShowLowerBand { get; set; }
        #endregion
        }
        }
        
        [HASHTAG="t3322"]region[/HASHTAG] NinjaScript generated code. Neither change nor remove.
        
        namespace NinjaTrader.NinjaScript.Indicators
        {
        public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
        {
        private CustomBollingerV1[] cacheCustomBollingerV1;
        public CustomBollingerV1 CustomBollingerV1(int period, double multiplier, bool enableAlert, string alertSoundPath, bool showUpperBand, bool showMiddleBand, bool showLowerBand)
        {
        return CustomBollingerV1(Input, period, multiplier, enableAlert, alertSoundPath, showUpperBand, showMiddleBand, showLowerBand);
        }
        
        public CustomBollingerV1 CustomBollingerV1(ISeries<double> input, int period, double multiplier, bool enableAlert, string alertSoundPath, bool showUpperBand, bool showMiddleBand, bool showLowerBand)
        {
        if (cacheCustomBollingerV1 != null)
        for (int idx = 0; idx < cacheCustomBollingerV1.Length; idx++)
        if (cacheCustomBollingerV1[idx] != null && cacheCustomBollingerV1[idx].Period == period && cacheCustomBollingerV1[idx].Multiplier == multiplier && cacheCustomBollingerV1[idx].EnableAlert == enableAlert && cacheCustomBollingerV1[idx].AlertSoundPath == alertSoundPath && cacheCustomBollingerV1[idx].ShowUpperBand == showUpperBand && cacheCustomBollingerV1[idx].ShowMiddleBand == showMiddleBand && cacheCustomBollingerV1[idx].ShowLowerBand == showLowerBand && cacheCustomBollingerV1[idx].EqualsInput(input))
        return cacheCustomBollingerV1[idx];
        return CacheIndicator<CustomBollingerV1>(new CustomBollingerV1(){ Period = period, Multiplier = multiplier, EnableAlert = enableAlert, AlertSoundPath = alertSoundPath, ShowUpperBand = showUpperBand, ShowMiddleBand = showMiddleBand, ShowLowerBand = showLowerBand }, input, ref cacheCustomBollingerV1);
        }
        }
        }
        
        namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
        {
        public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
        {
        public Indicators.CustomBollingerV1 CustomBollingerV1(int period, double multiplier, bool enableAlert, string alertSoundPath, bool showUpperBand, bool showMiddleBand, bool showLowerBand)
        {
        return indicator.CustomBollingerV1(Input, period, multiplier, enableAlert, alertSoundPath, showUpperBand, showMiddleBand, showLowerBand);
        }
        
        public Indicators.CustomBollingerV1 CustomBollingerV1(ISeries<double> input , int period, double multiplier, bool enableAlert, string alertSoundPath, bool showUpperBand, bool showMiddleBand, bool showLowerBand)
        {
        return indicator.CustomBollingerV1(input, period, multiplier, enableAlert, alertSoundPath, showUpperBand, showMiddleBand, showLowerBand);
        }
        }
        }
        
        namespace NinjaTrader.NinjaScript.Strategies
        {
        public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
        {
        public Indicators.CustomBollingerV1 CustomBollingerV1(int period, double multiplier, bool enableAlert, string alertSoundPath, bool showUpperBand, bool showMiddleBand, bool showLowerBand)
        {
        return indicator.CustomBollingerV1(Input, period, multiplier, enableAlert, alertSoundPath, showUpperBand, showMiddleBand, showLowerBand);
        }
        
        public Indicators.CustomBollingerV1 CustomBollingerV1(ISeries<double> input , int period, double multiplier, bool enableAlert, string alertSoundPath, bool showUpperBand, bool showMiddleBand, bool showLowerBand)
        {
        return indicator.CustomBollingerV1(input, period, multiplier, enableAlert, alertSoundPath, showUpperBand, showMiddleBand, showLowerBand);
        }
        }
        }
        
        #endregion
        ​

        Comment


          #5
          Can you help

          What I’ve Accomplished So Far:
          • Created a custom Bollinger Bands indicator.
          • Implemented a feature to display the number 5 after 5 consecutive closes occur either above or below the bands.
          • Added an alert system to notify when this condition is met.
          • Configured the system to display all swing points with a strength of 1.



          Now i need to code this:
          Condition:
          After observing 5 consecutive candle closes, identify the last swing high for a Long position and the last swing low for a Short position.

          Action:
          • If the price breaks the last swing high by at least one tick (without waiting for the candle to close), display an up arrow for a Long signal.
          • If the price breaks the last swing low by at least one tick, display a down arrow for a Short signal.

          Reset Condition:
          If the price closes inside the bands before breaking the last swing high or low, the counter resets, and the last swing high/low is no longer valid. In this case, wait for the next cycle of 5 consecutive closes to reassess the condition.
          Last edited by Babbou72; 02-17-2025, 10:08 AM.

          Comment


            #6
            What are you considering a swing high? Is it where a potential bar's high (I'll call it 'x') is higher than the both the previous candle and the proceeding candle?
            (High[x] > High[x-1] && High[x] > High[x+1])?
            If you are in a downtrend where the top is a pivot and it creates a pullback for another pivot, and both are within 5 candles, which would you consider the swing high? The higher of the two? I'm guessing you'll need a double value to keep track of the level you need to keep track so that if Close[0] >= level (in a long scenario) then that level has been broken.

            Comment


              #7
              There are two ways to trade: Long and Short.
              For Long we need a swing high to be broken: formed by 3 candles, the one in the middle have a high higher than the 2 others.
              For Short we need a swing low

              Comment


                #8
                Ok. So you would be looking at it in the way I mentioned then. Does it just need to break the most recent swing high? The way I'm thinking about it, you could either start from the 5th candle and check if there are any highs and lows and work back to the current candle, or you could do the reverse and get the most recent one.

                Comment


                  #9
                  Yes, that’s true, after 5 closes I start looking for the most recent high to break if we are long and the most recent low if we are short.

                  Comment


                    #10
                    Here is the summary of Strategy if it can help:
                    1. Strategy Settings
                    • Overlay: The strategy is plotted on the main chart.
                    • Default Quantity Type: Uses 100% of the available equity for each trade.
                    • Process Orders on Close: Orders are executed at the close of the candle.
                    • Max Labels Count: Limits the number of labels on the chart to 500.

                    2. Inputs

                    Bollinger Bands Settings
                    • Price Source: The closing price is used as the default source for Bollinger Bands calculations.
                    • Bollinger Length: The length of the Bollinger Bands (default: 20).
                    • Standard Deviation Multiplier: The multiplier for the standard deviation (default: 0.382).
                    Setup Settings
                    • Order Direction: Allows the user to choose between long, short, or both directions (default: long).
                    • Use Trailing Stop: Enables or disables trailing stop functionality (default: false).
                    • Consecutive Closes for Setup: The number of consecutive closes required for a setup (default: 5).
                    • Extension (%): The percentage extension for calculating the target price (default: 100%).

                    3. Bollinger Bands Calculation
                    • The Bollinger Bands are calculated using the ta.bb function:
                      • Middle Band: Exponential moving average (EMA) of the log-transformed price.
                      • Upper Band: Middle band + (standard deviation × multiplier).
                      • Lower Band: Middle band - (standard deviation × multiplier).
                    • The bands are then transformed back using math.exp to plot on the chart.

                    4. Setup Conditions

                    Long Setup
                    • Condition: The close price is above the upper Bollinger Band.
                    • Consecutive Closes: The close must remain above the upper band for a specified number of consecutive candles (consecutiveCloses).
                    • Pivot High: A pivot high must occur within the range of the setup.
                    Short Setup
                    • Condition: The close price is below the lower Bollinger Band.
                    • Consecutive Closes: The close must remain below the lower band for a specified number of consecutive candles (consecutiveCloses).
                    • Pivot Low: A pivot low must occur within the range of the setup.

                    5. Entry Conditions

                    Long Entry
                    • Condition: The setup for a long trade is confirmed (canBuy).
                    • Entry Price: The pivot high price + 1 tick.
                    • Stop Loss: The pivot low price.
                    • Target Price: Calculated as the entry price + (extension × (entry price - stop loss)).
                    Short Entry
                    • Condition: The setup for a short trade is confirmed (canSell).
                    • Entry Price: The pivot low price - 1 tick.
                    • Stop Loss: The pivot high price.
                    • Target Price: Calculated as the entry price - (extension × (stop loss - entry price)).

                    6. Exit Conditions
                    • Stop Loss: The stop loss is set at the pivot low for long trades and the pivot high for short trades.
                    • Target Price: The target price is calculated based on the extension percentage.
                    • Trailing Stop: If enabled, the stop loss trails the price for long trades (moves up) or for short trades (moves down).

                    7. Order Management
                    • Entry Orders:
                      • Long orders are placed if the long setup conditions are met.
                      • Short orders are placed if the short setup conditions are met.
                    • Exit Orders:
                      • Exit orders are placed with a stop loss and target price.
                      • If a trailing stop is enabled, the stop loss is updated dynamically.
                    • Cancel Orders: If no setup is confirmed, pending orders are canceled.

                    8. Plotting
                    • Bollinger Bands: The upper, middle, and lower bands are plotted on the chart.
                    • Stop Loss and Target: The stop loss and target levels are plotted for visual reference.

                    Summary of Key Conditions
                    1. Long Trade:
                      • Close price > Upper Bollinger Band for consecutiveCloses candles.
                      • Pivot high within the setup range.
                      • Entry at pivot high + 1 tick.
                      • Stop loss at pivot low.
                      • Target price calculated using the extension percentage.
                    2. Short Trade:
                      • Close price < Lower Bollinger Band for consecutiveCloses candles.
                      • Pivot low within the setup range.
                      • Entry at pivot low - 1 tick.
                      • Stop loss at pivot high.
                      • Target price calculated using the extension percentage.
                    3. Trailing Stop:
                      • If enabled, the stop loss trails the price for open trades.
                    4. Order Direction:
                      • The strategy can be configured to trade long, short, or both directions.

                    Comment


                      #11
                      Off the top of my head, this is the logic that I'm thinking of when looking for swing highs. You would change it to Short and swap High with Low for shorts....Do you think that would work?

                      if (Position.MarketPosition == MarketPosition.Long)
                      {
                      for (int i = 1; i <5; i++)
                      {
                      if (High[i] > High[i-1] && High[i] > High[i+1])
                      swingHigh = High[i] + TickOffset * TickSize; // Where default TickOffset = 1;
                      break;
                      }
                      }​

                      Comment


                        #12
                        Hello,

                        Action:
                        • If the price breaks the last swing high by at least one tick (without waiting for the candle to close), display an up arrow for a Long signal.
                        • If the price breaks the last swing low by at least one tick, display a down arrow for a Short signal.
                        If you want to track Swing highs and lows, you can use the Swing indicator:



                        High Value
                        Swing(int strength).SwingHigh[int barsAgo]
                        Swing(ISeries<double> input, int strength).SwingHigh[int barsAgo]

                        Low Value
                        Swing(int strength).SwingLow[int barsAgo]
                        Swing(ISeries<double> input, int strength).SwingLow[int barsAgo]


                        Close[0] will be the current price of the currently forming bar if you are using Calculate.OnPriceChange or .OnEachTick. So to compare the price to the Swing + 1 tick, you could do something like:

                        if (Close[0] >= mySwingHigh + (1*TickSize)) // do something


                        Then, to draw up or down arrows, you can use the following Draw methods.





                        Please let us know if you have any further specific questions.
                        Last edited by NinjaTrader_Gaby; 02-17-2025, 12:28 PM.

                        Comment


                          #13
                          • break;
                            • Once a swing high is found, the loop is exited immediately using the break statement. This means that the code will only find the first swing high within the last 4 bars and then stop searching.
                          No if we don’t find a swing high after those 5. Closes, we wait for an another to form and to break it​

                          Comment


                            #14
                            Ok. so it's not the most recent of the swing highs. Are you looking for the highest swing high out of the 5 closes? Also, when you say 5 closes, assuming the current bar is [0], you are looking at High[1] - High[5]?
                            I suppose you can take out the break and it will keep searching and if there is another swing high, it will update swingHigh to the next one found. If nothing is found the loop will end and swingHigh will remain the last value it was assigned. On the next bar, it will search again using the most recent 5 closes.

                            Comment


                              #15
                              Here are some exemple to better undrrstand

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              65 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              139 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              75 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              45 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              50 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X