PROTECTED SOURCE SCRIPT

Trend Duration (Top-Right) — Fixed

16
//version=5
indicator("Trend Duration (Top-Right) — Fixed", overlay=true)

// === Input ===
maLen = input.int(50, "MA Length", minval=1)
maType = input.string("EMA", "MA Type", options=["SMA", "EMA"])
showBox = input.bool(true, "Show status box (top-right)")

// === MA calculation ===
ma = maType == "EMA" ? ta.ema(close, maLen) : ta.sma(close, maLen)
plot(ma, "MA", color=color.orange, linewidth=2)

// === Trend detection ===
isUp = close > ma
isDown = close < ma

// === Persistent state ===
var string curTrend = "NONE"
var int startBarIndex = na

if barstate.isconfirmed
if isUp and curTrend != "UP"
curTrend := "UP"
startBarIndex := bar_index
else if isDown and curTrend != "DOWN"
curTrend := "DOWN"
startBarIndex := bar_index

// === Duration calculation ===
// Hitung jumlah bar sejak trend mulai
barsPassed = na(startBarIndex) ? 0 : bar_index - startBarIndex
// Konversi ke menit sesuai TF chart
minutesPassed = barsPassed * timeframe.multiplier
hours = math.floor(minutesPassed / 60)
mins = minutesPassed - hours * 60
durText = (hours > 0 ? str.tostring(hours) + "h " : "") + str.tostring(mins) + "m"

// === Build table (top-right) ===
var table t = table.new(position.top_right, 1, 2, border_width = 1)

if showBox
bg = curTrend == "UP" ? color.new(color.green, 0) : curTrend == "DOWN" ? color.new(color.red, 0) : color.new(color.gray, 0)
table.cell(t, 0, 0, "Trend: " + curTrend, text_color = color.white, bgcolor = bg, text_size = size.normal)
table.cell(t, 0, 1, "Duration: " + durText, text_color = color.white, bgcolor = bg, text_size = size.normal)

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.