0% found this document useful (0 votes)
845 views17 pages

SuperTrend ULTIMATE - Bug Fixed

The document is a Pine Script code for a TradingView indicator called 'SuperTrend ULTIMATE', which includes various technical analysis tools such as SuperTrend, EMA, Ichimoku, RSI, and ADX. It allows users to customize parameters for different indicators and visualize market trends through various plots and colors. The script also includes functions for calculating and displaying market conditions based on the selected indicators.

Uploaded by

comomat2.0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
845 views17 pages

SuperTrend ULTIMATE - Bug Fixed

The document is a Pine Script code for a TradingView indicator called 'SuperTrend ULTIMATE', which includes various technical analysis tools such as SuperTrend, EMA, Ichimoku, RSI, and ADX. It allows users to customize parameters for different indicators and visualize market trends through various plots and colors. The script also includes functions for calculating and displaying market conditions based on the selected indicators.

Uploaded by

comomat2.0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 17

//@version=6

indicator('SuperTrend ULTIMATE', overlay = true, max_labels_count = 500)


import TradingView/ta/9

// DEBRIEF
//
//
//
//
//
//
//

//////////////////////////////////////////////////

//_____ PARAMETERS _____ //

// SUPERTREND //

atr_len = input.int(10, "ATR Length", group = "SuperTrend Settings")


fact = input.float(3, "SuperTrend Factor", group = "SuperTrend Settings")

training_data_period = input.int(100, "Training Data Length", group = "ATR


volatilité Settings")
highvol = input.float(0.75, "Initial High volatility Percentile Guess", maxval = 1,
group = "ATR volatilité Settings", tooltip = "The initial guess of where the
potential 'high volatility' area is, a value of 0.75 will take the 75th percentile
of the range of ATR values over the training data period")
midvol = input.float(0.5, "Initial Medium volatility Percentile Guess", maxval = 1,
group = "ATR volatilité Settings", tooltip = "The initial guess of where the
potential 'medium volatility' area is, a value of 0.5 will take the 50th percentile
of the range of ATR values over the training data period")
lowvol = input.float(0.25, "Initial Low volatility Percentile Guess", maxval = 1,
group = "ATR volatilité Settings", tooltip = "The initial guess of where the
potential 'low volatility' area is, a value of 0.25 will take the 25th percentile
of the range of ATR values over the training data period")

t1 = input.int(85, "Transparency 1", maxval = 100, minval = 0, group = "ST


Appearance")
t2 = input.int(100, "Transparency 2", maxval = 100, minval = 0, group = "ST
Appearance")
green = input.color(#00ffbb, "Bullish shadow", group = "ST Appearance")
red = input.color(#ff1100, "Bearish shadow", group = "ST Appearance")
green2 = input.color(#00ffbb, "Bullish line", group = "ST Appearance")
red2 = input.color(#ff1100, "Bearish line", group = "ST Appearance")

// EMA //

len1 = input.int(7, minval=1, title="EMA 1 Length", group =" EMA ")


ema1color = input.color(#64f1ea, title=" EMA 1 color ", group = " EMA ")

len2 = input.int(21, minval=1, title="EMA 2 Length",group =" EMA ")


ema2color = input.color(#2196f3, title=" EMA 2 color ", group = " EMA ")

len3 = input.int(70, minval=1, title="EMA 3 Length",group =" EMA ")


ema3color = input.color(#bb21f379, title=" EMA 3 color ", group = " EMA ")

len4 = input.int(200, minval=1, title="EMA 4 Length",group =" EMA ")


ema4color = input.color(#a9006b,title=" EMA 4 color ", group = " EMA ")

// KIJUN - ICHIMOKU //

conversionPeriods = input.int(9, minval=1, title="Conversion Line Length", group ="


KIJUN - ICHIMOKU ")
basePeriods = input.int(26, minval=1, title="Base Line Length", group =" KIJUN -
ICHIMOKU ")
laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length", group
=" KIJUN - ICHIMOKU ")
displacement = input.int(26, minval=1, title="Lagging Span", group =" KIJUN -
ICHIMOKU ")
Kijuncolor = input.color(color.rgb(247, 191, 38, 35), title="Kijun - base_Line",
group =" KIJUN - ICHIMOKU ")

// RSI OVERLOAD //

length = input.int(14, minval = 2, title="Lenght", group="RSI OB/OS")


smoType1 = input.string('RMA', 'Method', options = ['EMA', 'SMA', 'RMA', 'TMA'],
group="RSI OB/OS")
src_rsi = input(close, 'Source')

//Signal Line
smooth = input.int(14, minval = 1, title="smooth", group="RSI OB/OS")
smoType2 = input.string('EMA', 'Method', options = ['EMA', 'SMA', 'RMA', 'TMA'],
group = "RSI OB/OS")

//OB/OS Style
obValue = input.float(80, 'Overbought', inline = 'ob', group = "RSI OB/OS")
marker_color_ob = input.color(#00e6775c, title="Overbought Marker Color",
group="RSI OB/OS")

osValue = input.float(20, 'Oversold', inline = 'os', group = "RSI OB/OS")


marker_color_os = input.color(#ff000071, title="Oversold Marker Color",
group="RSI OB/OS")

// ADX + DIDI Pourcentage //

len = input.int(14, minval=1, title="ADX Length")


th = input.float(20, title="Threshold (Zero Level)")
th2 = input.float(30, title="Threshold (Zero Level)")

// STAT SuperTrend //

analysisLimit = input.int(100, title="Ratio-ST (+1%TP/-1%SL) ", group ="STAT


SuperTrend", tooltip="Choisie et analyse le nombre de trend du ST (bullish&bearish)
qui touche un TP de 1% vs SL de -1%")
target_percent_neg = input.float(1.0, title="Target SL (%)", group ="STAT
SuperTrend", minval=0.1, step=0.1) / 100
target_percent_pos = input.float(1.0, title="Target TP (%)", group ="STAT
SuperTrend", minval=0.1, step=0.1) / 100
target_percent_pos2 = input.float(1.0, title="Target TP2 (%)", group ="STAT
SuperTrend", minval=0.1, step=0.1) / 100
//////////////////////////////////////////////////

//_____ FONCTIONS & DISPLAY _____ //

//////////////////////////////////////////////////
// FONCTION EMA ------------------------->

ema1 = ta.ema(close, len1)


ema2 = ta.ema(close, len2)
ema3 = ta.ema(close, len3)
ema4 = ta.ema(close, len4)

// Vérification des croisements EMA 50/200 et EMA 7/21


ema_50_200 = ema3 > ema4 ? "BULL" : "BEAR" // Croisement EMA 50/200
ema_7_21 = ema1 > ema2 ? "BULL" : "BEAR" // Croisement EMA 7/21

// DISPLAY EMA ------------------------->

plot(ema1, title="EMA 1", color= ema1color)


plot(ema2, title="EMA 2", color= ema2color)
plot(ema3, title="EMA 3", color= ema3color)
plot(ema4, title="EMA 4", color= ema4color)

//////////////////////////////////////////////////

// FONCTION KIJUN - ICHIMOKU ------------------------->

// Calcul des lignes Ichimoku


donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)

// Détection des signaux basés sur la Kijun


kijun_trend = close > baseLine ? "BULL" : "BEAR"

// DISPLAY KIJUN - ICHIMOKU ------------------------->

// Affichage du nuage Ichimoku


plot(conversionLine, color=#7bc1fa00, title="Conversion Line")
plot(baseLine, color=Kijuncolor, title="base Line")
p1 = plot(leadLine1, offset = displacement - 1, color=#4caf4f00)
p2 = plot(leadLine2, offset = displacement - 1, color=#ff525200)
fill(p1, p2, color = leadLine1 > leadLine2 ? #43a04800 : #f4433600)

//////////////////////////////////////////////////

// FONCTION RSI OVERLOAD ------------------------->

ma(x, len, maType)=>


switch maType
'EMA' => ta.ema(x, len)
'SMA' => ta.sma(x, len)
'RMA' => ta.rma(x, len)
'TMA' => ta.sma(ta.sma(x, len), len)

//Augmented RSI
upper_rsi = ta.highest(src_rsi, length)
lower_rsi = ta.lowest(src_rsi, length)
r = upper_rsi - lower_rsi

d = src_rsi - src_rsi[1]
diff = upper_rsi > upper_rsi[1] ? r
: lower_rsi < lower_rsi[1] ? -r
: d

num = ma(diff, length, smoType1)


den = ma(math.abs(diff), length, smoType1)
arsi = num / den * 50 + 50

// DISPLAY RSI OVERLOAD ------------------------->

// Plot discreet markers for RSI overbought/oversold


plotshape(arsi > obValue ? arsi : na, style=shape.triangleup,
location=location.top, color=marker_color_ob, size=size.tiny, title="Overbought
Marker")
plotshape(arsi < osValue ? arsi : na, style=shape.triangledown,
location=location.top, color=marker_color_os, size=size.tiny, title="Oversold
Marker")

// color based on RSI percentage

RSI_percentage = math.min(math.max(arsi, 0), 100)

getColorForRSI(RSI_percentage) =>
if RSI_percentage >= 0 and RSI_percentage < 20
color.rgb(208, 0, 0) // Red shade for weaker market
else if RSI_percentage >= 20 and RSI_percentage < 50
#ff9500 // Orange for moderate strength
else if RSI_percentage >= 50 and RSI_percentage < 80
color.rgb(223, 253, 72) // Yellow for decent strength
else if RSI_percentage >= 80
color.rgb(0, 157, 5) // Green for strong market

RSI_color = getColorForRSI(RSI_percentage)

// Determine RSI Direction and Color


rsi_direction = arsi > nz(arsi[1]) ? "Bullish" : "Bearish"
rsi_arrow = arsi > nz(arsi[1]) ? "↑" : "↓"
rsi_direction_color = arsi > nz(arsi[1]) ? color.green : color.red

//////////////////////////////////////////////////

// FONCTION ADX & DIDI ------------------------->

// ADX Calculation
TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))),
math.abs(low - nz(close[1])))
DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high -
nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ?
math.max(nz(low[1]) - low, 0) : 0

SmoothedTrueRange = ta.rma(TrueRange, len)


SmoothedDirectionalMovementPlus = ta.rma(DirectionalMovementPlus, len)
SmoothedDirectionalMovementMinus = ta.rma(DirectionalMovementMinus, len)

DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100


DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
ADX = ta.sma(DX, len)

// Plotting logic for DI+ and DI- combined into one line
plotLine = DIPlus > DIMinus ? DIPlus : (DIMinus > DIPlus ? DIMinus : na) // Only
show the dominant DI line
plotColor = DIPlus > DIMinus ? color.green : color.red // Color green if DI+ is
above, red if DI- is above

// Calculate the ADX percentage


adx_percentage = (ADX - th) * 2 // Adjust the multiplier based on desired
sensitivity
DIDI_percentage = (plotLine - th) * 2 // Adjust the multiplier based on desired
sensitivity

// Condition for Range Detection


isRange = (ADX < th) //and (bbWidth < ta.atr(atrLen) * dynamicMult)

isWeakADX = (ADX >= th and ADX < th2 and plotLine < th2)

// DISPLAY ADX & DIDI ------------------------->

// BAR Colors [ WEAK Trend & RANGE Trend ]


rangeColor = isRange ? color.rgb(28, 0, 0) : na
WeakColor = isWeakADX ? (close > open ? color.rgb(186, 255, 91) : color.rgb(255,
111, 44)) : na

// Modification du barcolor avec la nouvelle condition


barcolor(isRange ? rangeColor : na)
barcolor(isWeakADX ? WeakColor : na)

// color based on ADX percentage


getColorForADX(percentage) =>
if percentage >= -40 and percentage < -20
color.rgb(226, 72, 0) // Red shade for weaker market
else if percentage >= -20 and percentage < 5
#ff9500 // Orange for moderate strength
else if percentage >= 5 and percentage < 40
color.rgb(223, 253, 72) // Yellow for decent strength
else if percentage >= 40 and percentage < 80
color.rgb(0, 157, 5) // Green for strong market
else if percentage >= 80 and percentage < 100
color.rgb(208, 55, 0) // For OverLoad market
else if percentage >= 100
color.rgb(208, 0, 0) // Red for OverLoad+ market

adx_color = getColorForADX(adx_percentage)

// Colors Direction ADX & DIDI : Ascendant ou Descendant


adxDirection = ADX > nz(ADX[1]) ? "↑" : "↓"
adxDirectionColor = ADX > nz(ADX[1]) ? color.green : color.red

DiDi_Direction = plotLine > nz(plotLine[1]) ? "↑" : "↓"


DiDi_DirectionColor = plotLine > nz(plotLine[1]) ? color.green : color.rgb(255,
200, 20)

//////////////////////////////////////////////////

// SUPERTREND Fonctions ------------------------->

// Variable ST //
var hi_time = int(na)
var lo_time = int(na)
var float entryPrice = na
var float entryPrice_n1 = na
var float entryPrice_n2 = na
var float entryPrice_n3 = na
var float previous_bearish_st = na
var float previous_bullish_st = na
var int trendBarCount = 0

// variable pour compter le temps de chaques trend


//var int previousTrendBarCount = na
//var int currentTrendDirection = na
//var int trend_start_time = na // Heure de début de la tendance
//var int trend_end_time = na // Heure de fin de la tendance
//var int candleDuration = 15 // Par exemple, 15 minutes pour des bougies de 15
minutes

// variable pour compter les stats (+1%/-1%)


var bool shapePlotted = false // Contrôle pour un seul plotshape par tendance
var bool shapePlotted_n2 = false
var bool shapePlotted_n3 = false
var int barIndexAtTrend = na
var int barIndexAtTrend_n2 = na
var int barIndexAtTrend_n3 = na
var int totalBullishHits = 0
var int totalBearishHits = 0
var table trendsTable = na
var string[] hitLog = array.new_string()
var string[] hitLog2 = array.new_string()
var string[] hitLog3 = array.new_string()
var allLogs = array.new_string(0)
var float posTh1 = na
var float negTh1 = na
var float posTh2 = na
var float negTh2 = na
var float posTh3 = na
var float negTh3 = na
var int bullneg_hits = 0
var int bullpos_hits = 0
var int bearneg_hits = 0
var int bearpos_hits = 0
var int bullneg_hits2 = 0
var int bullpos_hits2 = 0
var int bearneg_hits2 = 0
var int bearpos_hits2 = 0
var int bullneg_hits3 = 0
var int bullpos_hits3 = 0
var int bearneg_hits3 = 0
var int bearpos_hits3 = 0
// SuperTrend & ATR volatility Machine-Learning dynamic calcul //

// Super trend calcul //


pine_supertrend(factor, atr) =>
src = hl2
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])

lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ?


lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ?
upperBand : prevUpperBand
int _direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
_direction := 1
else if prevSuperTrend == prevUpperBand
_direction := close > upperBand ? -1 : 1
else
_direction := close < lowerBand ? 1 : -1
superTrend := _direction == -1 ? lowerBand : upperBand
[superTrend, _direction]

volatility = ta.atr(atr_len)

// ATR volatility Cluster calcul //


upper = ta.highest(volatility, training_data_period)
lower = ta.lowest(volatility, training_data_period)

high_volatility = lower + (upper-lower) * highvol


medium_volatility = lower + (upper-lower) * midvol
low_volatility = lower + (upper-lower) * lowvol

iterations = 0

size_a = 0
size_b = 0
size_c = 0

hv = array.new_float()
mv = array.new_float()
lv = array.new_float()
amean = array.new_float(1,high_volatility)
bmean = array.new_float(1,medium_volatility)
cmean = array.new_float(1,low_volatility)

if nz(volatility) > 0 and bar_index >= training_data_period-1

while ((amean.size() == 1 ? true : (amean.first() != amean.get(1))) or


(bmean.size() == 1 ? true : (bmean.first() != bmean.get(1))) or (cmean.size() ==
1 ? true : (cmean.first() != cmean.get(1))))
hv.clear()
mv.clear()
lv.clear()
for i = training_data_period-1 to 0
_1 = math.abs(volatility[i] - amean.first())
_2 = math.abs(volatility[i] - bmean.first())
_3 = math.abs(volatility[i] - cmean.first())
if _1 < _2 and _1 < _3
hv.unshift(volatility[i])

if _2 < _1 and _2 < _3


mv.unshift(volatility[i])

if _3 < _1 and _3 < _2


lv.unshift(volatility[i])

amean.unshift(hv.avg())
bmean.unshift(mv.avg())
cmean.unshift(lv.avg())
size_a := hv.size()
size_b := mv.size()
size_c := lv.size()
iterations := iterations + 1

hv_new = amean.first()
mv_new = bmean.first()
lv_new = cmean.first()
vdist_a = math.abs(volatility - hv_new)
vdist_b = math.abs(volatility - mv_new)
vdist_c = math.abs(volatility - lv_new)

distances = array.new_float()
centroids = array.new_float()

distances.push(vdist_a)
distances.push(vdist_b)
distances.push(vdist_c)

centroids.push(hv_new)
centroids.push(mv_new)
centroids.push(lv_new)

cluster = distances.indexof(distances.min()) // 0 for high, 1 for medium, 2 for low


assigned_centroid = cluster == -1 ? na : centroids.get(cluster)

[ST, dir] = pine_supertrend(fact, assigned_centroid)

// Condition d'alerte unique - Croisement des deux tendances


bullishTrendShift = ta.crossunder(dir, 0) and barstate.isconfirmed
bearishTrendShift = ta.crossover(dir, 0) and barstate.isconfirmed
trendAlert = bullishTrendShift or bearishTrendShift

// Détection du changement de tendance (bullish ou bearish)


if bullishTrendShift or bearishTrendShift
// Sauvegarder les valeurs des précédentes tendances
previous_bearish_st := bearishTrendShift ? ST[1] : previous_bearish_st
previous_bullish_st := bullishTrendShift ? ST[1] : previous_bullish_st

// Capturer le prix exact au début de la tendance précédente (qui vient de se


terminer)
entryPrice := bullishTrendShift ? previous_bearish_st : previous_bullish_st
///// compteur de Bar pour avoir la durée des tendances
//if trendAlert
///// Sauvegarder la durée de la tendance précédente
//previousTrendBarCount := trendBarCount

///// Réinitialiser le compteur pour la nouvelle tendance


//trendBarCount := 1
//currentTrendDirection := dir
//else
///// Incrémenter le compteur de bougies pour la tendance actuelle
//trendBarCount += 1

///// Calculer la durée en heures, minutes et jours (de chaque trend)


//trendDurationMinutes = previousTrendBarCount * candleDuration
//trendDurationDays = math.floor(trendDurationMinutes / 1440) // 1440 minutes dans
un jour
//trendDurationHours = math.floor((trendDurationMinutes % 1440) / 60) // Restant
en heures
//trendDurationMinutesOnly = trendDurationMinutes % 60 // Restant en minutes

// Calcule du Pourcentage des fluctuations (Plus HAUT & Plus BAS de chaque trend)
st_change = dir != dir[2]
hi = ta.highestSince(st_change, high)
hi_time := hi == high ? time : hi_time
lo = ta.lowestSince(st_change, low)
lo_time := lo == low ? time : lo_time

fluctuation_pct_high = (hi[2] - entryPrice) / entryPrice * 100


fluctuation_pct_low = (lo[2] - entryPrice) / entryPrice * 100

H_TP = "\nMAX TP : " + str.tostring(fluctuation_pct_high, "0.00") + "%"


H_SL = "\nMAX SL : " + str.tostring(fluctuation_pct_high, "0.00") + "%"
L_SL = "\nMAX SL : " + str.tostring(fluctuation_pct_low, "0.00") + "%"
L_TP = "\nMAX TP : " + str.tostring(fluctuation_pct_low, "0.00") + "%"
if trendAlert
label.new(bar_index, high, text = "Prix d'entrée : " + str.tostring(entryPrice,
"0.0000") + (dir == 1 ? H_TP : H_SL) + (dir == 1 ? L_SL : L_TP) , style=(dir == 1 ?
label.style_label_down : label.style_label_up), color=(dir == 1 ? color.rgb(0, 176,
6, 85) : color.rgb(183, 21, 0, 85)), textcolor=color.white, size=size.small,
yloc=(dir == 1 ? yloc.abovebar : yloc.belowbar))

// Fonction - calcul de Seuil +1%/-1% identifie la premiere bougie qui touchera


TP1% ou SL-1% de chaque tendance

// display label switch bull/bear trend //

BULLRATE_1 = bullishTrendShift
BEARRATE_1 = bearishTrendShift
BULLRATE_2 = BULLRATE_1 and ema3 > ema4
BEARRATE_2 = BEARRATE_1 and ema4 > ema3
BULLRATE_3 = BULLRATE_2 and ADX > th
BEARRATE_3 = BEARRATE_2 and ADX > th

var float priority_level = na


// Détection des signaux et gestion des priorités
priority_level := BULLRATE_3 ? 3 :
BULLRATE_2 ? 2 :
BULLRATE_1 ? 1 : na

priority_level := BEARRATE_3 ? -3 :
BEARRATE_2 ? -2 :
BEARRATE_1 ? -1 : priority_level

// Capture du prix d'entrée et des seuils lors d'un changement de tendance


if priority_level == 1
entryPrice_n1 := bullishTrendShift ? ST[1] : ST[1]
posTh1 := entryPrice_n1 * (1+target_percent_pos) // Seuil pour TP1%
negTh1 := entryPrice_n1 * (1-target_percent_neg) // Seuil pour SL1%
shapePlotted := false // Réinitialise le flag pour chaque nouvelle tendance
barIndexAtTrend := bar_index // Marque l'index de la première bougie de la
tendance

if priority_level == -1
entryPrice_n1 := bearishTrendShift ? ST[1] : ST[1]
posTh1 := entryPrice_n1 * (1+target_percent_neg) // Seuil pour SL1%
negTh1 := entryPrice_n1 * (1-target_percent_pos) // Seuil pour TP1%
shapePlotted := false // Réinitialise le flag pour chaque nouvelle tendance
barIndexAtTrend := bar_index // Marque l'index de la première bougie de la
tendance

if priority_level == 2
entryPrice_n2 := priority_level == 2 ? ST[1] : ST[1]
posTh2 := entryPrice_n2 * (1+target_percent_pos) // Seuil pour TP1%
negTh2 := entryPrice_n2 * (1-target_percent_neg) // Seuil pour SL1%
shapePlotted_n2 := false // Réinitialise le flag pour chaque nouvelle tendance
barIndexAtTrend_n2 := bar_index // Marque l'index de la première bougie de la
tendance

if priority_level == -2
entryPrice_n2 := priority_level == -2 ? ST[1] : ST[1]
posTh2 := entryPrice_n2 * (1+target_percent_neg) // Seuil pour SL1%
negTh2 := entryPrice_n2 * (1-target_percent_pos) // Seuil pour TP1%
shapePlotted_n2 := false // Réinitialise le flag pour chaque nouvelle tendance
barIndexAtTrend_n2 := bar_index // Marque l'index de la première bougie de la
tendance

if priority_level == 3
entryPrice_n3 := priority_level == 3 ? ST[1] : ST[1]
posTh3 := entryPrice_n3 * (1+target_percent_pos) // Seuil pour TP1%
negTh3 := entryPrice_n3 * (1-target_percent_neg) // Seuil pour SL1%
shapePlotted_n3 := false // Réinitialise le flag pour chaque nouvelle tendance
barIndexAtTrend_n3 := bar_index // Marque l'index de la première bougie de la
tendance

if priority_level == -3
entryPrice_n2 := priority_level == -3 ? ST[1] : ST[1]
posTh3 := entryPrice_n3 * (1+target_percent_neg) // Seuil pour SL1%
negTh3 := entryPrice_n3 * (1-target_percent_pos) // Seuil pour TP1%
shapePlotted_n3 := false // Réinitialise le flag pour chaque nouvelle tendance
barIndexAtTrend_n3 := bar_index // Marque l'index de la première bougie de la
tendance
// Détection de la première bougie atteignant les seuils (excluant la première
bougie de la tendance)
bool isAfterFirstBar = bar_index > barIndexAtTrend
bool bearishHit_n1 = isAfterFirstBar and not shapePlotted and dir == 1 and (high >=
posTh1 or low <= negTh1)
bool bullishHit_n1 = isAfterFirstBar and not shapePlotted and dir == -1 and (low <=
negTh1 or high >= posTh1)
bool isAfterFirstBar_n2 = bar_index > barIndexAtTrend_n2
bool bearishHit_n2 = isAfterFirstBar_n2 and not shapePlotted_n2 and dir == 1 and
(high >= posTh2 or low <= negTh2)
bool bullishHit_n2 = isAfterFirstBar_n2 and not shapePlotted_n2 and dir == -1 and
(low <= negTh2 or high >= posTh2)
bool isAfterFirstBar_n3 = bar_index > barIndexAtTrend_n3
bool bearishHit_n3 = isAfterFirstBar_n3 and not shapePlotted_n3 and dir == 1 and
(high >= posTh3 or low <= negTh3)
bool bullishHit_n3 = isAfterFirstBar_n3 and not shapePlotted_n3 and dir == -1 and
(low <= negTh3 or high >= posTh3)

// Fonction pour récupérer le bar_index à partir d'une entrée


bar_index_from_entry(entry)=>
int(str.split(entry, "|")[1])

// Fonction pour fusionner les logs


allLogsLocal = array.new_string()

mergeLogs(log1, log2, log3) =>


// Ajouter les éléments des trois logs
for i = 0 to array.size(hitLog) - 1
array.push(allLogsLocal, array.get(hitLog, i))
for i = 0 to array.size(hitLog2) - 1
array.push(allLogsLocal, array.get(hitLog2, i))
for i = 0 to array.size(hitLog3) - 1
array.push(allLogsLocal, array.get(hitLog3, i))

allLogsLocal

// Trier le tableau combiné par ordre chronologique (bar_index)


sorted_indices = array.sort_indices(allLogs)
sorted_allLogs = array.new_string()

for i = 0 to array.size(sorted_indices) - 1
array.push(sorted_allLogs, array.get(allLogs, array.get(sorted_indices, i)))

// Réaffecter allLogs avec les éléments triés


allLogs := mergeLogs(hitLog, hitLog2, hitLog3)

// Fonction pour limiter la taille du tableau à la limite spécifiée


limitTotalLogsToAnalysisLimit(allLogs, analysisLimit) =>
// Limiter la taille de allLogs à la limite spécifiée
while array.size(allLogs) > analysisLimit
array.shift(allLogs)

// Réaffecter les éléments dans les tableaux respectifs selon leur type
array.clear(hitLog)
array.clear(hitLog2)
array.clear(hitLog3)

for i = 0 to array.size(allLogs) - 1
string entry = array.get(allLogs, i)
if str.startswith(entry, "bullnegn1") or str.startswith(entry, "bearnegn1")
or str.startswith(entry, "bullposn1") or str.startswith(entry, "bearposn1")
array.push(hitLog, entry)
else if str.startswith(entry, "bullnegn2") or str.startswith(entry,
"bearnegn2") or str.startswith(entry, "bullposn2") or str.startswith(entry,
"bearposn2")
array.push(hitLog2, entry)
else if str.startswith(entry, "bullnegn3") or str.startswith(entry,
"bearnegn3") or str.startswith(entry, "bullposn3") or str.startswith(entry,
"bearposn3")
array.push(hitLog3, entry)

// Logique de traitement des entrées


if bearishHit_n1 or bullishHit_n1
shapePlotted := true // Empêche d'autres plotshape pour cette tendance

if bullishHit_n1
if low <= negTh1
array.push(hitLog, "bullnegn1|" + str.tostring(bar_index))
if high >= posTh1
array.push(hitLog, "bullposn1|" + str.tostring(bar_index))
if bearishHit_n1
if low <= negTh1
array.push(hitLog, "bearnegn1|" + str.tostring(bar_index))
if high >= posTh1
array.push(hitLog, "bearposn1|" + str.tostring(bar_index))

if bearishHit_n2 or bullishHit_n2
shapePlotted_n2 := true // Empêche d'autres plotshape pour cette tendance

if bullishHit_n2
if low <= negTh2
array.push(hitLog2, "bullnegn2|" + str.tostring(bar_index))
if high >= posTh2
array.push(hitLog2, "bullposn2|" + str.tostring(bar_index))
if bearishHit_n2
if low <= negTh2
array.push(hitLog2, "bearnegn2|" + str.tostring(bar_index))
if high >= posTh2
array.push(hitLog2, "bearposn2|" + str.tostring(bar_index))

if bearishHit_n3 or bullishHit_n3
shapePlotted_n3 := true // Empêche d'autres plotshape pour cette tendance

if bullishHit_n3
if low <= negTh3
array.push(hitLog3, "bullnegn3|" + str.tostring(bar_index))
if high >= posTh3
array.push(hitLog3, "bullposn3|" + str.tostring(bar_index))
if bearishHit_n3
if low <= negTh3
array.push(hitLog3, "bearnegn3|" + str.tostring(bar_index))
if high >= posTh3
array.push(hitLog3, "bearposn3|" + str.tostring(bar_index))

// Fusionner les logs, trier et limiter la taille

limitTotalLogsToAnalysisLimit(allLogs, analysisLimit)
// Pourcentage des seuils ( TP et SL )

totalHits = ( bullneg_hits + bullneg_hits2 + bullneg_hits3) + (bullpos_hits +


bullpos_hits2 + bullpos_hits3) + (bearneg_hits + bearneg_hits2 + bearneg_hits3) +
(bearpos_hits + bearpos_hits2 + bearpos_hits3)

totalHits_n1 = bullneg_hits + bullpos_hits + bearneg_hits + bearpos_hits


totalHits_n2 = bullneg_hits2 + bullpos_hits2 + bearneg_hits2 + bearpos_hits2
totalHits_n3 = bullneg_hits3 + bullpos_hits3 + bearneg_hits3 + bearpos_hits3

calculate_percentage(hits, total) =>


na(total) or total == 0 ? 0 : (hits / total) * 100

bullneg_percentage = calculate_percentage(bullneg_hits, totalHits)


bullpos_percentage = calculate_percentage(bullpos_hits, totalHits)
bearneg_percentage = calculate_percentage(bearneg_hits, totalHits)

bearpos_percentage = calculate_percentage (bearpos_hits, totalHits)


bullneg_percentage_n2 = calculate_percentage(bullneg_hits2, totalHits)
bullpos_percentage_n2 = calculate_percentage(bullpos_hits2, totalHits)
bearneg_percentage_n2 = calculate_percentage (bearneg_hits2, totalHits)
bearpos_percentage_n2 = calculate_percentage(bearpos_hits2, totalHits)
bullneg_percentage_n3 = calculate_percentage(bullneg_hits3, totalHits)
bullpos_percentage_n3 = calculate_percentage(bullpos_hits3, totalHits)
bearneg_percentage_n3 = calculate_percentage(bearneg_hits3, totalHits)
bearpos_percentage_n3 = calculate_percentage (bearpos_hits3, totalHits)
// Calcul du pourcentage total des hits
STU_TT_neg_Percentage = bearpos_percentage + bullneg_percentage +
bearpos_percentage_n2 + bullneg_percentage_n2 + bearpos_percentage_n3 +
bullneg_percentage_n3
STU_TT_Pos_Percentage = bearneg_percentage + bullpos_percentage +
bearneg_percentage_n2 + bullpos_percentage_n2 + bearneg_percentage_n3 +
bullpos_percentage_n3
// Calcul du pourcentage des hits positif
STU_TT_pos_Percentage_n1 = calculate_percentage ((bullpos_hits + bearneg_hits),
totalHits_n1)
STU_TT_pos_Percentage_n2 = calculate_percentage ((bullpos_hits2 + bearneg_hits2),
totalHits_n2)
STU_TT_pos_Percentage_n3 = calculate_percentage ((bullpos_hits3 + bearneg_hits3),
totalHits_n3)

// DISPLAY SUPERTREND ------------------------->

// display color Supertrend line //


upTrend = plot(close > ST ? ST : na, color = color.new(green, t1), style =
plot.style_linebr) //, force_overlay = true
downTrend = plot(close < ST ? ST : na, color = color.new(red, t1), style =
plot.style_linebr, force_overlay = false) //, force_overlay = true
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, "Body Middle",display
= display.none)

upTrend2 = plot(close > ST ? ST : na, color = green2, style =


plot.style_linebr) //, force_overlay = true
downTrend2 = plot(close < ST ? ST : na, color = red2, style = plot.style_linebr,
force_overlay = false) //, force_overlay = true

// display color fill_trend //


fill(bodyMiddle, upTrend, (open + close) / 2, ST, color.new(green, t2),
color.new(green, t1))
fill(bodyMiddle, downTrend, ST, (open + close) / 2, color.new(red, t1),
color.new(red, t2))

// supertrend stat //
// display // ATR volatility colors // table
volatilityColor = cluster == 0 ? color.green : (cluster == 1 ? color.yellow :
color.orange)
volatilityText = cluster == 0 ? "HIGH" : (cluster == 1 ? "MIDIUM" : "LOW")

// DISPLAY // TABLE // STU 1% STAT // Mise à jour du tableau des tendances


percentage = na(STU_TT_Pos_Percentage) ? na : STU_TT_Pos_Percentage
percentage := na(STU_TT_pos_Percentage_n1) ? percentage : STU_TT_pos_Percentage_n1
percentage := na(STU_TT_pos_Percentage_n2) ? percentage : STU_TT_pos_Percentage_n2
percentage := na(STU_TT_pos_Percentage_n3) ? percentage : STU_TT_pos_Percentage_n3

getColorForSTUPercentage(percentage) =>
if percentage >= 1 and percentage < 40
color.rgb(226, 0, 0)
else if percentage >= 40 and percentage < 50
#ff9500
else if percentage >= 50 and percentage < 60
color.rgb(223, 253, 72)
else
color.rgb(0, 157, 5)

// Détermination de la couleur en fonction de positivePercentage


txt_color = getColorForSTUPercentage(percentage)

//////////////////////////////////////////////////

// SUPER_STAT //

// DISPLAY // LABEL STAT DATA TRENDS

plotshape(priority_level == 3,"Bullish Trend [3]", shape.labelup, location.bottom,


color = #132d0078, text = "[3]", textcolor = #00ff4c, size = size.tiny)
plotshape(priority_level == -3,"Bearish Trend [3]", shape.labelup, location.bottom,
color = #6c000080, text = "[3]", textcolor = #ff0000, size = size.tiny)
plotshape(priority_level == 2,"Bullish Trend [2]", shape.labelup, location.bottom,
color = #132d0078, text = "[2]", textcolor = #00ff4c, size = size.tiny)
plotshape(priority_level == -2,"Bearish Trend [2]", shape.labelup, location.bottom,
color = #6c000080, text = "[2]", textcolor = #ff0000, size = size.tiny)
plotshape(priority_level == 1,"Bullish Trend [1]", shape.labelup, location.bottom,
color = #132d0078, text = "[1]", textcolor = #00ff4c, size = size.tiny)
plotshape(priority_level == -1,"Bearish Trend [1]", shape.labelup, location.bottom,
color = #6c000080, text = "[1]", textcolor = #ff0000, size = size.tiny)

// DISPLAY - seuil TP%/SL% // PlotShape avec conditions adaptées


plotshape(bearishHit_n1 and high >= posTh1, "Bearish SL", shape.labelup,
location.belowbar, color = #6c000080, text = "sl", textcolor = #ff0000, size =
size.tiny)
plotshape(bearishHit_n1 and low <= negTh1, "Bearish tp1", shape.labelup,
location.belowbar, color = #132d0078, text = "t1", textcolor = #00ff4c, size =
size.tiny)
plotshape(bullishHit_n1 and low <= negTh1, "Bullish SL", shape.labeldown,
location.abovebar, color = #6c000080, text = "sl", textcolor = #ff0000, size =
size.tiny)
plotshape(bullishHit_n1 and high >= posTh1, "Bullish tp1",shape.labeldown,
location.abovebar, color = #132d0078, text = "t1", textcolor = #00ff4c, size =
size.tiny)
plotshape(bearishHit_n2 and high >= posTh2, "Bearish SL", shape.labelup,
location.belowbar, color = #6c000080, text = "sl", textcolor = color.rgb(255, 251,
0), size = size.tiny)
plotshape(bearishHit_n2 and low <= negTh2, "Bearish tp1", shape.labelup,
location.belowbar, color = #132d0078, text = "t1", textcolor = color.rgb(132, 0,
255), size = size.tiny)
plotshape(bullishHit_n2 and low <= negTh2, "Bullish SL", shape.labeldown,
location.abovebar, color = #6c000080, text = "sl", textcolor = color.rgb(246, 255,
0), size = size.tiny)
plotshape(bullishHit_n2 and high >= posTh2, "Bullish tp1",shape.labeldown,
location.abovebar, color = #132d0078, text = "t1", textcolor = color.rgb(132, 0,
255), size = size.tiny)
plotshape(bearishHit_n3 and high >= posTh3, "Bearish SL", shape.labelup,
location.belowbar, color = #6c000080, text = "sl", textcolor = color.rgb(0, 225,
255), size = size.tiny)
plotshape(bearishHit_n3 and low <= negTh3, "Bearish tp1", shape.labelup,
location.belowbar, color = #132d0078, text = "t1", textcolor = #f700ff, size =
size.tiny)
plotshape(bullishHit_n3 and low <= negTh3, "Bullish SL", shape.labeldown,
location.abovebar, color = #6c000080, text = "sl", textcolor = #00eaff, size =
size.tiny)
plotshape(bullishHit_n3 and high >= posTh3, "Bullish tp1",shape.labeldown,
location.abovebar, color = #132d0078, text = "t1", textcolor = #ff00d4, size =
size.tiny)

//////////////////////////////////////////////////

//_____ TABLE DISPLAY _____ //

//MIDDLE TABLE //

var table Strength_table = table.new(position.top_right, columns=2, rows=13,


border_width=1)
if bar_index == 0
table.cell(Strength_table, 0, 0)
table.cell(Strength_table, 1, 0)

// Displaying ADX percentage with dynamic color


table.cell(Strength_table, 0, 1, text="strength", text_color=color.rgb(105, 105,
105, 11), bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 1, text=adx_percentage < 0 ? "RANGE" : adx_percentage
< 20 ? "Weak" : adx_percentage < 40 ? "Strong" : adx_percentage < 80 ? "Heavy" :
"OverLoad", text_color=adx_color, bgcolor=color.rgb(0, 0, 0, 49))

table.cell(Strength_table, 0, 2, text="adx "+ adxDirection,


text_color=adxDirectionColor, bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 2, text=str.tostring(adx_percentage, "#.##")+"%",
text_color=adx_color, bgcolor=color.rgb(0, 0, 0, 49))

// Displaying the DI+ / DI- ratio and its color


table.cell(Strength_table, 0, 3, text=(DIPlus > DIMinus ?"Di+ " : "Di- ") +
DiDi_Direction, text_color=DiDi_DirectionColor, bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 3, text=str.tostring(DIDI_percentage, "#.##")+"%",
text_color=plotColor, bgcolor=color.rgb(0, 0, 0, 49))
// ATR
table.cell(Strength_table, 0, 4, text="ATR vol.", text_color=color.white,
bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 4, text=volatilityText, text_color=volatilityColor,
bgcolor=color.rgb(0, 0, 0, 49))

// RSI
table.cell(Strength_table, 0, 5, text="RSI " + rsi_arrow,
text_color=rsi_direction_color, bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 5, text=str.tostring(math.round(arsi, 2)) + "%",
text_color=RSI_color, bgcolor=color.rgb(0, 0, 0, 49))

// Croisement EMA 50/200


table.cell(Strength_table, 0, 6, text="EMA [200]", text_color=color.white,
bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 6, text=ema_50_200, text_color=ema_50_200 == "BULL" ?
color.green : color.red, bgcolor=color.rgb(0, 0, 0, 49))

// Croisement EMA 7/21


table.cell(Strength_table, 0, 7, text="EMA [7/21]", text_color=color.white,
bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 7, text=ema_7_21, text_color=ema_7_21 == "BULL" ?
color.green : color.red, bgcolor=color.rgb(0, 0, 0, 49))

// Signal basé sur la Kijun


table.cell(Strength_table, 0, 8, text="KIJUN", text_color=color.white,
bgcolor=color.rgb(0, 0, 0, 49))
table.cell(Strength_table, 1, 8, text=kijun_trend, text_color=kijun_trend == "BULL"
? color.green : color.red, bgcolor=color.rgb(0, 0, 0, 49))

// STU % STAT //
table.cell(Strength_table, 0, 9, "STU TT G00D", bgcolor=color.rgb(0, 0, 0, 49),
text_color=color.white)
table.cell(Strength_table, 1, 9, str.tostring(STU_TT_Pos_Percentage, "#.##") + "%",
bgcolor=color.rgb(0, 0, 0, 49), text_color=txt_color)
table.cell(Strength_table, 0, 10, "STU [n1]", bgcolor=color.rgb(0, 0, 0, 49),
text_color=color.white)
table.cell(Strength_table, 1, 10, str.tostring(STU_TT_pos_Percentage_n1, "#.##") +
"%", bgcolor=color.rgb(0, 0, 0, 49), text_color=txt_color)
table.cell(Strength_table, 0, 11, "STU [n2]", bgcolor=color.rgb(0, 0, 0, 49),
text_color=color.white)
table.cell(Strength_table, 1, 11, str.tostring(STU_TT_pos_Percentage_n2, "#.##") +
"%", bgcolor=color.rgb(0, 0, 0, 49), text_color=txt_color)
table.cell(Strength_table, 0, 12, "STU [n3]", bgcolor=color.rgb(0, 0, 0, 49),
text_color=color.white)
table.cell(Strength_table, 1, 12, str.tostring(STU_TT_pos_Percentage_n3, "#.##") +
"%", bgcolor=color.rgb(0, 0, 0, 49), text_color=txt_color)

////////////////////////// ALERTS

//supertrend croisement //

// Création du message JSON pour l'alerte


valeur = close
exchange = syminfo.prefix
ticker = syminfo.ticker
trendType = bullishTrendShift ? "Bullish Trend Shift" : "Bearish Trend Shift"
jsonMessage = '{"exchange": "' + exchange + '", "monnaie": "' + ticker + '",
"valeur": ' + str.tostring(valeur) + ', "trendType": "' + trendType + '"}'
// Définir une condition d'alerte avec un message constant
alertcondition(true, title="Alerte Supertrend", message="Alerte")

// Afficher une notification toast avec JSON à chaque nouvelle barre confirmée
if barstate.isconfirmed and trendAlert
alert(jsonMessage, alert.freq_once_per_bar_close)

////////////////////////

You might also like