Laguerre Pulse | Trend, Structure & Pressure Strategy

blitz_algo · strategy · 482 行 · 点赞 80 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// Laguerre Pulse | Trend, Structure & Pressure Strategy
//
// Idea: trade pullbacks and momentum resumes in the direction of a smooth trend.
//   1. Trend    : a Laguerre filter plus an EMA ribbon decide long or short bias.
//   2. Location : swing highs/lows become support/resistance zones to trade from.
//   3. Trigger  : zone retest, MACD cross, or the trend flip itself.
//   4. Filter   : candle-based buy/sell pressure must agree with the trade.
//   5. Exits    : ATR stop, R-multiple target, optional ATR trail, optional flip exit.
// ─────────────────────────────────────────────────────────────────────────────
strategy("Laguerre Pulse | Trend, Structure & Pressure Strategy", shorttitle = "Laguerre Pulse", overlay = true,
     max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500,
     initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100,
     commission_type = strategy.commission.percent, commission_value = 0.05, slippage = 1,
     pyramiding = 0, margin_long = 0, margin_short = 0,
     calc_on_every_tick = false, process_orders_on_close = false)
 
// ───────────────────────────── Input groups ─────────────────────────────
const string g1 = "Trend Engine"
const string g2 = "Structure Levels"
const string g3 = "Pressure Filter"
const string g4 = "MACD Trigger"
const string g5 = "Entries"
const string g6 = "Risk & Exits"
const string g7 = "Display"
 
// ───────────────────────────── Inputs ─────────────────────────────
// Trend engine
float src         = input.source(hlc3, "Source", group = g1)
float gamma       = input.float(0.72, "Laguerre Gamma", minval = 0.10, maxval = 0.95, step = 0.01, group = g1, tooltip = "Higher = smoother and slower trend line.")
int   ribbonLen   = input.int(8, "Ribbon Length", minval = 2, group = g1, tooltip = "EMA of the Laguerre line. The line must be on the correct side of it for the trend to flip.")
int   atrLen      = input.int(14, "ATR Length", minval = 2, group = g1)
float flipBuffer  = input.float(0.20, "Flip Buffer (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = g1, tooltip = "How far price must clear the Laguerre line before the trend can flip.")
int   slopeLook   = input.int(2, "Slope Lookback", minval = 1, maxval = 10, group = g1, tooltip = "The Laguerre line must be rising (or falling) versus this many bars ago.")
 
// Structure levels
int   swingLen    = input.int(5, "Swing Length", minval = 2, maxval = 30, group = g2, tooltip = "Bars on each side needed to confirm a swing high or low.")
int   maxLevels   = input.int(4, "Maximum Levels", minval = 1, maxval = 10, group = g2)
float pullbackATR = input.float(0.80, "Ribbon Proximity (ATR)", minval = 0.10, maxval = 3.0, step = 0.05, group = g2, tooltip = "A swing only becomes a level if it formed this close to the ribbon.")
float zoneATR     = input.float(0.12, "Zone Thickness (ATR)", minval = 0.02, maxval = 0.50, step = 0.01, group = g2)
float mergeATR    = input.float(0.30, "Level Merge (ATR)", minval = 0.05, maxval = 1.5, step = 0.05, group = g2, tooltip = "New levels closer than this to an existing same-side level are ignored.")
float breakATR    = input.float(0.08, "Break Buffer (ATR)", minval = 0.0, maxval = 1.0, step = 0.02, group = g2, tooltip = "A close this far beyond a zone removes it.")
int   originAge   = input.int(100, "Origin Swing Max Age", minval = 10, maxval = 500, group = g2, tooltip = "Max age in bars of the swing used as a trend-origin level.")
bool  showOrigin  = input.bool(true, "Trend Origin Levels", group = g2)
bool  showCont    = input.bool(true, "Continuation Levels", group = g2)
 
// Pressure filter
int   pressLen    = input.int(8, "Pressure Smoothing", minval = 2, maxval = 50, group = g3, tooltip = "EMA length used to smooth the buy/sell pressure.")
float wickW       = input.float(0.85, "Wick Rejection Weight", minval = 0.0, maxval = 2.5, step = 0.05, group = g3, tooltip = "How much long wicks count as rejection pressure.")
bool  useVolW     = input.bool(false, "Weight by Relative Volume", group = g3, tooltip = "Scales each candle by volume versus its 50-bar average. Needs reliable volume data.")
float pressMin    = input.float(0.10, "Min Pressure Bias", minval = 0.0, maxval = 0.9, step = 0.05, group = g3, tooltip = "Longs need pressure >= this value. Shorts need pressure <= minus this value. Range is -1 to +1.")
 
// MACD trigger
int   macdFast    = input.int(12, "MACD Fast", minval = 2, group = g4)
int   macdSlow    = input.int(26, "MACD Slow", minval = 3, group = g4)
int   macdSigLen  = input.int(9, "MACD Signal", minval = 2, group = g4)
string macdMode   = input.string("Any cross", "Cross Type", options = ["Any cross", "Outside band only"], group = g4, tooltip = "Outside band only: the cross must start with the signal line beyond the zero band below.")
float macdBand    = input.float(0.25, "Zero Band (ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = g4)
 
// Entries
string dirMode    = input.string("Both", "Direction", options = ["Both", "Long Only", "Short Only"], group = g5)
bool  useRetest   = input.bool(true, "Trigger: Structure Retest", group = g5)
bool  useMacd     = input.bool(true, "Trigger: MACD Cross in Trend", group = g5)
bool  useFlip     = input.bool(true, "Trigger: Trend Flip", group = g5)
bool  needSide    = input.bool(false, "Require Price Beyond Laguerre Line", group = g5, tooltip = "Longs: close above the Laguerre line. Shorts: close below it.")
int   cooldown    = input.int(3, "Bars Between Entries", minval = 0, maxval = 100, group = g5)
int   startTime   = input.time(timestamp("2018-01-01T00:00:00"), "Backtest Start", group = g5)
 
// Risk and exits
string sizeMode   = input.string("Risk %", "Position Sizing", options = ["Risk %", "Fixed % of equity"], group = g6)
float riskPct     = input.float(1.0, "Risk per Trade (%)", minval = 0.05, maxval = 20.0, step = 0.05, group = g6)
float fixedPct    = input.float(100.0, "Fixed Size (% of equity)", minval = 1.0, maxval = 1000.0, group = g6)
float maxLev      = input.float(1.0, "Max Leverage", minval = 0.1, maxval = 20.0, step = 0.1, group = g6, tooltip = "Caps position value at equity times this number, whatever the risk-based size says.")
float stopMult    = input.float(2.0, "Stop (ATR)", minval = 0.3, maxval = 10.0, step = 0.1, group = g6)
float stopMax     = input.float(3.0, "Max Structure Stop (ATR)", minval = 0.5, maxval = 10.0, step = 0.1, group = g6, tooltip = "Retest entries stop beyond the zone, clamped between 0.6 ATR and this value.")
bool  useTP       = input.bool(true, "Take Profit", group = g6)
float rr          = input.float(2.5, "Target (R multiple)", minval = 0.5, maxval = 10.0, step = 0.1, group = g6)
bool  useTrail    = input.bool(true, "ATR Trailing Stop", group = g6)
float trailStartR = input.float(1.0, "Trail Starts After (R)", minval = 0.0, maxval = 10.0, step = 0.1, group = g6)
float trailATR    = input.float(2.5, "Trail Distance (ATR)", minval = 0.5, maxval = 10.0, step = 0.1, group = g6)
bool  exitOnFlip  = input.bool(true, "Exit on Opposite Trend Flip", group = g6)
 
// Display
bool  showFill    = input.bool(true, "Price Gradient", group = g7)
bool  showRibbon  = input.bool(true, "Trend Ribbon", group = g7)
bool  showGlow    = input.bool(true, "Filter Glow", group = g7)
bool  showLevels  = input.bool(true, "Draw Structure Levels", group = g7)
bool  showLabels  = input.bool(true, "Entry Labels", group = g7)
bool  showStops   = input.bool(true, "Stop / Target Lines", group = g7)
bool  showTable   = input.bool(true, "Dashboard", group = g7)
string candleMode = input.string("Off", "Candle Colouring", options = ["Off", "Trend", "Pressure"], group = g7)
int   lineWidth   = input.int(3, "Trend Line Width", minval = 1, maxval = 6, group = g7)
color bullCol     = input.color(#00FF66, "Bullish", inline = "col", group = g7)
color bearCol     = input.color(#FF0066, "Bearish", inline = "col", group = g7)
 
// ───────────────────────────── Helpers ─────────────────────────────
f_clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
 
// ───────────────────────────── Trend: Laguerre filter ─────────────────────────────
// Four chained smoothing stages, averaged 1-2-2-1 into one line.
var float l0 = na
var float l1 = na
var float l2 = na
var float l3 = na
 
l0 := (1.0 - gamma) * src + gamma * nz(l0[1], src)
l1 := -gamma * l0 + nz(l0[1], src) + gamma * nz(l1[1], src)
l2 := -gamma * l1 + nz(l1[1], src) + gamma * nz(l2[1], src)
l3 := -gamma * l2 + nz(l2[1], src) + gamma * nz(l3[1], src)
 
float filt   = (l0 + 2.0 * l1 + 2.0 * l2 + l3) / 6.0
float ribbon = ta.ema(filt, ribbonLen)
float atr    = ta.atr(atrLen)
 
// A trend change needs price beyond the line (by a buffer), a sloping line, and the line beyond the ribbon.
bool bullReady = close > filt + atr * flipBuffer and filt > filt[slopeLook] and filt > ribbon
bool bearReady = close < filt - atr * flipBuffer and filt < filt[slopeLook] and filt < ribbon
 
var int trend = 0   // 1 = up, -1 = down
if bullReady
    trend := 1
else if bearReady
    trend := -1
else if trend == 0
    trend := filt >= ribbon ? 1 : -1
 
bool bullFlip = trend == 1 and trend[1] == -1
bool bearFlip = trend == -1 and trend[1] == 1
color col = trend == 1 ? bullCol : bearCol
 
// ───────────────────────────── Pressure score ─────────────────────────────
// Scores each candle from its movement, body, close position and wicks, then smooths it.
// Result runs from -1 (sellers in control) to +1 (buyers in control).
float rng         = math.max(high - low, syminfo.mintick)
float directional = f_clamp((close - open) / rng, -1.0, 1.0)
float travel      = f_clamp((close - nz(close[1], open)) / rng, -1.5, 1.5)
float closeLoc    = f_clamp((2.0 * close - high - low) / rng, -1.0, 1.0)
float resp        = f_clamp(0.55 * travel + 0.25 * directional + 0.20 * closeLoc, -1.5, 1.5)
float force       = math.abs(resp)
float contin      = resp * nz(resp[1]) > 0 ? 1.45 : resp * nz(resp[1]) < 0 ? 0.55 : 1.0   // follow-through bonus
float lowWick     = math.max(0.0, math.min(open, close) - low) / rng
float highWick    = math.max(0.0, high - math.max(open, close)) / rng
float volAvg      = ta.sma(volume, 50)
float volW        = useVolW and volAvg > 0 ? f_clamp(volume / volAvg, 0.25, 4.0) : 1.0
 
float buyP  = (math.max(resp, 0.0) * (1.0 + force * 1.25) * contin * 2.0 + wickW * lowWick * (0.35 + 1.20 * math.max(resp, 0.0))) * volW
float sellP = (math.max(-resp, 0.0) * (1.0 + force * 1.25) * contin * 2.0 + wickW * highWick * (0.35 + 1.20 * math.max(-resp, 0.0))) * volW
 
float buyE     = ta.ema(buyP, pressLen)
float sellE    = ta.ema(sellP, pressLen)
float pressure = (buyE - sellE) / math.max(buyE + sellE, 0.0000001)
 
// ───────────────────────────── MACD ─────────────────────────────
int   mFast    = math.min(macdFast, macdSlow)
int   mSlow    = macdFast == macdSlow ? macdSlow + 1 : math.max(macdFast, macdSlow)
float macdLine = ta.ema(close, mFast) - ta.ema(close, mSlow)
float sigLine  = ta.ema(macdLine, macdSigLen)
float macdHist = macdLine - sigLine
float bandV    = macdBand * ta.atr(mSlow)
 
bool xUp      = ta.crossover(macdLine, sigLine)
bool xDn      = ta.crossunder(macdLine, sigLine)
bool anyCross = macdMode == "Any cross"
bool macdBuy  = xUp and (anyCross or sigLine[1] < -nz(bandV[1], bandV))
bool macdSell = xDn and (anyCross or sigLine[1] > nz(bandV[1], bandV))
 
// ───────────────────────────── Swing points ─────────────────────────────
// A swing is only confirmed swingLen bars after it forms, so its real bar is bar_index - swingLen.
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
 
var float lastPH    = na
var float lastPL    = na
var int   lastPHBar = na
var int   lastPLBar = na
var float lastPHAtr = na
var float lastPLAtr = na
 
if not na(ph)
    lastPH    := ph
    lastPHBar := bar_index - swingLen
    lastPHAtr := nz(atr[swingLen], atr)
 
if not na(pl)
    lastPL    := pl
    lastPLBar := bar_index - swingLen
    lastPLAtr := nz(atr[swingLen], atr)
 
// ───────────────────────────── Structure levels ─────────────────────────────
type StructureLevel
    float price
    float top
    float bottom
    int   direction   // 1 = support, -1 = resistance
    bool  origin
    bool  armed       // true once price has moved away, so the next touch counts as a retest
    line  ln
    box   outer
    box   inner
 
var array<StructureLevel> levels = array.new<StructureLevel>()
 
f_delete_level(StructureLevel lv) =>
    line.delete(lv.ln)
    box.delete(lv.outer)
    box.delete(lv.inner)
 
f_clear_opposite(int direction) =>
    if levels.size() > 0
        for i = levels.size() - 1 to 0
            StructureLevel lv = levels.get(i)
            if lv.direction != direction
                f_delete_level(lv)
                levels.remove(i)
 
f_add_level(float price, int pivotBar, int direction, bool origin, float levelAtr) =>
    bool doAdd = true
    float mergeDist = levelAtr * mergeATR
 
    // skip if a same-side level already sits nearby
    if levels.size() > 0
        for i = 0 to levels.size() - 1
            StructureLevel existing = levels.get(i)
            if existing.direction == direction and math.abs(existing.price - price) <= mergeDist
                doAdd := false
                break
 
    if doAdd
        color css = direction == 1 ? bullCol : bearCol
        float height = levelAtr * zoneATR
        float zTop = price + height
        float zBot = price - height
        float innerH = height * 0.42
 
        int outerAlpha = origin ? 88 : 92
        int innerAlpha = origin ? 68 : 78
        int lineAlpha  = origin ? 5 : 22
 
        box   bxOuter = na
        box   bxInner = na
        line  lnLvl   = na
        if showLevels
            bxOuter := box.new(pivotBar, zTop, pivotBar + 1, zBot, xloc = xloc.bar_index, extend = extend.right,
                 border_color = color.new(css, 100), bgcolor = color.new(css, outerAlpha))
            bxInner := box.new(pivotBar, price + innerH, pivotBar + 1, price - innerH, xloc = xloc.bar_index, extend = extend.right,
                 border_color = color.new(css, 100), bgcolor = color.new(css, innerAlpha))
            lnLvl := line.new(pivotBar, price, pivotBar + 1, price, xloc = xloc.bar_index, extend = extend.right,
                 color = color.new(css, lineAlpha), width = origin ? 2 : 1, style = origin ? line.style_solid : line.style_dotted)
 
        levels.unshift(StructureLevel.new(price, zTop, zBot, direction, origin, false, lnLvl, bxOuter, bxInner))
 
        // keep only the newest levels
        while levels.size() > maxLevels
            StructureLevel oldest = levels.pop()
            f_delete_level(oldest)
 
    doAdd
 
// Origin levels: when a new trend starts, the last opposing swing becomes a level.
if bullFlip
    f_clear_opposite(1)
    if showOrigin and not na(lastPL) and not na(lastPLBar) and bar_index - lastPLBar <= originAge
        f_add_level(lastPL, lastPLBar, 1, true, nz(lastPLAtr, atr))
 
if bearFlip
    f_clear_opposite(-1)
    if showOrigin and not na(lastPH) and not na(lastPHBar) and bar_index - lastPHBar <= originAge
        f_add_level(lastPH, lastPHBar, -1, true, nz(lastPHAtr, atr))
 
// Continuation levels: swings that form close to the ribbon during a trend.
if showCont and not na(pl) and trend[swingLen] == 1
    float pAtrL  = nz(atr[swingLen], atr)
    float rbTopL = math.max(filt[swingLen], ribbon[swingLen])
    float rbBotL = math.min(filt[swingLen], ribbon[swingLen])
    float distL  = pl < rbBotL ? rbBotL - pl : pl > rbTopL ? pl - rbTopL : 0.0
    if distL <= pAtrL * pullbackATR
        f_add_level(pl, bar_index - swingLen, 1, false, pAtrL)
 
if showCont and not na(ph) and trend[swingLen] == -1
    float pAtrS  = nz(atr[swingLen], atr)
    float rbTopS = math.max(filt[swingLen], ribbon[swingLen])
    float rbBotS = math.min(filt[swingLen], ribbon[swingLen])
    float distS  = ph > rbTopS ? ph - rbTopS : ph < rbBotS ? rbBotS - ph : 0.0
    if distS <= pAtrS * pullbackATR
        f_add_level(ph, bar_index - swingLen, -1, false, pAtrS)
 
// Level upkeep, every bar:
//   - delete a level when price closes through it
//   - arm it when price trades fully away from it
//   - flag a retest when an armed level is touched and the close holds on the right side
bool  bullRetest    = false
bool  bearRetest    = false
float bullRetBottom = na
float bearRetTop    = na
 
if levels.size() > 0
    for i = levels.size() - 1 to 0
        StructureLevel lv = levels.get(i)
 
        bool invalid = lv.direction == 1 ? close < lv.bottom - atr * breakATR : close > lv.top + atr * breakATR
 
        if invalid
            f_delete_level(lv)
            levels.remove(i)
        else
            bool outside = lv.direction == 1 ? low > lv.top : high < lv.bottom
            bool touch   = high >= lv.bottom and low <= lv.top
            bool holds   = lv.direction == 1 ? close > lv.price : close < lv.price
 
            if outside
                lv.armed := true
            else if lv.armed and touch and holds and trend == lv.direction
                lv.armed := false
                if lv.direction == 1
                    bullRetest := true
                    bullRetBottom := na(bullRetBottom) ? lv.bottom : math.min(bullRetBottom, lv.bottom)
                else
                    bearRetest := true
                    bearRetTop := na(bearRetTop) ? lv.top : math.max(bearRetTop, lv.top)
 
// ───────────────────────────── Entry rules ─────────────────────────────
bool allowLong  = dirMode != "Short Only"
bool allowShort = dirMode != "Long Only"
bool inRange    = time >= startTime
 
var int   lastEntryBar = na
var float longRisk  = na   // risk distance of the current long, in price
var float shortRisk = na
var float runHigh   = na   // best price since a long entry (for the trail)
var float runLow    = na
 
bool cooled = na(lastEntryBar) or bar_index - lastEntryBar >= cooldown
 
bool longViaRetest  = useRetest and bullRetest
bool shortViaRetest = useRetest and bearRetest
bool longTrigger    = longViaRetest or (useMacd and macdBuy) or (useFlip and bullFlip)
bool shortTrigger   = shortViaRetest or (useMacd and macdSell) or (useFlip and bearFlip)
 
// Trend and pressure must agree with the trade.
bool longOk  = trend == 1 and pressure >= pressMin and (not needSide or close > filt)
bool shortOk = trend == -1 and pressure <= -pressMin and (not needSide or close < filt)
 
bool longSignal  = longTrigger and longOk and allowLong and inRange and cooled and strategy.position_size <= 0 and not na(atr)
bool shortSignal = shortTrigger and shortOk and allowShort and inRange and cooled and strategy.position_size >= 0 and not na(atr)
 
// Position size from the chosen mode, capped by max leverage.
f_qty(float riskDist) =>
    float eq     = math.max(strategy.equity, 0.0)
    float pv     = syminfo.pointvalue
    float qRisk  = eq * riskPct / 100.0 / (math.max(riskDist, syminfo.mintick) * pv)
    float qFixed = eq * fixedPct / 100.0 / (close * pv)
    float qCap   = eq * maxLev / (close * pv)
    math.min(sizeMode == "Risk %" ? qRisk : qFixed, qCap)
 
f_trig_name(bool viaRetest, bool viaMacd, bool viaFlip) =>
    viaRetest ? "Retest" : viaMacd ? "MACD" : viaFlip ? "Flip" : "Signal"
 
if longSignal
    // Retest trades stop just beyond the zone; others use a plain ATR stop.
    float structStop = longViaRetest and not na(bullRetBottom) ? bullRetBottom - 0.25 * atr : na
    float rawRisk    = not na(structStop) ? close - structStop : stopMult * atr
    float rL         = f_clamp(rawRisk, 0.6 * atr, stopMax * atr)
    float qL         = f_qty(rL)
    if qL > 0
        string nm = f_trig_name(longViaRetest, useMacd and macdBuy, useFlip and bullFlip)
        longRisk := rL
        strategy.entry("Long", strategy.long, qty = qL, comment = "L " + nm, alert_message = "Laguerre Pulse Long (" + nm + ") " + syminfo.ticker)
        strategy.exit("L Exit", "Long", stop = close - rL, limit = useTP ? close + rL * rr : na)
        lastEntryBar := bar_index
        if showLabels
            label.new(bar_index, na, "L " + nm, yloc = yloc.belowbar, style = label.style_label_up, color = bullCol, textcolor = color.black, size = size.tiny)
 
if shortSignal
    float structStopS = shortViaRetest and not na(bearRetTop) ? bearRetTop + 0.25 * atr : na
    float rawRiskS    = not na(structStopS) ? structStopS - close : stopMult * atr
    float rS          = f_clamp(rawRiskS, 0.6 * atr, stopMax * atr)
    float qS          = f_qty(rS)
    if qS > 0
        string nmS = f_trig_name(shortViaRetest, useMacd and macdSell, useFlip and bearFlip)
        shortRisk := rS
        strategy.entry("Short", strategy.short, qty = qS, comment = "S " + nmS, alert_message = "Laguerre Pulse Short (" + nmS + ") " + syminfo.ticker)
        strategy.exit("S Exit", "Short", stop = close + rS, limit = useTP ? close - rS * rr : na)
        lastEntryBar := bar_index
        if showLabels
            label.new(bar_index, na, "S " + nmS, yloc = yloc.abovebar, style = label.style_label_down, color = bearCol, textcolor = color.white, size = size.tiny)
 
// ───────────────────────────── Managing open trades ─────────────────────────────
// Once filled, stop and target are rebuilt from the real fill price, and the trail is updated.
float curSL = na
float curTP = na
 
if strategy.position_size > 0
    float avgL   = strategy.position_avg_price
    runHigh := strategy.position_size[1] <= 0 ? high : math.max(nz(runHigh, high), high)
    float rk     = nz(longRisk, stopMult * atr)
    float baseSL = avgL - rk
    float trailSL = useTrail and (runHigh - avgL) >= trailStartR * rk ? runHigh - trailATR * atr : na
    curSL := na(trailSL) ? baseSL : math.max(baseSL, trailSL)   // the stop only moves up
    curTP := useTP ? avgL + rk * rr : na
    strategy.exit("L Exit", "Long", stop = curSL, limit = curTP)
    if exitOnFlip and bearFlip
        strategy.close("Long", comment = "Trend flip")
 
if strategy.position_size < 0
    float avgS    = strategy.position_avg_price
    runLow := strategy.position_size[1] >= 0 ? low : math.min(nz(runLow, low), low)
    float rkS     = nz(shortRisk, stopMult * atr)
    float baseSLs = avgS + rkS
    float trailSLs = useTrail and (avgS - runLow) >= trailStartR * rkS ? runLow + trailATR * atr : na
    curSL := na(trailSLs) ? baseSLs : math.min(baseSLs, trailSLs)   // the stop only moves down
    curTP := useTP ? avgS - rkS * rr : na
    strategy.exit("S Exit", "Short", stop = curSL, limit = curTP)
    if exitOnFlip and bullFlip
        strategy.close("Short", comment = "Trend flip")
 
// ───────────────────────────── Chart drawing ─────────────────────────────
pFilter = plot(filt, "Laguerre Trend", col, lineWidth)
pPrice  = plot(close, "Price Reference", display = display.none, editable = false)
pRibbon = plot(showRibbon ? ribbon : na, "Ribbon", color.new(col, 58), 2)
 
// Gradient between price and the trend line. It gets stronger when pressure is stronger.
int strongA = int(math.round(f_clamp(70.0 - 50.0 * math.min(math.abs(pressure), 1.0), 15.0, 70.0)))
float priceTop = math.max(close, filt)
float priceBot = math.min(close, filt)
color priceTopCol = close > filt ? color.new(col, 92) : color.new(col, strongA)
color priceBotCol = close > filt ? color.new(col, strongA) : color.new(col, 92)
fill(pPrice, pFilter, priceTop, priceBot, showFill ? priceTopCol : na, showFill ? priceBotCol : na, title = "Price Gradient")
 
// Gradient between the trend line and the ribbon.
float rbTop = math.max(filt, ribbon)
float rbBot = math.min(filt, ribbon)
color rbTopCol = filt > ribbon ? color.new(col, 18) : color.new(col, 88)
color rbBotCol = filt > ribbon ? color.new(col, 88) : color.new(col, 18)
fill(pFilter, pRibbon, rbTop, rbBot, showRibbon ? rbTopCol : na, showRibbon ? rbBotCol : na, title = "Trend Ribbon")
 
// Glow around the trend line.
float glow      = atr * 0.045
float outerGlow = glow * 2.2
pGlowU  = plot(showGlow ? filt + glow : na, display = display.none, editable = false)
pGlowL  = plot(showGlow ? filt - glow : na, display = display.none, editable = false)
pOuterU = plot(showGlow ? filt + outerGlow : na, display = display.none, editable = false)
pOuterL = plot(showGlow ? filt - outerGlow : na, display = display.none, editable = false)
fill(pOuterU, pOuterL, showGlow ? color.new(col, 93) : na, title = "Outer Glow")
fill(pGlowU, pGlowL, showGlow ? color.new(col, 72) : na, title = "Inner Glow")
 
color barCol = candleMode == "Trend" ? col : candleMode == "Pressure" ? (pressure >= pressMin ? bullCol : pressure <= -pressMin ? bearCol : color.gray) : na
barcolor(barCol)
 
plot(showStops ? curSL : na, "Active Stop", color = color.new(bearCol, 20), style = plot.style_linebr, linewidth = 1)
plot(showStops ? curTP : na, "Active Target", color = color.new(bullCol, 20), style = plot.style_linebr, linewidth = 1)
 
plotshape(bullFlip, "Bull Flip", shape.triangleup, location.belowbar, bullCol, size = size.tiny)
plotshape(bearFlip, "Bear Flip", shape.triangledown, location.abovebar, bearCol, size = size.tiny)
 
// Values visible in the Data Window.
plot(pressure, "Pressure Bias", display = display.data_window)
plot(macdHist, "MACD Histogram", display = display.data_window)
plot(trend, "Trend State", display = display.data_window)
 
// ───────────────────────────── Dashboard ─────────────────────────────
var table tbl = table.new(position.top_right, 2, 9, bgcolor = color.new(#10131A, 12), frame_width = 0, border_width = 0)
 
f_row(int r, string k, string v, color vc) =>
    table.cell(tbl, 0, r, k, text_color = color.new(#D1D4DC, 35), text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
if barstate.islast and showTable
    int   nTr = strategy.closedtrades
    float wr  = nTr > 0 ? 100.0 * strategy.wintrades / nTr : na
    float pf  = strategy.grossloss > 0 ? strategy.grossprofit / strategy.grossloss : na
    color neutral = #D1D4DC
    f_row(0, "LAGUERRE PULSE", syminfo.ticker, neutral)
    f_row(1, "Trend", trend == 1 ? "Bullish" : "Bearish", col)
    f_row(2, "Pressure", str.tostring(pressure * 100, "+0;-0") + "%", pressure >= pressMin ? bullCol : pressure <= -pressMin ? bearCol : neutral)
    f_row(3, "MACD", macdHist > 0 ? "Above signal" : "Below signal", macdHist > 0 ? bullCol : bearCol)
    f_row(4, "Position", strategy.position_size > 0 ? "Long" : strategy.position_size < 0 ? "Short" : "Flat", strategy.position_size > 0 ? bullCol : strategy.position_size < 0 ? bearCol : neutral)
    f_row(5, "Net P/L", str.tostring(strategy.netprofit, "#,##0.00"), strategy.netprofit >= 0 ? bullCol : bearCol)
    f_row(6, "Trades / Win %", str.tostring(nTr) + " / " + (na(wr) ? "-" : str.tostring(wr, "0") + "%"), neutral)
    f_row(7, "Profit factor", na(pf) ? "-" : str.tostring(pf, "0.00"), neutral)
    f_row(8, "Max drawdown", str.tostring(strategy.max_drawdown, "#,##0.00"), neutral)

← 返回列表