[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
Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
Converting Tradingview to Ninjascript, can someone help me?
Collapse
X
-
Code:
-
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.
Leave a comment:
-
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.
Leave a comment:
-
Converting Tradingview to Ninjascript, can someone help me?
[/CODE]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) Last edited by Babbou72; 02-15-2025, 08:41 PM.Tags: None
Latest Posts
Collapse
| Topics | Statistics | Last Post | ||
|---|---|---|---|---|
|
Started by DannyP96, 05-18-2026, 02:38 PM
|
1 response
93 views
0 likes
|
Last Post
|
||
|
Started by CarlTrading, 05-11-2026, 05:56 AM
|
0 responses
144 views
0 likes
|
Last Post
by CarlTrading
05-11-2026, 05:56 AM
|
||
|
Started by CarlTrading, 05-10-2026, 08:12 PM
|
0 responses
83 views
0 likes
|
Last Post
by CarlTrading
05-10-2026, 08:12 PM
|
||
|
Started by Hwop38, 05-04-2026, 07:02 PM
|
0 responses
257 views
0 likes
|
Last Post
by Hwop38
05-04-2026, 07:02 PM
|
||
|
Started by Mindset, 04-21-2026, 06:46 AM
|
0 responses
337 views
0 likes
|
Last Post
by Mindset
04-21-2026, 06:46 AM
|

Leave a comment: