Market Memory AI [TradeIQ]

Tradeiqofficial · study · 457 行 · 点赞 293 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Market Memory AI: a k-nearest-neighbours model that finds the past bars on this chart that looked most like the current
// one (RSI, momentum, stretch from the EMA 50, volume, volatility, trend strength) and shows what price did after them:
// a projection line with a range cone, candles coloured by how many of those analogs went up, and the analogs' own paths.
// Signals are breakouts on heavy volume in an active market, with a 2 ATR stop and a 3 ATR trailing stop: profit factor 1.50
// (2021–24) and 1.27 (2025–26) on BTC / ETH / SOL 1h after costs. Most trades lose; the edge comes from the trends it catches. © TradeIQ
// The model learns only from bars whose outcome is already known, and signals confirm on the candle close.
// Education only, not financial advice.
//@version=6
indicator("Market Memory AI [TradeIQ]", shorttitle = "Market Memory AI", overlay = true, max_labels_count = 500, max_lines_count = 500, max_polylines_count = 100)
 
// ═════════════════════════════════════════ INPUTS ═════════════════════════════════════════
G_AI = "1 · AI Model"
kNb      = input.int(16, "Analogs (k)", minval = 4, maxval = 40, group = G_AI,
     tooltip = "How many of the most similar past bars the model looks at. Similarity is a Lorentzian distance over 7 features: RSI 14, 6-bar and 24-bar momentum (ATR-scaled), distance from the EMA 50, relative volume, ATR against its 100-bar average, and ADX.")
horizon  = input.int(12, "Look-ahead (bars)", minval = 2, maxval = 50, group = G_AI,
     tooltip = "How far ahead the model looks. Each analog's outcome is what price did over this many bars after it. A past bar only becomes an analog once that outcome is known, so the model never sees the future.")
memBars  = input.int(2000, "Memory (bars searched)", minval = 200, maxval = 4000, step = 100, group = G_AI,
     tooltip = "How far back the model searches for analogs.")
stride   = input.int(4, "Check every Nth bar", minval = 2, maxval = 10, group = G_AI,
     tooltip = "Checking every 4th bar keeps the script fast. 2 is the most thorough setting allowed; lower values are slower, and TradingView stops scripts that take too long.")
calcBars = input.int(2000, "Run the model on the last (bars)", minval = 100, maxval = 5000, step = 100, group = G_AI,
     tooltip = "The model runs on the most recent bars only, for speed. Older bars keep the chart's own candles. Signals and the signal record use the whole chart.")
 
G_PJ = "2 · Projection"
projOn   = input.bool(true, "Projection line", group = G_PJ,
     tooltip = "The analogs' average path over the look-ahead, scaled to today's ATR and started from the last close. On BTC, ETH and SOL 1h (2021–2026) its direction was right about half the time, so read it as a likely range rather than a call.")
coneOn   = input.bool(true, "Range cone (±1 and ±½ spread)", group = G_PJ,
     tooltip = "The spread of the analogs' outcomes around the line. On BTC, ETH and SOL 1h, 69 % of 12-bar outcomes ended inside the ±1 cone. The panel shows the same check on your chart.")
ghostN   = input.int(3, "Analog paths shown", minval = 0, maxval = 8, group = G_PJ,
     tooltip = "Faint dotted lines: what price actually did after the nearest analogs, scaled to today. 0 hides them.")
markOn   = input.bool(false, "Mark the analog bars in history", group = G_PJ,
     tooltip = "A small dot on each past bar the model matched, so you can see where the memories come from.")
cUp      = input.color(#00E5A0, "Up", inline = "pj", group = G_PJ)
cDn      = input.color(#FF3D71, "Down", inline = "pj", group = G_PJ)
cCone    = input.color(#8B5CF6, "Cone", inline = "pj", group = G_PJ)
cGhost   = input.color(#2F80FF, "Paths", inline = "pj", group = G_PJ)
 
G_SG = "3 · Breakout Signals"
sigOn    = input.bool(true, "Show signals", group = G_SG,
     tooltip = "Long: the close breaks above the highest high of the last 34 bars, on volume at least 2.5× its 20-bar average, while ATR is above its 200-bar average. Short: the mirror below the lowest low. Entry is the next bar's open, the stop starts 2 ATR away and then trails 3 ATR behind the close. One trade at a time.")
brkLen   = input.int(34, "Breakout length (bars)", minval = 5, maxval = 200, group = G_SG)
volX     = input.float(2.5, "Volume at least average ×", minval = 0, maxval = 10, step = 0.1, group = G_SG,
     tooltip = "Weak-volume breakouts were the worst ones in our test. 1.5 = the first, unfiltered version. 0 turns the check off; symbols without volume skip it.")
volaOn   = input.bool(true, "Only when the market is active (ATR above its average)", group = G_SG,
     tooltip = "Skips breakouts while ATR(14) is below its average over the length below. On BTC, ETH and SOL 1h this filter plus volume ≥ 2.5× raised the profit factor from 1.10 to 1.50 (2021–2024) and from 1.12 to 1.27 (2025–2026), with 60 % fewer trades.")
volaLen  = input.int(200, "Volatility average (bars)", minval = 20, maxval = 1000, group = G_SG)
stopX    = input.float(2.0, "Initial stop (ATR ×)", minval = 0.5, maxval = 10, step = 0.1, group = G_SG)
trailX   = input.float(3.0, "Trailing stop (ATR ×)", minval = 0.5, maxval = 10, step = 0.1, group = G_SG)
maxBars  = input.int(120, "Time stop (bars)", minval = 5, maxval = 1000, group = G_SG)
aiFilt   = input.bool(false, "Only take signals the AI agrees with", group = G_SG,
     tooltip = "Off by default. In our test it raised the profit factor in 2021–2024 but cut it to 0.78 in 2025–2026 when it was tested on the unfiltered signals, so it is not a reliable improvement. It only works where the model runs (the setting 'Run the model on the last').")
aiMin    = input.int(10, "AI filter: analogs agreeing at least", minval = 1, maxval = 40, group = G_SG)
emaFilt  = input.bool(false, "Only longs above / shorts below the EMA 200", group = G_SG)
costPct  = input.float(0.07, "Cost per side % (fee + slippage)", minval = 0, maxval = 1, step = 0.01, group = G_SG,
     tooltip = "Used for the R results on the chart and in the panel. 0.07 = 0.05 % fee + 0.02 % slippage, the same as our backtest.")
sigSize  = input.string("Large", "Triangle size", ["Normal", "Large", "Huge"], group = G_SG)
trailOn  = input.bool(true, "Trailing stop line and trade zone", group = G_SG)
exitOn   = input.bool(true, "Exit marks with the result in R", group = G_SG)
 
G_VS = "4 · Visuals"
candleOn = input.bool(true, "Colour candles by the AI read", group = G_VS,
     tooltip = "Green when most analogs went up over the look-ahead, pink when most went down, grey when they are split.")
chanOn   = input.bool(true, "Breakout channel", group = G_VS,
     tooltip = "The highest high and lowest low of the breakout length: the levels a close has to break for a signal.")
cChanU   = input.color(#8B5CF6, "Channel top", inline = "ch", group = G_VS)
cChanD   = input.color(#2F80FF, "Channel bottom", inline = "ch", group = G_VS)
cMid     = input.color(#7C8096, "Neutral", inline = "ch", group = G_VS)
cGold    = input.color(#FFD60A, "Highlights", inline = "ch", group = G_VS)
 
G_UI = "5 · Panel"
showDash = input.bool(true, "Show panel", group = G_UI)
dashPos  = input.string("Top Right", "Position", ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_UI)
dashSz   = input.string("Small", "Size", ["Tiny", "Small", "Normal"], group = G_UI)
 
// ═════════════════════════════════════════ FEATURES ═════════════════════════════════════════
color TXT  = #D1D4DC
color MUTE = #8A8FA3
color BG   = #0E111A
color EDGE = #262B3A
 
f_tanh(float x) =>
    float y = math.max(-20.0, math.min(20.0, x))
    float e = math.exp(2 * y)
    (e - 1) / (e + 1)
 
atr   = ta.atr(14)
ema50 = ta.ema(close, 50)
[diP, diM, adx] = ta.dmi(14, 14)
float lv   = math.log(1 + nz(volume))
float lvM  = ta.sma(lv, 50)
float lvS  = ta.stdev(lv, 50)
float atrL = ta.sma(atr, 100)
 
// every feature is squeezed into about −1 … +1 so none of them dominates the distance
float f1 = (ta.rsi(close, 14) - 50) / 50
float f2 = f_tanh((close - close[6]) / (atr * math.sqrt(6)))
float f3 = f_tanh((close - close[24]) / (atr * math.sqrt(24)))
float f4 = f_tanh((close - ema50) / (atr * 3))
float f5 = not na(lvS) and lvS > 0 ? f_tanh((lv - lvM) / (2 * lvS)) : 0.0
float f6 = not na(atrL) and atrL > 0 ? f_tanh(math.log(atr / atrL) * 2) : na
float f7 = (adx - 25) / 25
bool okNow = not na(atr) and atr > 0 and not na(f1) and not na(f2) and not na(f3) and not na(f4) and not na(f6) and not na(f7)
 
// ═════════════════════════════════════════ MEMORY (ring buffer) ═════════════════════════════════════════
int S = memBars + horizon + 1
var array<float> b1 = array.new_float(S, na)
var array<float> b2 = array.new_float(S, na)
var array<float> b3 = array.new_float(S, na)
var array<float> b4 = array.new_float(S, na)
var array<float> b5 = array.new_float(S, na)
var array<float> b6 = array.new_float(S, na)
var array<float> b7 = array.new_float(S, na)
var array<float> bC = array.new_float(S, na)
var array<float> bA = array.new_float(S, na)
var array<bool>  bOk = array.new_bool(S, false)
 
int slotNow = bar_index % S
b1.set(slotNow, f1)
b2.set(slotNow, f2)
b3.set(slotNow, f3)
b4.set(slotNow, f4)
b5.set(slotNow, f5)
b6.set(slotNow, f6)
b7.set(slotNow, f7)
bC.set(slotNow, close)
bA.set(slotNow, atr)
bOk.set(slotNow, okNow)
 
// ═════════════════════════════════════════ k-NEAREST NEIGHBOURS ═════════════════════════════════════════
var array<float> nbD = array.new_float(0)
var array<int>   nbJ = array.new_int(0)
bool  doCalc = okNow and bar_index >= last_bar_index - calcBars and bar_index > horizon + kNb * stride
float prob = na      // share of analogs that closed higher after the look-ahead
float projE = na     // their average move, in ATR
float projS = na     // spread of their moves, in ATR
float avgD = na      // average distance to them (lower = closer match)
 
if doCalc
    nbD.clear()
    nbJ.clear()
    for m = horizon to horizon + memBars by stride
        int j = bar_index - m
        if j < 0
            break
        int sl = j % S
        if bOk.get(sl)
            float d = math.log(1 + math.abs(f1 - b1.get(sl))) + math.log(1 + math.abs(f2 - b2.get(sl))) + math.log(1 + math.abs(f3 - b3.get(sl))) + math.log(1 + math.abs(f4 - b4.get(sl))) + math.log(1 + math.abs(f5 - b5.get(sl))) + math.log(1 + math.abs(f6 - b6.get(sl))) + math.log(1 + math.abs(f7 - b7.get(sl)))
            int n = nbD.size()
            if n < kNb
                nbD.push(d)
                nbJ.push(j)
                int q = n
                while q > 0 and nbD.get(q - 1) > d
                    nbD.set(q, nbD.get(q - 1))
                    nbJ.set(q, nbJ.get(q - 1))
                    q -= 1
                nbD.set(q, d)
                nbJ.set(q, j)
            else if d < nbD.get(kNb - 1)
                int q = kNb - 1
                while q > 0 and nbD.get(q - 1) > d
                    nbD.set(q, nbD.get(q - 1))
                    nbJ.set(q, nbJ.get(q - 1))
                    q -= 1
                nbD.set(q, d)
                nbJ.set(q, j)
    if nbD.size() == kNb
        int up = 0
        float s1 = 0.0
        float s2 = 0.0
        float sd = 0.0
        for q = 0 to kNb - 1
            int j = nbJ.get(q)
            float r = (bC.get((j + horizon) % S) - bC.get(j % S)) / bA.get(j % S)
            up += r > 0 ? 1 : 0
            s1 += r
            s2 += r * r
            sd += nbD.get(q)
        prob  := float(up) / kNb
        projE := s1 / kNb
        projS := math.sqrt(math.max(0.0, s2 / kNb - projE * projE))
        avgD  := sd / kNb / 7
 
int upCount = na(prob) ? na : int(math.round(prob * kNb))
int aiDir   = na(prob) ? 0 : prob > 0.5 ? 1 : prob < 0.5 ? -1 : 0
 
// live scorecard on this chart: was the AI's direction right, and did price end inside the ±1 cone?
var int hitN = 0
var int hitOk = 0
var int coneOk = 0
if not na(prob[horizon]) and aiDir[horizon] != 0 and not na(atr[horizon])
    float realR = (close - close[horizon]) / atr[horizon]
    hitN += 1
    hitOk += math.sign(realR) == aiDir[horizon] ? 1 : 0
    coneOk += math.abs(realR - projE[horizon]) <= projS[horizon] ? 1 : 0
 
// match quality: today's distance against the average distance seen so far
var float dSum = 0.0
var int   dCnt = 0
if not na(avgD)
    dSum += avgD
    dCnt += 1
float dRel = not na(avgD) and dCnt > 20 and dSum > 0 ? avgD / (dSum / dCnt) : na
string matchQ = na(dRel) ? "—" : dRel < 0.9 ? "High" : dRel > 1.1 ? "Low" : "Medium"
 
// ═════════════════════════════════════════ BREAKOUT SIGNALS ═════════════════════════════════════════
float hh   = ta.highest(high, brkLen)[1]
float ll   = ta.lowest(low, brkLen)[1]
float vAvg = ta.sma(volume, 20)
float vRel = not na(volume) and not na(vAvg) and vAvg > 0 ? volume / vAvg : na
bool  volOk = volX <= 0 or na(vRel) or vRel >= volX
float atrAvg = ta.sma(atr, volaLen)
float atrRel = not na(atrAvg) and atrAvg > 0 ? atr / atrAvg : na
bool  volaOk = not volaOn or (not na(atrRel) and atrRel > 1)
float ema200 = ta.ema(close, 200)
bool  upBrk = not na(hh) and not na(hh[1]) and close > hh and close[1] <= hh[1]
bool  dnBrk = not na(ll) and not na(ll[1]) and close < ll and close[1] >= ll[1]
bool  aiLongOk  = not aiFilt or (not na(upCount) and upCount >= aiMin)
bool  aiShortOk = not aiFilt or (not na(upCount) and kNb - upCount >= aiMin)
bool  emaLongOk  = not emaFilt or (not na(ema200) and close > ema200)
bool  emaShortOk = not emaFilt or (not na(ema200) and close < ema200)
 
var int   pos = 0          // +1 long, −1 short, 0 flat
var bool  pend = false     // a signal fired, entry on this bar's open
var int   pendDir = 0
var float ent = na
var float trl = na
var float riskU = na
var int   sigBar = na
var float sigAtr = na
var int   tN = 0
var int   tWin = 0
var float gW = 0.0
var float gL = 0.0
var float sumR = 0.0
var string lastSig = "—"
var int   lastSigBar = na
bool  exitNow = false
float exitPx = na
float exitR = na
int   exitDir = 0
 
if pend
    pos   := pendDir
    ent   := open
    riskU := stopX * sigAtr
    trl   := open - pos * riskU
    pend  := false
if pos != 0
    if (pos == 1 and low <= trl) or (pos == -1 and high >= trl)
        exitNow := true
        exitPx  := pos == 1 ? math.min(trl, open) : math.max(trl, open)
    else
        float nt = close - pos * trailX * atr
        trl := pos == 1 ? math.max(trl, nt) : math.min(trl, nt)
        if bar_index - sigBar >= maxBars
            exitNow := true
            exitPx  := close
    if exitNow
        exitR   := ((exitPx - ent) * pos - (ent + exitPx) * costPct / 100) / riskU
        exitDir := pos
        tN   += 1
        tWin += exitR > 0 ? 1 : 0
        gW   += exitR > 0 ? exitR : 0
        gL   += exitR > 0 ? 0 : -exitR
        sumR += exitR
        pos  := 0
 
bool canSig  = sigOn and pos == 0 and not pend and not exitNow and not na(atr)
bool longSig  = canSig and upBrk and volOk and volaOk and aiLongOk and emaLongOk
bool shortSig = canSig and dnBrk and volOk and volaOk and aiShortOk and emaShortOk and not longSig
if longSig or shortSig
    pend    := true
    pendDir := longSig ? 1 : -1
    sigBar  := bar_index
    sigAtr  := atr
    lastSig := longSig ? "Long ▲" : "Short ▼"
    lastSigBar := bar_index
 
// ═════════════════════════════════════════ CHANNEL & TRADE ZONE ═════════════════════════════════════════
float chMid = (hh + ll) / 2
pChU = plot(chanOn ? hh : na, "Channel top", color = color.new(cChanU, 35), linewidth = 1, style = plot.style_stepline)
pChM = plot(chanOn ? chMid : na, "Channel middle", display = display.none, editable = false)
pChD = plot(chanOn ? ll : na, "Channel bottom", color = color.new(cChanD, 35), linewidth = 1, style = plot.style_stepline)
fill(pChU, pChM, hh, chMid, color.new(cChanU, 86), color.new(cChanU, 100), "Channel top glow")
fill(pChM, pChD, chMid, ll, color.new(cChanD, 100), color.new(cChanD, 86), "Channel bottom glow")
 
// the trailing stop shows while a trade is open, including the bar it is hit
float trlPlot = trailOn and (pos != 0 or exitNow) ? trl : na
int   tDir    = pos != 0 ? pos : exitDir
color tCol    = tDir == 1 ? cUp : cDn
pTr = plot(trlPlot, "Trailing stop", color = color.new(tCol, 10), linewidth = 2, style = plot.style_linebr)
plot(trlPlot, "Trailing stop glow", color = color.new(tCol, 82), linewidth = 7, style = plot.style_linebr, editable = false, display = display.pane)
pCl = plot(trailOn and not na(trlPlot) ? close : na, "Close (zone)", display = display.none, editable = false)
float zTop = tDir == 1 ? close : trlPlot
float zBot = tDir == 1 ? trlPlot : close
fill(pCl, pTr, zTop, zBot, color.new(tCol, tDir == 1 ? 80 : 97), color.new(tCol, tDir == 1 ? 97 : 80), "Trade zone")
 
// ═════════════════════════════════════════ CANDLES ═════════════════════════════════════════
color aiCol = na(prob) ? na : prob >= 0.5 ? color.from_gradient(prob, 0.5, 0.85, cMid, cUp) : color.from_gradient(prob, 0.15, 0.5, cDn, cMid)
color candC = candleOn ? aiCol : na
plotcandle(open, high, low, close, "AI candles", color = candC, wickcolor = candC, bordercolor = candC, editable = true)
 
// signal triangles (below for longs, above for shorts) and exit marks
plotshape(longSig and sigSize == "Normal", "Long", shape.triangleup, location.belowbar, cUp, size = size.normal, text = "LONG", textcolor = cUp, editable = false)
plotshape(longSig and sigSize == "Large",  "Long", shape.triangleup, location.belowbar, cUp, size = size.large,  text = "LONG", textcolor = cUp, editable = false)
plotshape(longSig and sigSize == "Huge",   "Long", shape.triangleup, location.belowbar, cUp, size = size.huge,   text = "LONG", textcolor = cUp, editable = false)
plotshape(shortSig and sigSize == "Normal", "Short", shape.triangledown, location.abovebar, cDn, size = size.normal, text = "SHORT", textcolor = cDn, editable = false)
plotshape(shortSig and sigSize == "Large",  "Short", shape.triangledown, location.abovebar, cDn, size = size.large,  text = "SHORT", textcolor = cDn, editable = false)
plotshape(shortSig and sigSize == "Huge",   "Short", shape.triangledown, location.abovebar, cDn, size = size.huge,   text = "SHORT", textcolor = cDn, editable = false)
plot(exitOn and exitNow ? exitPx : na, "Exit", cGold, 4, plot.style_cross, editable = false)
if exitOn and exitNow
    label.new(bar_index, exitPx, (exitR >= 0 ? "+" : "") + str.tostring(exitR, "#.#") + "R", style = exitDir == 1 ? label.style_label_upper_left : label.style_label_lower_left, color = #00000000, textcolor = exitR >= 0 ? cUp : cDn, size = size.small)
 
// ═════════════════════════════════════════ PROJECTION ═════════════════════════════════════════
var polyline pjLine = na
var polyline pjGlow = na
var polyline pjCone1 = na
var polyline pjCone2 = na
var label    pjLab = na
var array<polyline> ghosts = array.new<polyline>()
var array<label>    marks  = array.new<label>()
float projEnd = na
float rngLo = na
float rngHi = na
 
if barstate.islast and doCalc and nbJ.size() == kNb
    // the path: for each step h, the analogs' average move after h bars (and its spread), scaled to today's ATR
    array<chart.point> pMid = array.new<chart.point>()
    array<chart.point> pHi1 = array.new<chart.point>()
    array<chart.point> pLo1 = array.new<chart.point>()
    array<chart.point> pHi2 = array.new<chart.point>()
    array<chart.point> pLo2 = array.new<chart.point>()
    pMid.push(chart.point.from_index(bar_index, close))
    pHi1.push(chart.point.from_index(bar_index, close))
    pLo1.push(chart.point.from_index(bar_index, close))
    pHi2.push(chart.point.from_index(bar_index, close))
    pLo2.push(chart.point.from_index(bar_index, close))
    for h = 1 to horizon
        float a1 = 0.0
        float a2 = 0.0
        for q = 0 to kNb - 1
            int j = nbJ.get(q)
            float r = (bC.get((j + h) % S) - bC.get(j % S)) / bA.get(j % S)
            a1 += r
            a2 += r * r
        float mu = a1 / kNb
        float sg = math.sqrt(math.max(0.0, a2 / kNb - mu * mu))
        float pm = close + atr * mu
        pMid.push(chart.point.from_index(bar_index + h, pm))
        pHi1.push(chart.point.from_index(bar_index + h, pm + atr * sg))
        pLo1.push(chart.point.from_index(bar_index + h, pm - atr * sg))
        pHi2.push(chart.point.from_index(bar_index + h, pm + atr * sg * 0.5))
        pLo2.push(chart.point.from_index(bar_index + h, pm - atr * sg * 0.5))
        if h == horizon
            projEnd := pm
            rngLo := pm - atr * sg
            rngHi := pm + atr * sg
    // closed cone shapes: upper edge out, lower edge back
    array<chart.point> cone1 = pHi1.copy()
    array<chart.point> cone2 = pHi2.copy()
    for i = pLo1.size() - 1 to 0
        cone1.push(pLo1.get(i))
        cone2.push(pLo2.get(i))
    color pc = projEnd >= close ? cUp : cDn
    if not na(pjLine)
        pjLine.delete()
    if not na(pjGlow)
        pjGlow.delete()
    if not na(pjCone1)
        pjCone1.delete()
    if not na(pjCone2)
        pjCone2.delete()
    if not na(pjLab)
        pjLab.delete()
    while ghosts.size() > 0
        ghosts.pop().delete()
    while marks.size() > 0
        marks.pop().delete()
    if coneOn
        pjCone1 := polyline.new(cone1, curved = true, closed = true, line_color = color.new(cCone, 70), fill_color = color.new(cCone, 88), line_width = 1)
        pjCone2 := polyline.new(cone2, curved = true, closed = true, line_color = color.new(cCone, 100), fill_color = color.new(cCone, 80), line_width = 1)
    if ghostN > 0
        for q = 0 to math.min(ghostN, kNb) - 1
            int j = nbJ.get(q)
            array<chart.point> gp = array.new<chart.point>()
            gp.push(chart.point.from_index(bar_index, close))
            for h = 1 to horizon
                gp.push(chart.point.from_index(bar_index + h, close + atr * (bC.get((j + h) % S) - bC.get(j % S)) / bA.get(j % S)))
            ghosts.push(polyline.new(gp, curved = true, line_color = color.new(cGhost, 45), line_style = line.style_dotted, line_width = 1))
    if projOn
        pjGlow := polyline.new(pMid, curved = true, line_color = color.new(pc, 80), line_width = 8)
        pjLine := polyline.new(pMid, curved = true, line_color = pc, line_width = 3)
        float pct = (projEnd / close - 1) * 100
        pjLab := label.new(bar_index + horizon, projEnd, (pct >= 0 ? "+" : "") + str.tostring(pct, "#.##") + "%  " + str.tostring(projEnd, format.mintick), style = label.style_label_left, color = #00000000, textcolor = pc, size = size.normal)
    if markOn
        for q = 0 to kNb - 1
            int j = nbJ.get(q)
            float r = bC.get((j + horizon) % S) - bC.get(j % S)
            marks.push(label.new(j, bC.get(j % S), "", style = label.style_circle, color = color.new(r > 0 ? cUp : cDn, 20), size = size.tiny))
 
// ═════════════════════════════════════════ PANEL ═════════════════════════════════════════
pos_ = dashPos == "Top Right" ? position.top_right : dashPos == "Top Left" ? position.top_left : dashPos == "Bottom Right" ? position.bottom_right : position.bottom_left
tsz  = dashSz == "Tiny" ? size.tiny : dashSz == "Normal" ? size.normal : size.small
var table tb = table.new(pos_, 2, 12, bgcolor = color.new(BG, 8), border_color = EDGE, border_width = 1, frame_color = EDGE, frame_width = 1)
 
f_row(int r, string k, string v, color c, string tip) =>
    table.cell(tb, 0, r, k, text_color = MUTE, text_size = tsz, text_halign = text.align_left, tooltip = tip)
    table.cell(tb, 1, r, v, text_color = c, text_size = tsz, text_halign = text.align_right, tooltip = tip)
 
f_bar(float p) =>
    int n = int(math.round(p * 10))
    string s = ""
    for i = 1 to 10
        s += i <= n ? "█" : "░"
    s
 
f_pct(float x) =>
    (x >= 0 ? "+" : "") + str.tostring(x, "#.##") + "%"
 
if showDash and barstate.islast
    bool  live  = not na(prob)
    color readC = not live ? MUTE : prob >= 0.625 ? cUp : prob <= 0.375 ? cDn : TXT
    string read = not live ? "Waiting" : prob >= 0.625 ? "Bullish ▲" : prob <= 0.375 ? "Bearish ▼" : "Mixed"
    float pct   = na(projEnd) ? na : (projEnd / close - 1) * 100
    float liveR = pos != 0 ? ((close - ent) * pos) / riskU : na
    float pf    = gL > 0 ? gW / gL : na
    table.cell(tb, 0, 0, "MARKET MEMORY AI", text_color = TXT, text_size = tsz, text_halign = text.align_left)
    table.cell(tb, 1, 0, "TradeIQ", text_color = cGold, text_size = tsz, text_halign = text.align_right)
    f_row(1, "AI read", live ? read + " · " + str.tostring(upCount) + "/" + str.tostring(kNb) + " up" : read, readC,
         "How many of the " + str.tostring(kNb) + " most similar past bars closed higher " + str.tostring(horizon) + " bars later. This is the analogs' vote, not a win probability.")
    f_row(2, "Agreement", live ? f_bar(prob) + " " + str.tostring(math.round(prob * 100)) + "%" : "—", readC, "Share of analogs that went up.")
    f_row(3, "Projection " + str.tostring(horizon) + " bars", na(pct) ? "—" : f_pct(pct) + " → " + str.tostring(projEnd, format.mintick), na(pct) ? MUTE : pct >= 0 ? cUp : cDn,
         "Where the analogs' average path ends, scaled to today's ATR.")
    f_row(4, "Likely range", na(rngLo) ? "—" : str.tostring(rngLo, format.mintick) + " – " + str.tostring(rngHi, format.mintick), cCone,
         "The ±1 cone at the end of the look-ahead: the analogs' average move ± one spread.")
    f_row(5, "Match quality", matchQ, matchQ == "High" ? cUp : matchQ == "Low" ? cGold : TXT,
         "How close the analogs are compared with usual. Low means today looks unlike most of the memory, so trust the projection less.")
    f_row(6, "Position", pos != 0 ? (pos == 1 ? "Long" : "Short") + " · " + str.tostring(bar_index - sigBar) + " bars · " + (liveR >= 0 ? "+" : "") + str.tostring(liveR, "#.#") + "R" : pend ? "Entry next bar" : "Flat · waiting", pos == 1 ? cUp : pos == -1 ? cDn : MUTE,
         "The breakout trade the indicator is managing, with its open result in R (1R = the initial stop distance).")
    f_row(7, "Trailing stop", pos != 0 ? str.tostring(trl, format.mintick) : "—", pos == 1 ? cUp : pos == -1 ? cDn : MUTE, "Moves only in the trade's favour, " + str.tostring(trailX) + " ATR behind the close.")
    f_row(8, "Last signal", na(lastSigBar) ? lastSig : lastSig + " · " + str.tostring(bar_index - lastSigBar) + " bars ago", str.contains(lastSig, "▲") ? cUp : str.contains(lastSig, "▼") ? cDn : MUTE, "The last breakout signal on this chart.")
    f_row(9, "Signal record", tN == 0 ? "No closed trades" : str.tostring(tN) + " · " + str.tostring(math.round(100.0 * tWin / tN)) + "% win · PF " + (na(pf) ? "—" : str.tostring(pf, "#.##")) + " · " + (sumR >= 0 ? "+" : "") + str.tostring(sumR, "#") + "R", tN == 0 ? MUTE : sumR >= 0 ? cUp : cDn,
         "Every closed breakout trade on the loaded history, after the cost per side. Measured live on this chart.")
    f_row(10, "AI hit rate", hitN == 0 ? "—" : str.tostring(math.round(100.0 * hitOk / hitN)) + "% dir · " + str.tostring(math.round(100.0 * coneOk / hitN)) + "% in cone", TXT,
         "Measured on this chart over " + str.tostring(hitN) + " bars: how often the analogs' majority got the " + str.tostring(horizon) + "-bar direction right, and how often price ended inside the ±1 cone. 50 % direction is a coin flip.")
    string actTxt = (volaOn ? (volaOk ? "Active" : "Quiet") + " · " : "") + "ATR " + (na(atrRel) ? "—" : str.tostring(atrRel, "#.#") + "×") + " · Vol " + (na(vRel) ? "n/a" : str.tostring(vRel, "#.#") + "×")
    f_row(11, "Market", actTxt, volaOn and not volaOk ? MUTE : not na(vRel) and vRel >= volX and volX > 0 ? cGold : TXT,
         "ATR against its " + str.tostring(volaLen) + "-bar average and volume against its 20-bar average. Quiet = the volatility filter blocks signals right now.")
 
// ═════════════════════════════════════════ ALERTS ═════════════════════════════════════════
alertcondition(longSig, "Breakout Long", "Market Memory AI: breakout long (close above the channel on heavy volume)")
alertcondition(shortSig, "Breakout Short", "Market Memory AI: breakout short (close below the channel on heavy volume)")
alertcondition(exitNow, "Trade exit", "Market Memory AI: trailing stop or time stop hit")
alertcondition(not na(prob) and prob >= 0.625 and not (prob[1] >= 0.625), "AI turned bullish", "Market Memory AI: most analogs went up")
alertcondition(not na(prob) and prob <= 0.375 and not (prob[1] <= 0.375), "AI turned bearish", "Market Memory AI: most analogs went down")

← 返回列表