//@version=5
// ─────────────────────────────────────────────────────────────────────────────
//  ORIGIN — HalfTrend + Laguerre RSI
//  Free, from Origin Explains Charts · https://t.me/originexplainscharts
//
//  This is the SAME algorithm as the MT5 robot in this zip
//  (OriginLaguerre.mq5) and as the chart in the video. One set of rules:
//
//    TOOL 1   HalfTrend (Amplitude 5, Channel Deviation 2).
//             The trend line is BLUE (bullish trend = 1).
//
//    TOOL 2   Laguerre RSI (Alpha 0.20, Gamma 0.80).
//             The smooth meter dips into the floor (< 20.00) and crosses
//             back ABOVE 20.00 on the finished candle.
//
//    ENTRY    Both conditions agree on the SAME closed candle. Buy at that
//             candle's close.
//
//    STOP     Placed under the recent swing low where price turned.
//
//    TARGET   Fixed at two times the risk (1:2 Risk/Reward ratio).
//
//    Sells mirror: HalfTrend is RED (bearish trend = -1), Laguerre RSI dips
//    from above the ceiling (> 80.00) and crosses back BELOW 80.00. Stop
//    above the recent swing high, target 2x risk.
//
//  HOW TO ADD IT: Open TradingView (1-Hour chart recommended), open the
//  Pine Editor tab at the bottom, paste this code in, and click "Add to chart".
// ─────────────────────────────────────────────────────────────────────────────
indicator("Origin — HalfTrend + Laguerre RSI", overlay = true, max_lines_count = 500, max_labels_count = 500)

// ─── Inputs ──────────────────────────────────────────────────────────────────
grp1 = "1 · HalfTrend Settings"
amplitude   = input.int(5,     "Amplitude",           minval = 1, group = grp1)
channelDev  = input.float(2.0, "Channel Deviation",   minval = 0.5, step = 0.5, group = grp1)
showChannels= input.bool(true, "Show ATR Channels",   group = grp1)

grp2 = "2 · Laguerre RSI Settings"
alpha       = input.float(0.20,"Alpha (Gamma = 1 - Alpha)", minval = 0.01, maxval = 1.0, step = 0.05, group = grp2)
oversold    = input.float(20.0,"Oversold Level",       minval = 5.0, maxval = 40.0, step = 5.0, group = grp2)
overbought  = input.float(80.0,"Overbought Level",     minval = 60.0, maxval = 95.0, step = 5.0, group = grp2)

grp3 = "3 · Trade Management"
rr          = input.float(2.0, "Risk/Reward Ratio (x Risk)", minval = 0.5, step = 0.5, group = grp3)
swingBars   = input.int(5,     "Swing High/Low Lookback",    minval = 2, maxval = 20, group = grp3)
wantLong    = input.bool(true, "Enable Buy Signals",         group = grp3)
wantShort   = input.bool(true, "Enable Sell Signals",        group = grp3)

grp4 = "4 · Visual Styling"
fwdBars     = input.int(12,    "Draw Plan (Bars Forward)",   minval = 3, group = grp4)
colUp       = input.color(#2962FF, "Bullish Trend / Buy",    group = grp4)
colDn       = input.color(#F23645, "Bearish Trend / Sell",   group = grp4)

// ─── 1 · HalfTrend Calculation ───────────────────────────────────────────────
atrPeriod = 100
atrVal    = ta.atr(atrPeriod)

var int   htTrend       = 1
var int   nextTrend     = 1
var float maxLowPrice   = low
var float minHighPrice  = high
var float htLine        = close

highestHigh = ta.highest(high, amplitude)
lowestLow   = ta.lowest(low, amplitude)
dev         = channelDev * atrVal

if bar_index >= amplitude
    if nextTrend == 1
        maxLowPrice := math.max(lowestLow, maxLowPrice)
        if highestHigh < maxLowPrice and close < low[1]
            htTrend      := -1
            nextTrend    := 0
            minHighPrice := highestHigh
    else
        minHighPrice := math.min(highestHigh, minHighPrice)
        if lowestLow > minHighPrice and close > high[1]
            htTrend      := 1
            nextTrend    := 1
            maxLowPrice  := lowestLow

    htLine := htTrend == 1 ? maxLowPrice : minHighPrice

upChannel   = htLine + dev
downChannel = htLine - dev

plot(htLine, "HalfTrend Line", color = htTrend == 1 ? colUp : colDn, linewidth = 2)
plot(showChannels ? upChannel : na, "HalfTrend Upper Channel", color = color.new(colUp, 70), style = plot.style_circles)
plot(showChannels ? downChannel : na, "HalfTrend Lower Channel", color = color.new(colDn, 70), style = plot.style_circles)

// ─── 2 · Laguerre RSI Calculation ────────────────────────────────────────────
gamma = 1.0 - alpha
var float l0 = 0.0
var float l1 = 0.0
var float l2 = 0.0
var float l3 = 0.0

prevL0 = nz(l0[1], close)
prevL1 = nz(l1[1], close)
prevL2 = nz(l2[1], close)
prevL3 = nz(l3[1], close)

l0 := (1.0 - gamma) * close + gamma * prevL0
l1 := -gamma * l0 + prevL0 + gamma * prevL1
l2 := -gamma * l1 + prevL1 + gamma * prevL2
l3 := -gamma * l2 + prevL2 + gamma * prevL3

cu = 0.0
cd = 0.0
if l0 >= l1
    cu := cu + (l0 - l1)
else
    cd := cd + (l1 - l0)

if l1 >= l2
    cu := cu + (l1 - l2)
else
    cd := cd + (l2 - l1)

if l2 >= l3
    cu := cu + (l2 - l3)
else
    cd := cd + (l3 - l2)

denom = cu + cd
lrsi = denom != 0.0 ? (cu / denom) * 100.0 : 0.0

// ─── 3 · Signal Detection ────────────────────────────────────────────────────
// LRSI crossover conditions (scaled 0-100)
lrsiCrossUp   = ta.crossover(lrsi, oversold)
lrsiCrossDown = ta.crossunder(lrsi, overbought)

longTrigger  = wantLong and htTrend == 1 and lrsiCrossUp
shortTrigger = wantShort and htTrend == -1 and lrsiCrossDown

plotshape(longTrigger,  title = "Buy Signal",  location = location.belowbar, color = colUp, style = shape.triangleup,   size = size.normal, text = "BUY")
plotshape(shortTrigger, title = "Sell Signal", location = location.abovebar, color = colDn, style = shape.triangledown, size = size.normal, text = "SELL")

// ─── 4 · Visual Trade Plan ───────────────────────────────────────────────────
var line  lnEntry = na
var line  lnStop  = na
var line  lnTgt   = na

if longTrigger
    swingLow = ta.lowest(low, swingBars)
    stopVal  = math.min(swingLow, htLine)
    entryVal = close
    riskVal  = entryVal - stopVal
    tgtVal   = entryVal + riskVal * rr
    
    line.delete(lnEntry)
    line.delete(lnStop)
    line.delete(lnTgt)
    
    lnEntry := line.new(bar_index, entryVal, bar_index + fwdBars, entryVal, color = color.gray, width = 1, style = line.style_dotted)
    lnStop  := line.new(bar_index, stopVal,  bar_index + fwdBars, stopVal,  color = colDn,      width = 2)
    lnTgt   := line.new(bar_index, tgtVal,   bar_index + fwdBars, tgtVal,   color = colUp,      width = 2)

if shortTrigger
    swingHigh = ta.highest(high, swingBars)
    stopVal   = math.max(swingHigh, htLine)
    entryVal  = close
    riskVal   = stopVal - entryVal
    tgtVal    = entryVal - riskVal * rr
    
    line.delete(lnEntry)
    line.delete(lnStop)
    line.delete(lnTgt)
    
    lnEntry := line.new(bar_index, entryVal, bar_index + fwdBars, entryVal, color = color.gray, width = 1, style = line.style_dotted)
    lnStop  := line.new(bar_index, stopVal,  bar_index + fwdBars, stopVal,  color = colDn,      width = 2)
    lnTgt   := line.new(bar_index, tgtVal,   bar_index + fwdBars, tgtVal,   color = colUp,      width = 2)
