RSI MA Trend - Adaptive Profile Engine

Seckin_Tuncay · study · 309 行 · 点赞 62 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Seckin_Tuncay
// ══════════════════════════════════════════════════════════════════════════════
//  RSI MA TREND - ADAPTIVE PROFILE ENGINE   v1.2
//
//  v1.2 - Signal label text selectable: BUY / BULL / BOĞA.
//
//  v1.1 - Panel modes (Normal / Mobile / Mini), panel position and text size,
//         signal label size. No signal behaviour changed.
//
//  EN: Long-only trend entry: RSI momentum trigger + moving-average trend,
//      managed by an ATR trailing stop. The trigger and the filters adapt to the
//      timeframe and to the asset class. The adaptive ADX regime and the dynamic
//      RSI band are taken from the author's "RSI ADX Divergence Panel - Adaptive
//      Regime Engine".
//  TR: Yalnızca alım yönlü trend girişi: RSI momentum tetikleyicisi + hareketli
//      ortalama trendi, ATR iz süren stop ile yönetilir. Tetikleyici ve filtreler
//      zaman dilimine ve varlık sınıfına göre kendini ayarlar. Adaptif ADX rejimi
//      ve dinamik RSI bandı, yazarın "RSI ADX Divergence Panel" göstergesinden alındı.
//
//  Every default below was chosen by measurement, not by assumption: 7 markets
//  (gold, silver, BTC, ETH, ADA, TUPRS, THYAO) on the Daily and 4h charts.
//  Features that did not help across markets were removed from the code.
// ══════════════════════════════════════════════════════════════════════════════
//@version=6
indicator("RSI MA Trend - Adaptive Profile Engine", shorttitle = "RSI MA TREND", overlay = true, max_labels_count = 500)
 
// ══════════════ 1 · Entry ══════════════
G1 = "1 · Entry"
rsiLen  = input.int(7, "RSI Length", minval = 2, group = G1)
rsiMode = input.string("Auto", "RSI trigger", options = ["Auto", "Fixed level", "Dynamic band"], group = G1, tooltip = "Auto: fixed level on Daily and above, dynamic band intraday - the best result in testing on both.\nFixed level: RSI crosses above the level below.\nDynamic band: RSI crosses above an upper percentile of its own recent distribution, so in a strong trend the band moves up.\n\nOtomatik: günlük ve üstünde sabit seviye, gün içinde dinamik bant - testlerde ikisinde de en iyi sonuç.\nSabit seviye: RSI aşağıdaki seviyeyi yukarı keser.\nDinamik bant: RSI kendi yakın geçmiş dağılımının üst yüzdeliğini yukarı keser; güçlü trendde bant yukarı kayar.")
rsiLvl  = input.float(70.0, "Fixed · RSI level", minval = 1, maxval = 99, step = 1, group = G1)
obPct   = input.int(88, "Dynamic · upper percentile", minval = 50, maxval = 99, group = G1, tooltip = "Same 88th percentile as the RSI ADX Divergence Panel's overbought band.\nRSI ADX Divergence Panel'in aşırı alım bandıyla aynı 88. yüzdelik.")
maType  = input.string("EMA", "MA type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], group = G1, tooltip = "Entry needs the fast MA above the slow MA. 20 type/length pairs were tested: the differences were small and EMA 9/26 was among the best everywhere.\nGiriş için hızlı MA yavaş MA'nın üstünde olmalı. 20 tip/uzunluk çifti test edildi: farklar küçüktü, EMA 9/26 her yerde en iyiler arasındaydı.")
fastLen = input.int(9,  "Fast MA", minval = 2, group = G1)
slowLen = input.int(26, "Slow MA", minval = 2, group = G1)
 
// ══════════════ 2 · Profile · ADX · Higher TF ══════════════
G2 = "2 · Profile · ADX · Higher TF"
profile = input.string("Auto", "Profile", options = ["Auto", "Crypto", "Commodity / Stock", "Manual"], group = G2, tooltip = "Auto: Crypto profile on intraday crypto charts, Commodity / Stock everywhere else (including every Daily chart). Gold and silver futures listed on crypto exchanges (e.g. XAUUSDT.P) count as commodities.\nCrypto: adaptive ADX + ADX rising.\nCommodity / Stock: no ADX, no higher-TF filter.\nManual: the two settings below are used; other profiles ignore them.\n\nWhy: on 4h crypto the ADX filter raised profit factor from 1.2-1.9 to 2.3-3.5 and halved the drawdown. On gold, silver, TUPRS and on every Daily chart it lowered the result.\n\nOtomatik: gün içi kripto grafiğinde Kripto, diğer her yerde (tüm günlük grafikler dahil) Emtia / Hisse. Kripto borsasındaki altın/gümüş vadelileri (ör. XAUUSDT.P) emtia sayılır.\nKripto: adaptif ADX + ADX yükseliyor.\nEmtia / Hisse: ADX ve üst TF filtresi yok.\nElle: aşağıdaki iki ayar kullanılır.\n\nNeden: 4 saatlik kriptoda ADX filtresi kâr faktörünü 1.2-1.9'dan 2.3-3.5'e çıkardı, düşüşü yarıya indirdi. Altın, gümüş, TÜPRAŞ'ta ve tüm günlük grafiklerde sonucu düşürdü.")
adxMode = input.string("Off", "Manual · ADX filter", options = ["Off", "Adaptive", "Adaptive + rising"], group = G2, tooltip = "Used only when Profile = Manual.\nAdaptive: ADX above a percentile of its own history - the TREND regime of the RSI ADX Divergence Panel. The threshold is computed per symbol and timeframe, not fixed.\nAdaptive + rising: ADX also higher than 3 bars ago (trend strengthening).\nA fixed ADX threshold (20, 25, 30) was tested and lost to the adaptive one on every crypto market, so it was removed.\n\nSadece Profil = Elle iken kullanılır.\nAdaptif: ADX kendi geçmişinin yüzdeliğinin üstünde - RSI ADX Divergence Panel'deki TREND rejimi. Eşik sabit değil, her sembol ve periyot için ayrı hesaplanır.\nAdaptif + yükseliyor: ADX ayrıca 3 bar öncesinden yüksek (trend güçleniyor).\nSabit ADX eşiği (20, 25, 30) test edildi, tüm kripto piyasalarında adaptife kaybetti ve kaldırıldı.")
adxLen  = input.int(14, "ADX / DI Length", minval = 2, group = G2)
htfOn   = input.bool(false, "Manual · Higher-TF DI alignment", group = G2, tooltip = "Used only when Profile = Manual. DI+ must lead on one higher period, always read from its last CLOSED bar - no repainting.\nLadder: <=15m -> 1h · 30m -> 2h · 1h -> 4h · 4h -> Daily · Daily -> Weekly.\nTest result: raised profit factor on most markets but cut total profit on metals and stocks. Strongest single case: gold Daily (PF 3.42 -> 5.37, drawdown -36.7R -> -12.2R).\n\nSadece Profil = Elle iken kullanılır. Bir üst periyotta DI+ önde olmalı; her zaman KAPANMIŞ bardan okunur, repaint yoktur.\nTest sonucu: çoğu piyasada kâr faktörünü artırdı ama metal ve hisselerde toplam kazancı düşürdü. En güçlü tek örnek: altın günlük (KF 3.42 -> 5.37, düşüş -36.7R -> -12.2R).")
showCmp = input.bool(false, "Comparison table (research)", group = G2, tooltip = "Runs five variants side by side in the background on the same chart, independent of your settings. Use it to check a new symbol before trusting the Auto profile.\n\nBeş varyantı aynı grafikte, ayarlarından bağımsız olarak arka planda yan yana çalıştırır. Yeni bir sembolde Otomatik profile güvenmeden önce kontrol için kullan.")
 
// ══════════════ 3 · Exit · Risk ══════════════
G3 = "3 · Exit · Risk"
atrLen   = input.int(14, "ATR Length", minval = 1, group = G3)
initAtr  = input.float(2.0, "Initial stop (ATR ×)", minval = 0.5, step = 0.5, group = G3, tooltip = "The distance from entry to the initial stop is 1R. All statistics are in R.\nGirişten başlangıç stopuna olan mesafe 1R'dir. Tüm istatistikler R cinsindendir.")
trailAtr = input.float(4.0, "Trailing stop (ATR ×)", minval = 0.5, step = 0.5, group = G3, tooltip = "The stop trails this many ATR below each bar's high and only moves up. Multipliers 1.5-5 were tested: results improved steadily with width (no single spike), 4 kept the trade count reasonable on every market.\nStop, her barın tepesinden bu kadar ATR aşağıda takip eder ve sadece yukarı gider. 1.5-5 arası test edildi: genişledikçe sonuç düzenli iyileşti (tek bir sıçrama yok), 4 her piyasada işlem sayısını makul tuttu.")
 
// ══════════════ 4 · Statistics ══════════════
G4 = "4 · Statistics"
showStats = input.bool(true, "Statistics panel", group = G4, tooltip = "In-chart record of the signals on this chart. Includes commission, EXCLUDES slippage. Entry on the signal bar's close, exit at the stop (or the open on a gap). Defaults were chosen on this same history, so live results will probably be weaker. This is a measurement tool, not a promise.\n\nBu grafikteki sinyallerin kaydı. Komisyon dahil, kayma HARİÇ. Giriş sinyal barının kapanışında, çıkış stopta (boşlukta açılışta). Varsayılanlar aynı geçmiş veride seçildi; canlı sonuç muhtemelen daha zayıf olur. Bu bir ölçüm aracı, vaat değil.")
commPct   = input.float(0.05, "Commission % (per side)", minval = 0, step = 0.01, group = G4)
 
// ══════════════ 5 · Appearance ══════════════
G5 = "5 · Appearance"
showMa    = input.bool(true,  "MA band",             group = G5)
showStop  = input.bool(true,  "Stop line",           group = G5)
showHma   = input.bool(true,  "HMA reference line",  group = G5, tooltip = "Visual reference only - does not affect signals or statistics. As a filter (price > HMA 200) it helped on gold Daily but hurt TUPRS, BTC and ETH, so it is not part of the logic.\nSadece görsel referans - sinyali ve istatistiği etkilemez. Filtre olarak (fiyat > HMA 200) altın günlükte işe yaradı ama TÜPRAŞ, BTC ve ETH'de zarar verdi; bu yüzden mantığa dahil değil.")
hmaLen    = input.int(200,    "HMA Length", minval = 2, group = G5)
colorBars = input.bool(false, "Color bars while in a position", group = G5)
showTable = input.bool(true,  "Status panel",        group = G5)
pnlMode   = input.string("Normal", "Panel mode", options = ["Normal", "Mobile", "Mini"], group = G5, tooltip = "Normal: full table.\nMobile: four short lines, one size smaller - for phones and narrow screens.\nMini: one-line summary.\n\nNormal: tam tablo.\nMobil: dört kısa satır, bir boy küçük - telefon ve dar ekran için.\nMini: tek satırlık özet.")
pnlPosStr = input.string("Top Right", "Panel position", options = ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left", "Top Center", "Bottom Center"], group = G5)
pnlSizStr = input.string("Small", "Panel text size", options = ["Tiny", "Small", "Normal", "Large"], group = G5)
lblTxt    = input.string("BOĞA", "Signal label text", options = ["BUY", "BULL", "BOĞA"], group = G5, tooltip = "Text on the entry label. The script is long-only, so there is no bear/sell label - the exit is the stop mark (✕), not a bearish signal.\nGiriş etiketindeki yazı. Gösterge yalnızca alım yönlü; bu yüzden AYI/SAT etiketi yok - çıkış stop işaretidir (✕), düşüş sinyali değildir.")
lblSizStr = input.string("Small", "Signal label size", options = ["Tiny", "Small", "Normal", "Large"], group = G5, tooltip = "Size of the BUY label and the stop-exit mark.\nALIM etiketinin ve stop çıkış işaretinin boyutu.")
 
colUp   = #00E676
colDn   = #FF1744
colNeut = #9E9E9E
colWarn = #FFA726
 
// ══════════════ Period-dependent values (same as RSI ADX Divergence Panel) ══════════════
tfSec   = nz(timeframe.in_seconds(), 3600)
regLook = tfSec <= 300 ? 400 : tfSec <= 900 ? 300 : tfSec <= 3600 ? 250 : tfSec <= 86400 ? 200 : 150
regPct  = tfSec <= 300 ? 62  : tfSec <= 900 ? 58  : tfSec <= 86400 ? 55  : 50
htfTf   = tfSec <= 180 ? "15" : tfSec <= 900 ? "60" : tfSec <= 1800 ? "120" : tfSec <= 3600 ? "240" : tfSec <= 14400 ? "D" : tfSec <= 86400 ? "W" : "M"
htfName = htfTf == "15" ? "15m" : htfTf == "60" ? "1h" : htfTf == "120" ? "2h" : htfTf == "240" ? "4h" : htfTf == "D" ? "Daily" : htfTf == "W" ? "Weekly" : "Monthly"
 
// ══════════════ Core calculations ══════════════
f_ma(int len) =>
    e = ta.ema(close, len)
    s = ta.sma(close, len)
    w = ta.wma(close, len)
    h = ta.hma(close, len)
    r = ta.rma(close, len)
    maType == "SMA" ? s : maType == "WMA" ? w : maType == "HMA" ? h : maType == "RMA" ? r : e
 
rsi   = ta.rsi(close, rsiLen)
maF   = f_ma(fastLen)
maS   = f_ma(slowLen)
atr   = ta.atr(atrLen)
trend = maF > maS
c     = commPct / 100
 
obDyn  = ta.percentile_linear_interpolation(rsi, regLook, obPct)
rsiFix = ta.crossover(rsi, rsiLvl)
rsiDyn = ta.crossover(rsi, obDyn)
 
[diP, diM, adx] = ta.dmi(adxLen, adxLen)
adxRef = ta.percentile_linear_interpolation(adx, regLook, regPct)
adxUp  = adx > adx[3]
 
// Higher timeframe: last CLOSED bar ([1] + lookahead_on) - no repainting
[hP, hM] = request.security(syminfo.tickerid, htfTf, [diP[1], diM[1]], lookahead = barmerge.lookahead_on)
htfOk = hP > hM
 
// ══════════════ Profile -> active settings ══════════════
isDaily = tfSec >= 86400
useDyn  = rsiMode == "Dynamic band" or (rsiMode == "Auto" and not isDaily)
trig    = useDyn ? rsiDyn : rsiFix
 
// Metal futures on crypto exchanges (e.g. Binance XAUUSDT.P) are typed "crypto" by TradingView
tkr      = str.upper(syminfo.ticker)
isMetal  = str.contains(tkr, "XAU") or str.contains(tkr, "XAG") or str.contains(tkr, "PAXG") or str.contains(tkr, "XPT") or str.contains(tkr, "XPD") or str.contains(tkr, "GOLD") or str.contains(tkr, "SILVER")
isCrypto = syminfo.type == "crypto" and not isMetal
profUse  = profile == "Auto" ? (isCrypto and not isDaily ? "Crypto" : "Commodity / Stock") : profile
useAdx   = profUse == "Crypto" ? true : profUse == "Manual" ? adxMode != "Off" : false
useRise  = profUse == "Crypto" ? true : profUse == "Manual" ? adxMode == "Adaptive + rising" : false
useHtf   = profUse == "Manual" ? htfOn : false
 
adxOK   = not useAdx or (adx > adxRef and (not useRise or adxUp))
hmaV    = ta.hma(close, hmaLen)
liveSig = trig and trend and adxOK and (not useHtf or htfOk)
 
// ══════════════ Trade engine ══════════════
type Sim
    int   pos     = 0
    float entryPx
    float riskPx
    float stopPx
    int   nT      = 0
    int   nW      = 0
    float sumR    = 0.0
    float gw      = 0.0
    float gl      = 0.0
    float peak    = 0.0
    float dd      = 0.0
    bool  entered = false
    bool  exited  = false
 
method step(Sim s, bool sig) =>
    s.entered := false
    s.exited  := false
    // Open position: check the stop first, then trail it
    if s.pos == 1
        if low <= s.stopPx
            ex = math.min(open, s.stopPx)
            r  = (ex - s.entryPx - (s.entryPx + ex) * c) / s.riskPx
            s.nT   += 1
            s.sumR += r
            if r > 0
                s.nW += 1
                s.gw += r
            else
                s.gl -= r
            s.peak   := math.max(s.peak, s.sumR)
            s.dd     := math.max(s.dd, s.peak - s.sumR)
            s.exited := true
            s.pos    := 0
        else
            s.stopPx := math.max(s.stopPx, high - trailAtr * atr)
    // Entry
    if s.pos == 0 and sig and atr > 0
        s.pos     := 1
        s.entryPx := close
        s.riskPx  := math.max(initAtr * atr, syminfo.mintick)
        s.stopPx  := close - s.riskPx
        s.entered := true
    s
 
f_pf(Sim s) => s.gl > 0 ? s.gw / s.gl : na
 
var live = Sim.new()
live.step(liveSig)
 
// Comparison: each row trades independently in the background, fixed definitions
base0 = rsiFix and trend
baseD = rsiDyn and trend
adxA  = adx > adxRef
 
var cmpNames = array.from("RSI 70 · no filter", "Dynamic RSI · no filter", "RSI 70 + Higher TF", "Dynamic RSI + Higher TF", "Dynamic RSI + Adaptive ADX rising")
var cmpSims  = array.new<Sim>()
if barstate.isfirst
    for i = 0 to cmpNames.size() - 1
        cmpSims.push(Sim.new())
 
cmpSig = array.from(base0, baseD, base0 and htfOk, baseD and htfOk, baseD and adxA and adxUp)
for i = 0 to cmpSims.size() - 1
    cmpSims.get(i).step(cmpSig.get(i))
 
entrySig = live.entered
exitSig  = live.exited
pos      = live.pos
openR    = pos == 1 ? (close - live.entryPx - (live.entryPx + close) * c) / live.riskPx : na
 
// ══════════════ Drawing ══════════════
maCol = trend ? color.new(colUp, 75) : color.new(colDn, 75)
pF = plot(showMa ? maF : na, "Fast MA", color = maCol, linewidth = 1, display = display.all - display.status_line)
pS = plot(showMa ? maS : na, "Slow MA", color = maCol, linewidth = 1, display = display.all - display.status_line)
fill(pF, pS, color = trend ? color.new(colUp, 85) : color.new(colDn, 85), title = "MA band")
 
plot(showHma ? hmaV : na, "HMA", color = color.new(#2962FF, 20), linewidth = 2)
plot(showStop and pos == 1 ? live.stopPx : na, "Stop", color = colUp, style = plot.style_linebr, linewidth = 1)
 
// Entry label: label.new allows a selectable text and size
if entrySig
    label.new(bar_index, low, lblTxt, xloc = xloc.bar_index, yloc = yloc.belowbar, style = label.style_label_up, color = colUp, textcolor = color.black, size = lblSizStr == "Tiny" ? size.tiny : lblSizStr == "Normal" ? size.normal : lblSizStr == "Large" ? size.large : size.small)
// Stop-exit mark: plotshape size must be a constant, so one call per size
plotshape(exitSig and lblSizStr == "Tiny",    "Stop exit",    shape.xcross, location.abovebar, colUp, size = size.tiny,   display = display.pane)
plotshape(exitSig and lblSizStr == "Small",   "Stop exit ",   shape.xcross, location.abovebar, colUp, size = size.small,  display = display.pane)
plotshape(exitSig and lblSizStr == "Normal",  "Stop exit  ",  shape.xcross, location.abovebar, colUp, size = size.normal, display = display.pane)
plotshape(exitSig and lblSizStr == "Large",   "Stop exit   ", shape.xcross, location.abovebar, colUp, size = size.large,  display = display.pane)
 
barcolor(colorBars and pos == 1 ? colUp : na)
 
// ══════════════ Status + statistics panel ══════════════
f_rTxt(float r) => (r >= 0 ? "+" : "") + str.tostring(r, "#.##") + "R"
f_rCol(float r) => r > 0 ? colUp : r < 0 ? colDn : colNeut
f_pfTxt(float pf) => na(pf) ? "—" : str.tostring(pf, "#.##")
f_pfCol(float pf) => na(pf) ? colNeut : pf >= 1 ? colUp : colDn
 
pnlPos = pnlPosStr == "Top Right" ? position.top_right : pnlPosStr == "Middle Right" ? position.middle_right : pnlPosStr == "Bottom Right" ? position.bottom_right : pnlPosStr == "Top Left" ? position.top_left : pnlPosStr == "Middle Left" ? position.middle_left : pnlPosStr == "Bottom Left" ? position.bottom_left : pnlPosStr == "Top Center" ? position.top_center : position.bottom_center
f_size(string sz) => sz == "Tiny" ? size.tiny : sz == "Normal" ? size.normal : sz == "Large" ? size.large : size.small
f_down(string sz) => sz == "Large" ? size.normal : sz == "Normal" ? size.small : size.tiny
 
var table tb = table.new(pnlPos, 2, 12, bgcolor = color.new(#000000, 25), border_width = 1)
 
if showTable and barstate.islast
    table.clear(tb, 0, 0, 1, 11)
    nT     = live.nT
    winPct = nT > 0 ? float(live.nW) / nT * 100 : 0.0
    avgR   = nT > 0 ? live.sumR / nT : 0.0
    pf     = f_pf(live)
    adxTxt = profUse + " · " + str.tostring(adx, "#.0") + (not useAdx ? " · ADX off" : " / thr " + str.tostring(adxRef, "#.0") + (useRise ? " + rising" : ""))
    rsiTxt = str.tostring(rsi, "#.0") + (useDyn ? " / dynamic band " + str.tostring(obDyn, "#") : " / fixed level " + str.tostring(rsiLvl, "#"))
    posTxt = pos == 1 ? "LONG  " + f_rTxt(openR) : "Waiting"
    posCol = pos == 1 ? colUp : colNeut
    bgPos  = pos == 1 ? color.new(colUp, 75) : color.new(#000000, 25)
 
    if pnlMode == "Mini"
        ts = f_down(pnlSizStr)
        table.cell(tb, 0, 0, (trend ? "▲ " : "▼ ") + posTxt + (showStats ? "  ·  PF " + f_pfTxt(pf) + " · " + str.tostring(nT) + " tr" : ""), text_color = pos == 1 ? colUp : trend ? colUp : colDn, bgcolor = bgPos, text_size = ts)
 
    else if pnlMode == "Mobile"
        ts   = f_down(pnlSizStr)
        line3 = (profUse == "Crypto" ? "Crypto" : profUse == "Manual" ? "Manual" : "Cmdty/Stock") + (useAdx ? " · ADX " + str.tostring(adx, "#") + "/" + str.tostring(adxRef, "#") : " · ADX off") + "   " + htfName + (htfOk ? " ▲" : " ▼") + (useHtf ? " ✓" : "")
        table.cell(tb, 0, 0, (trend ? "▲ " : "▼ ") + posTxt, text_color = posCol == colNeut ? (trend ? colUp : colDn) : posCol, bgcolor = bgPos, text_size = ts, text_halign = text.align_left)
        table.cell(tb, 0, 1, "RSI " + str.tostring(rsi, "#") + " / " + (useDyn ? "dyn " + str.tostring(obDyn, "#") : str.tostring(rsiLvl, "#")) + "   " + maType + " " + str.tostring(fastLen) + "/" + str.tostring(slowLen), text_color = colNeut, text_size = ts, text_halign = text.align_left)
        table.cell(tb, 0, 2, line3, text_color = adxOK ? colUp : colWarn, text_size = ts, text_halign = text.align_left)
        if showStats
            table.cell(tb, 0, 3, str.tostring(nT) + " tr · PF " + f_pfTxt(pf) + " · " + f_rTxt(live.sumR) + " · DD -" + str.tostring(live.dd, "#.#") + "R", text_color = f_pfCol(pf), text_size = ts, text_halign = text.align_left)
 
    else
        ts = f_size(pnlSizStr)
        table.cell(tb, 0, 0, "Trend", text_color = color.white, text_size = ts)
        table.cell(tb, 1, 0, (trend ? "up · " : "down · ") + maType + " " + str.tostring(fastLen) + "/" + str.tostring(slowLen), text_color = trend ? colUp : colDn, text_size = ts)
        table.cell(tb, 0, 1, "Profile · ADX", text_color = color.white, text_size = ts)
        table.cell(tb, 1, 1, adxTxt, text_color = adxOK ? colUp : colWarn, text_size = ts)
        table.cell(tb, 0, 2, "Higher TF (" + htfName + ")", text_color = color.white, text_size = ts)
        table.cell(tb, 1, 2, (htfOk ? "DI+ ▲" : "DI− ▼") + (useHtf ? " · filter on" : " · filter off"), text_color = htfOk ? colUp : colDn, text_size = ts)
        table.cell(tb, 0, 3, "RSI", text_color = color.white, text_size = ts)
        table.cell(tb, 1, 3, rsiTxt, text_color = colNeut, text_size = ts)
        table.cell(tb, 0, 4, "Position", text_color = color.white, text_size = ts)
        table.cell(tb, 1, 4, posTxt, text_color = posCol, text_size = ts)
        if showStats
            table.cell(tb, 0, 5, "STATISTICS", text_color = colNeut, text_size = ts)
            table.cell(tb, 1, 5, "stop " + str.tostring(initAtr, "#.#") + " / trail " + str.tostring(trailAtr, "#.#") + " ATR · no slippage", text_color = colNeut, text_size = ts)
            table.cell(tb, 0, 6, "Trades", text_color = color.white, text_size = ts)
            table.cell(tb, 1, 6, str.tostring(nT), text_color = color.white, text_size = ts)
            table.cell(tb, 0, 7, "Win rate", text_color = color.white, text_size = ts)
            table.cell(tb, 1, 7, str.tostring(winPct, "#.#") + "%", text_color = color.white, text_size = ts)
            table.cell(tb, 0, 8, "Total / Avg", text_color = color.white, text_size = ts)
            table.cell(tb, 1, 8, f_rTxt(live.sumR) + "  ·  " + f_rTxt(avgR), text_color = f_rCol(live.sumR), text_size = ts)
            table.cell(tb, 0, 9, "Profit factor", text_color = color.white, text_size = ts)
            table.cell(tb, 1, 9, f_pfTxt(pf), text_color = f_pfCol(pf), text_size = ts)
            table.cell(tb, 0, 10, "Max drawdown", text_color = color.white, text_size = ts)
            table.cell(tb, 1, 10, "-" + str.tostring(live.dd, "#.##") + "R", text_color = colDn, text_size = ts)
 
// Comparison table
var table cmp = table.new(position.bottom_right, 6, 12, bgcolor = color.new(#000000, 25), border_width = 1)
 
if showCmp and barstate.islast
    ts = f_size(pnlSizStr)
    table.cell(cmp, 0, 0, "Variant",  text_color = colNeut, text_size = ts, text_halign = text.align_left)
    table.cell(cmp, 1, 0, "Trades",   text_color = colNeut, text_size = ts)
    table.cell(cmp, 2, 0, "Win",      text_color = colNeut, text_size = ts)
    table.cell(cmp, 3, 0, "Total",    text_color = colNeut, text_size = ts)
    table.cell(cmp, 4, 0, "PF",       text_color = colNeut, text_size = ts)
    table.cell(cmp, 5, 0, "DD",       text_color = colNeut, text_size = ts)
    for [i, sm] in cmpSims
        pfx = f_pf(sm)
        wr  = sm.nT > 0 ? float(sm.nW) / sm.nT * 100 : 0.0
        bg  = i <= 1 ? color.new(#2A2E39, 0) : color.new(#000000, 100)
        table.cell(cmp, 0, i + 1, cmpNames.get(i), text_color = color.white, bgcolor = bg, text_size = ts, text_halign = text.align_left)
        table.cell(cmp, 1, i + 1, str.tostring(sm.nT), text_color = color.white, bgcolor = bg, text_size = ts)
        table.cell(cmp, 2, i + 1, str.tostring(wr, "#.#") + "%", text_color = color.white, bgcolor = bg, text_size = ts)
        table.cell(cmp, 3, i + 1, f_rTxt(sm.sumR), text_color = f_rCol(sm.sumR), bgcolor = bg, text_size = ts)
        table.cell(cmp, 4, i + 1, f_pfTxt(pfx), text_color = f_pfCol(pfx), bgcolor = bg, text_size = ts)
        table.cell(cmp, 5, i + 1, "-" + str.tostring(sm.dd, "#.#") + "R", text_color = colDn, bgcolor = bg, text_size = ts)
    table.cell(cmp, 0, 11, "Higher TF = " + htfName + " · adaptive threshold: " + str.tostring(regPct) + "th pct / " + str.tostring(regLook) + " bars", text_color = colWarn, text_size = ts, text_halign = text.align_left)
 
// ══════════════ Alerts ══════════════
// Set alerts to "Once Per Bar Close".
alertcondition(entrySig, "Buy",       "RSI MA TREND: BUY | ALIM - {{ticker}} {{interval}} {{close}}")
alertcondition(exitSig,  "Stop exit", "RSI MA TREND: stop exit | stop çıkışı - {{ticker}} {{interval}} {{close}}")

← 返回列表