本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("VWAP Surge Pilot", shorttitle="VSP", overlay=true, max_labels_count=500)
cUp = #26a69a
cDn = #ef5350
BG = color.new(#131722, 10)
NC = 24 // tested combinations: ADX 2 × Volume 3 × HTF 2 × WAE 2
// =====================================================================
// 1 · VWAP
// =====================================================================
G1 = "1 · VWAP"
vwAnchor = input.string("Auto", "Reset period", options=["Auto", "Day", "Week", "Month", "Year"], group=G1,
tooltip="Auto: ≤1H → Day, 2H-4H → Week, 6H-1D → Month, above → Year. Keeps VWAP built from enough bars on every timeframe.\n\nTR: VWAP'ın sıfırlanma periyodu. Otomatik: 1s ve altı → Gün, 2s-4s → Hafta, 6s-1G → Ay, üstü → Yıl. Böylece VWAP her periyotta yeterli mumdan hesaplanır.")
vwSrc = input.source(hlc3, "Source", group=G1)
showBands = input.bool(false, "Deviation bands", group=G1, inline="b")
bandMult = input.float(1.0, "×", minval=0.1, step=0.1, group=G1, inline="b",
tooltip="Standard deviation bands around VWAP.\n\nTR: VWAP etrafında standart sapma bantları.")
// =====================================================================
// 2 · Turtle Channel
// =====================================================================
G2 = "2 · Turtle Channel"
entryLen = input.int(20, "Entry channel", minval=2, group=G2,
tooltip="Breakout of the highest high / lowest low of this many bars triggers an entry.\n\nTR: Bu kadar barın en yüksek / en düşük seviyesinin kırılması girişi tetikler.")
exitLen = input.int(10, "Exit channel (trailing stop)", minval=2, group=G2,
tooltip="A close beyond the opposite side of this shorter channel exits the trade.\n\nTR: Fiyat bu kısa kanalın ters tarafının dışında kapanırsa işlemden çıkılır.")
win = input.int(3, "Breakout validity (bars)", minval=0, maxval=20, group=G2,
tooltip="How many bars after the channel breakout (and volume spike) the other confirmations may still arrive. 0 = all on the same bar.\n\nTR: Kanal kırılımından (ve hacim patlamasından) sonra diğer onayların kaç bar içinde gelebileceği. 0 = hepsi aynı mumda olmalı.")
// =====================================================================
// 3 · WAE Explosion
// =====================================================================
G3 = "3 · WAE Explosion"
waeMode = input.string("Strict", "Confirmation mode (Manual)", options=["Strict", "Loose"], group=G3,
tooltip="Strict: bar has the right color AND is above the white explosion line.\nLoose: right color and larger than the previous bar is enough.\nIn Autopilot this is chosen automatically.\n\nTR: Sıkı: bar doğru renkte VE beyaz patlama çizgisinin üstünde olmalı.\nGevşek: bar doğru renkte ve bir önceki bardan büyük olması yeterli.\nOto pilotta bu seçim otomatik yapılır.")
sens = input.int(150, "Sensitivity", minval=1, group=G3)
fastLen = input.int(20, "Fast EMA", minval=1, group=G3)
slowLen = input.int(40, "Slow EMA", minval=1, group=G3)
bbLen = input.int(20, "BB length", minval=2, group=G3)
bbMult = input.float(2.0, "BB multiplier", minval=0.1, step=0.1, group=G3)
useDead = input.bool(true, "Dead zone filter", group=G3,
tooltip="Ignores momentum bars too small relative to average true range.\n\nTR: Ortalama gerçek aralığa göre çok küçük kalan momentum barlarını yok sayar.")
deadMult = input.float(3.7, "Dead zone multiplier", minval=0.1, step=0.1, group=G3)
// =====================================================================
// 4 · Extra Filters
// =====================================================================
G4 = "4 · Extra Filters"
filtMode = input.string("Autopilot", "Filter selection", options=["Autopilot", "Manual"], group=G4,
tooltip="Autopilot: back-tests 24 filter combinations (ADX off/dynamic, Volume off/fixed/dynamic, HTF, WAE strict/loose) in parallel and trades with the one that performed best so far. Selection uses only past trades — no look-ahead.\nManual: settings marked '(Manual)' apply.\n\nTR: Oto pilot: 24 filtre kombinasyonunu arka planda aynı anda test eder ve o ana kadar en iyi sonucu vereni kullanır. Seçim yalnızca geçmiş işlemlere bakar, ileriye bakmaz.\nManuel: '(Manual)' yazan ayarlar geçerli olur.")
autoMetric = input.string("Profit factor", "Autopilot metric", options=["Profit factor", "Return / DD"], group=G4,
tooltip="Profit factor: gross profit ÷ gross loss.\nReturn / DD: total return ÷ max drawdown — rewards smaller drawdowns.\n\nTR: Kâr faktörü: kazanç ÷ kayıp.\nGetiri / DD: toplam getiri ÷ maksimum düşüş — düşüşü küçük olanı ödüllendirir.")
minTr = input.int(30, "Autopilot min. trades", minval=5, group=G4,
tooltip="Combinations with fewer trades are not eligible. A high profit factor from few trades may be luck.\n\nTR: Bu sayıdan az işlem yapmış kombinasyonlar seçilmez. Az işlemle gelen yüksek kâr faktörü tesadüf olabilir.")
switchPct = input.int(10, "Autopilot switch threshold (%)", minval=0, maxval=100, group=G4,
tooltip="A new combination must beat the active one's score by this percentage before switching. Reduces losses from frequent switching. 0 = always switch to the best.\n\nTR: Yeni kombinasyon, aktif olanın skorunu bu yüzde kadar geçmedikçe geçiş yapılmaz. Sık değişimden doğan kaybı azaltır. 0 = her zaman en iyiye geç.")
adxMode = input.string("Off", "ADX (Manual)", options=["Off", "Dynamic"], group=G4,
tooltip="Dynamic: ADX is above its own percentile of the last N bars (with a floor) AND rising; DI direction must match the signal.\n\nTR: Dinamik: ADX, son N bardaki kendi yüzdelik değerinin (alt sınır: taban) üstünde VE yükseliyor; DI yönü sinyalle aynı olmalı.")
adxLen = input.int(14, "ADX length", minval=2, group=G4)
dynLen = input.int(100, "ADX dynamic window", minval=20, group=G4, inline="d")
dynPct = input.int(50, "Percentile", minval=10, maxval=90, group=G4, inline="d",
tooltip="50 = median ADX of the last N bars. Higher = stricter filter.\n\nTR: 50 = son N barın ADX medyanı. Yükseltirseniz filtre sıkılaşır.")
dynFloor = input.float(15, "ADX dynamic floor", minval=1, group=G4,
tooltip="The dynamic threshold never drops below this value — prevents it from sinking too low in long ranges.\n\nTR: Dinamik eşik bu değerin altına inmez — uzun yatay dönemlerde eşiğin çok düşmesini engeller.")
volMode = input.string("Off", "Volume (Manual)", options=["Off", "Fixed", "Dynamic"], group=G4,
tooltip="Relative volume = bar volume ÷ volume average.\nFixed: relative volume above a fixed multiplier (no direction rule).\nDynamic: relative volume above its own percentile of the last N bars (min 1.0) AND the spike candle points in the signal direction (long → green, short → red).\n\nTR: Göreli hacim = mum hacmi ÷ hacim ortalaması.\nSabit: göreli hacim sabit çarpanı aşmalı (yön şartı yok).\nDinamik: göreli hacim son N bardaki kendi yüzdelik değerini (en az 1.0) aşmalı VE patlama mumu sinyal yönünde olmalı (long → yeşil, short → kırmızı).")
volLen = input.int(20, "Volume average", minval=2, group=G4)
volMult = input.float(1.5, "Volume fixed multiplier", minval=0.1, step=0.1, group=G4)
dynVolLen = input.int(100, "Volume dynamic window", minval=20, group=G4, inline="hv")
dynVolPct = input.int(70, "Percentile", minval=10, maxval=95, group=G4, inline="hv",
tooltip="70 = relative volume higher than 70% of the last N bars. Higher = only rarer spikes count.\n\nTR: 70 = son N barın %70'inden yüksek göreli hacim. Yükseltirseniz yalnızca daha nadir patlamalar sayılır.")
useHtf = input.bool(false, "Higher timeframe trend (Manual)", group=G4,
tooltip="Long only above the higher timeframe EMA, short only below it.\n\nTR: Long yalnızca üst zaman dilimi EMA'sının üstünde, short yalnızca altında açılır.")
htfSel = input.string("Auto", "HTF period", options=["Auto", "1H", "4H", "1D", "1W", "1M"], group=G4,
tooltip="Auto: ≤5m → 1H, 15m-1H → 4H, 2H-4H → 1D, 6H-1D → 1W, above → 1M.\n\nTR: Otomatik: 5dk ve altı → 1s, 15dk-1s → 4s, 2s-4s → 1G, 6s-1G → 1H, üstü → 1A.")
htfLen = input.int(50, "HTF EMA length", minval=2, group=G4)
// =====================================================================
// 5 · Signal · Risk
// =====================================================================
G5 = "5 · Signal · Risk"
dirMode = input.string("Both", "Trade direction", options=["Both", "Long only", "Short only"], group=G5,
tooltip="For assets with a one-sided trend (e.g. gold in TRY → Long only). Statistics and Autopilot follow this setting.\n\nTR: Tek yönlü trendi olan varlıklar için (ör. gram altın → Sadece long). İstatistik ve oto pilot da bu yöne göre hesaplanır.")
waitClose = input.bool(true, "Wait for bar close (no repaint)", group=G5,
tooltip="Signals are confirmed only when the bar closes, so they never disappear.\n\nTR: Sinyaller yalnızca mum kapanınca onaylanır, sonradan kaybolmaz.")
useAtr = input.bool(true, "ATR max stop", group=G5, inline="atr")
atrMult = input.float(2.5, "× ATR", minval=0.5, step=0.1, group=G5, inline="atr",
tooltip="A fixed stop-loss is placed this many ATRs from the entry price. If touched intrabar, the trade exits at the stop (or at the open on a gap). The exit channel still applies — whichever comes first.\n\nTR: Girişte, giriş fiyatından bu kadar ATR uzağa sabit bir zarar kesme konur. Mum içinde dokunursa stop fiyatından (boşlukla açılırsa açılış fiyatından) çıkılır. Çıkış kanalı da geçerlidir; hangisi önce gelirse.")
atrLen = input.int(14, "ATR length", minval=2, group=G5)
showExit = input.bool(true, "Exit labels", group=G5)
showStop = input.bool(true, "Stop lines", group=G5)
// =====================================================================
// 6 · Statistics
// =====================================================================
G6 = "6 · Statistics"
showStats = input.bool(true, "Statistics panel", group=G6, inline="s")
statPos = input.string("Bottom right", "", options=["Bottom right", "Bottom left", "Top left"], group=G6, inline="s")
showCmp = input.bool(true, "Filter comparison", group=G6, inline="c")
cmpPos = input.string("Bottom left", "", options=["Bottom left", "Bottom right", "Top left"], group=G6, inline="c",
tooltip="Shows all filter combinations' results side by side, sorted by the Autopilot metric. ▶ marks the active one.\n\nTR: Tüm filtre kombinasyonlarının sonuçlarını, oto pilot ölçütüne göre sıralı gösterir. ▶ aktif olanı işaretler.")
cmpRows = input.int(8, "Comparison rows", minval=1, maxval=24, group=G6)
posPct = input.float(100, "Position size (% of balance)", minval=1, maxval=1000, step=5, group=G6,
tooltip="Share of the balance used in each trade for Total and Max DD. 100 = full balance. Above 100 simulates leverage (e.g. 300 = 3x). Profit factor, win rate and Avg trade do not change.\n\nTR: Toplam ve Maks. DD hesabında her işlemde kullanılan bakiye oranı. 100 = tüm bakiye. 100'ün üstü kaldıracı simüle eder (ör. 300 = 3x). Kâr faktörü, kazanma oranı ve ortalama işlem değişmez.")
showMtf = input.bool(true, "Timeframe summary", group=G6, inline="m")
mtfPos = input.string("Top center", "", options=["Top center", "Top left", "Bottom left", "Bottom right"], group=G6, inline="m",
tooltip="Runs the whole system (Autopilot included) on 15m, 1H, 4H and 1D in the background and shows the results side by side. ★ = recommended timeframe by the Autopilot metric (min. trades applies). Lower timeframes load history only from the chart's first bar, so results depend on the open chart ('Since' column). If the script becomes slow, turn this off.\n\nTR: Sistemin tamamını (oto pilot dahil) arka planda 15dk, 1s, 4s ve 1G'de çalıştırır, sonuçları yan yana gösterir. ★ = oto pilot ölçütüne göre önerilen zaman dilimi (min. işlem şartı geçerli). Düşük zaman dilimlerinin verisi açık grafiğin ilk mumundan başlar, bu yüzden sonuçlar açık grafiğe göre değişir ('Since' sütunu). Gösterge yavaşlarsa kapatın.")
fee = input.float(0.05, "Commission (one way %)", minval=0, step=0.01, group=G6,
tooltip="Deducted twice per trade (entry + exit). Binance futures taker ≈ 0.05%. Returns are unleveraged. Total and Max DD are compounded (full balance in every trade); Max DD = largest fall from an equity peak. With leverage, multiply DD by the leverage.\n\nTR: Her işlemden giriş + çıkış olarak iki kez düşülür. Binance vadeli taker ≈ %0.05. Getiriler kaldıraçsızdır. Toplam ve Maks. DD bileşik hesaplanır (her işlemde tüm bakiye); Maks. DD = bakiye zirvesinden en büyük düşüş. Kaldıraç kullanıyorsanız DD'yi kaldıraçla çarpın.")
// =====================================================================
// 7 · Display
// =====================================================================
G7 = "7 · Display"
showChan = input.bool(true, "Show Turtle channel", group=G7)
showTable = input.bool(true, "Status table", group=G7)
// ---------------------------------------------------------------------
// VWAP
// ---------------------------------------------------------------------
tfSec = timeframe.in_seconds()
autoName = tfSec <= 3600 ? "Day" : tfSec <= 14400 ? "Week" : tfSec <= 86400 ? "Month" : "Year"
anchorNm = vwAnchor == "Auto" ? autoName : vwAnchor
anchorTf = anchorNm == "Day" ? "D" : anchorNm == "Week" ? "W" : anchorNm == "Month" ? "M" : "12M"
newAnchor = timeframe.change(anchorTf)
[vw, vwU, vwL] = ta.vwap(vwSrc, newAnchor, bandMult)
noVol = ta.cum(nz(volume)) == 0
// ---------------------------------------------------------------------
// Turtle channel
// ---------------------------------------------------------------------
up = ta.highest(high, entryLen)[1]
dn = ta.lowest(low, entryLen)[1]
exUp = ta.highest(high, exitLen)[1]
exDn = ta.lowest(low, exitLen)[1]
brkUp = close > up
brkDn = close < dn
recUp = nz(ta.barssince(brkUp), 9999) <= win
recDn = nz(ta.barssince(brkDn), 9999) <= win
// ---------------------------------------------------------------------
// Waddah Attar Explosion
// ---------------------------------------------------------------------
macdNow = ta.ema(close, fastLen) - ta.ema(close, slowLen)
t1 = (macdNow - macdNow[1]) * sens
e1 = 2.0 * bbMult * ta.stdev(close, bbLen) // BB upper - BB lower = explosion line
trUp = t1 >= 0 ? t1 : 0.0
trDn = t1 < 0 ? -t1 : 0.0
dead = ta.rma(ta.tr(true), 100) * deadMult
deadL = not useDead or trUp > dead
deadS = not useDead or trDn > dead
waeLS = trUp > e1 and deadL // strict
waeSS = trDn > e1 and deadS
waeLG = trUp > 0 and trUp > trUp[1] and deadL // loose
waeSG = trDn > 0 and trDn > trDn[1] and deadS
// ---------------------------------------------------------------------
// ADX (dynamic)
// ---------------------------------------------------------------------
[diP, diM, adxV] = ta.dmi(adxLen, adxLen)
adxDyn = math.max(dynFloor, ta.percentile_linear_interpolation(adxV, dynLen, dynPct))
adxRise = adxV > adxV[1]
adxDL = adxV > adxDyn and adxRise and diP > diM
adxDS = adxV > adxDyn and adxRise and diM > diP
// ---------------------------------------------------------------------
// Volume (fixed + dynamic)
// ---------------------------------------------------------------------
volAvg = ta.sma(volume, volLen)
relVol = volAvg > 0 ? volume / volAvg : na
volDyn = math.max(1.0, ta.percentile_linear_interpolation(relVol, dynVolLen, dynVolPct))
spkS = relVol > volMult
spkDU = relVol > volDyn and close > open
spkDD = relVol > volDyn and close < open
volRecS = nz(ta.barssince(spkS), 9999) <= win
volRecL = nz(ta.barssince(spkDU), 9999) <= win // dynamic, long side
volRecH = nz(ta.barssince(spkDD), 9999) <= win // dynamic, short side
// ---------------------------------------------------------------------
// Higher timeframe
// ---------------------------------------------------------------------
autoHtf = tfSec <= 300 ? "60" : tfSec <= 3600 ? "240" : tfSec <= 14400 ? "D" : tfSec <= 86400 ? "W" : "M"
htfTf = htfSel == "Auto" ? autoHtf : htfSel == "1H" ? "60" : htfSel == "4H" ? "240" : htfSel == "1D" ? "D" : htfSel == "1W" ? "W" : "M"
htfNm = htfTf == "60" ? "1H" : htfTf == "240" ? "4H" : htfTf == "D" ? "1D" : htfTf == "W" ? "1W" : "1M"
htfEma = request.security(syminfo.tickerid, htfTf, ta.ema(close, htfLen)[1], lookahead=barmerge.lookahead_on)
htfL = close > htfEma
htfS = close < htfEma
atrV = ta.atr(atrLen)
ok = not waitClose or barstate.isconfirmed
allowL = dirMode != "Short only"
allowS = dirMode != "Long only"
// ---------------------------------------------------------------------
// Combination helpers
// ---------------------------------------------------------------------
cAdx(int c) => c % 2 == 1 // ADX dynamic on?
cVol(int c) => int(c / 2) % 3 // 0 off · 1 fixed · 2 dynamic
cHtf(int c) => int(c / 6) % 2 == 1
cLoose(int c) => int(c / 12) % 2 == 1
condL(int c) =>
v = cVol(c)
allowL and close > vw and recUp and (cLoose(c) ? waeLG : waeLS) and (not cAdx(c) or adxDL) and (v == 0 or (v == 1 ? volRecS : volRecL)) and (not cHtf(c) or htfL) and ok
condS(int c) =>
v = cVol(c)
allowS and close < vw and recDn and (cLoose(c) ? waeSG : waeSS) and (not cAdx(c) or adxDS) and (v == 0 or (v == 1 ? volRecS : volRecH)) and (not cHtf(c) or htfS) and ok
cName(int c) =>
string s = ""
v = cVol(c)
if cAdx(c)
s += "ADX-D + "
if v == 1
s += "Vol + "
else if v == 2
s += "Vol-D + "
if cHtf(c)
s += "HTF + "
if cLoose(c)
s += "WAE-L + "
s == "" ? "No filter" : str.substring(s, 0, str.length(s) - 3)
calcScore(int n, float gw, float gl, float cm, float dd) =>
float s = -1e9
if n >= minTr
s := autoMetric == "Profit factor" ? (gl > 0 ? gw / gl : 99.0) : cm / math.max(dd, 1.0)
s
// ---------------------------------------------------------------------
// Background test arrays
// ---------------------------------------------------------------------
var aPos = array.new<int>(NC, 0)
var aEp = array.new<float>(NC, na)
var aSt = array.new<float>(NC, na)
var aN = array.new<int>(NC, 0)
var aW = array.new<int>(NC, 0)
var aGW = array.new<float>(NC, 0.0)
var aGL = array.new<float>(NC, 0.0)
var aCum = array.new<float>(NC, 0.0)
var aPk = array.new<float>(NC, 1.0)
var aEq = array.new<float>(NC, 1.0)
var aDD = array.new<float>(NC, 0.0)
var aSc = array.new<float>(NC, -1e9)
// ---------------------------------------------------------------------
// Active combination (based only on results up to previous bars)
// ---------------------------------------------------------------------
manualIdx = (adxMode == "Dynamic" ? 1 : 0) + (volMode == "Fixed" ? 2 : volMode == "Dynamic" ? 4 : 0) + (useHtf ? 6 : 0) + (waeMode == "Loose" ? 12 : 0)
var int active = 0
if filtMode == "Autopilot"
bestV = array.max(aSc)
curV = array.get(aSc, active)
if bestV > -1e8
if curV <= -1e8 or bestV > curV + math.abs(curV) * switchPct / 100.0
active := array.indexof(aSc, bestV)
else
active := manualIdx
fAdx = cAdx(active)
fVol = cVol(active)
fHtf = cHtf(active)
fLoose = cLoose(active)
// ---------------------------------------------------------------------
// Main signals
// ---------------------------------------------------------------------
longCond = condL(active)
shortCond = condS(active)
var int pos = 0
var float entryPx = na
var float stopPx = na
int closeDir = 0
float exitPx = close
hitL = pos == 1 and useAtr and not na(stopPx) and low <= stopPx and ok
hitS = pos == -1 and useAtr and not na(stopPx) and high >= stopPx and ok
chL = pos == 1 and close < exDn and ok
chS = pos == -1 and close > exUp and ok
if hitL or hitS
closeDir := pos
exitPx := hitL ? math.min(open, stopPx) : math.max(open, stopPx)
pos := 0
else if chL or chS
closeDir := pos
pos := 0
longExit = hitL or chL
shortExit = hitS or chS
longSig = longCond and pos != 1
shortSig = shortCond and pos != -1
if longSig
if pos == -1
closeDir := -1
pos := 1
else if shortSig
if pos == 1
closeDir := 1
pos := -1
// ---------------------------------------------------------------------
// Main statistics
// ---------------------------------------------------------------------
var int t0 = time
var int nTr = 0
var int nWin = 0
var int nL = 0
var int nLW = 0
var int nS = 0
var int nSW = 0
var int nStop = 0
var float grossW = 0.0
var float grossL = 0.0
var float cum = 0.0 // compounded total return %
var float sumR = 0.0 // sum of trade returns (for average)
var float eq = 1.0 // equity, starts at 1
var float peak = 1.0
var float maxDD = 0.0
var float best = na
var float worst = na
if closeDir != 0 and not na(entryPx)
ret = closeDir * (exitPx - entryPx) / entryPx * 100 - 2 * fee
nTr += 1
nStop += (hitL or hitS) ? 1 : 0
if ret > 0
nWin += 1
grossW += ret
else
grossL += -ret
if closeDir == 1
nL += 1
nLW += ret > 0 ? 1 : 0
else
nS += 1
nSW += ret > 0 ? 1 : 0
sumR += ret
eq := math.max(0.0, eq * (1 + ret / 100 * posPct / 100))
peak := math.max(peak, eq)
maxDD := math.max(maxDD, peak > 0 ? (peak - eq) / peak * 100 : 0.0)
cum := (eq - 1) * 100
best := na(best) ? ret : math.max(best, ret)
worst := na(worst) ? ret : math.min(worst, ret)
if longSig or shortSig
entryPx := close
stopPx := useAtr ? (longSig ? close - atrMult * atrV : close + atrMult * atrV) : na
if pos == 0
stopPx := na
openRet = pos != 0 and not na(entryPx) ? pos * (close - entryPx) / entryPx * 100 : na
// ---------------------------------------------------------------------
// Background: test all 24 combinations at once
// ---------------------------------------------------------------------
for c = 0 to NC - 1
lc = condL(c)
sc = condS(c)
p = array.get(aPos, c)
ep = array.get(aEp, c)
st = array.get(aSt, c)
int cd = 0
float xp = close
hL = p == 1 and useAtr and not na(st) and low <= st and ok
hS = p == -1 and useAtr and not na(st) and high >= st and ok
if hL or hS
cd := p
xp := hL ? math.min(open, st) : math.max(open, st)
p := 0
else if (p == 1 and close < exDn and ok) or (p == -1 and close > exUp and ok)
cd := p
p := 0
ls = lc and p != 1
ss = sc and p != -1
if ls
if p == -1
cd := -1
p := 1
else if ss
if p == 1
cd := 1
p := -1
if cd != 0 and not na(ep)
r = cd * (xp - ep) / ep * 100 - 2 * fee
array.set(aN, c, array.get(aN, c) + 1)
if r > 0
array.set(aW, c, array.get(aW, c) + 1)
array.set(aGW, c, array.get(aGW, c) + r)
else
array.set(aGL, c, array.get(aGL, c) - r)
eqC = math.max(0.0, array.get(aEq, c) * (1 + r / 100 * posPct / 100))
pk = math.max(array.get(aPk, c), eqC)
cm = (eqC - 1) * 100
array.set(aEq, c, eqC)
array.set(aCum, c, cm)
array.set(aPk, c, pk)
array.set(aDD, c, math.max(array.get(aDD, c), pk > 0 ? (pk - eqC) / pk * 100 : 0.0))
array.set(aSc, c, calcScore(array.get(aN, c), array.get(aGW, c), array.get(aGL, c), cm, array.get(aDD, c)))
if ls or ss
ep := close
st := useAtr ? (ls ? close - atrMult * atrV : close + atrMult * atrV) : na
if p == 0
st := na
array.set(aPos, c, p)
array.set(aEp, c, ep)
array.set(aSt, c, st)
// ---------------------------------------------------------------------
// Multi-timeframe: whole system as one function, run per timeframe
// ---------------------------------------------------------------------
cond(bool base, bool wS, bool wG, bool aOk, bool vS, bool vD, bool hOk, int c) =>
v = cVol(c)
base and (cLoose(c) ? wG : wS) and (not cAdx(c) or aOk) and (v == 0 or (v == 1 ? vS : vD)) and (not cHtf(c) or hOk)
mtfRun() =>
tfS = timeframe.in_seconds()
aNm = vwAnchor == "Auto" ? (tfS <= 3600 ? "Day" : tfS <= 14400 ? "Week" : tfS <= 86400 ? "Month" : "Year") : vwAnchor
aTf = aNm == "Day" ? "D" : aNm == "Week" ? "W" : aNm == "Month" ? "M" : "12M"
[mvw, mvU, mvL] = ta.vwap(vwSrc, timeframe.change(aTf), bandMult)
mUp = ta.highest(high, entryLen)[1]
mDn = ta.lowest(low, entryLen)[1]
mExU = ta.highest(high, exitLen)[1]
mExD = ta.lowest(low, exitLen)[1]
mRecU = nz(ta.barssince(close > mUp), 9999) <= win
mRecD = nz(ta.barssince(close < mDn), 9999) <= win
mMacd = ta.ema(close, fastLen) - ta.ema(close, slowLen)
mT1 = (mMacd - mMacd[1]) * sens
mE1 = 2.0 * bbMult * ta.stdev(close, bbLen)
mTU = mT1 >= 0 ? mT1 : 0.0
mTD = mT1 < 0 ? -mT1 : 0.0
mDead = ta.rma(ta.tr(true), 100) * deadMult
mDL = not useDead or mTU > mDead
mDS = not useDead or mTD > mDead
wLS = mTU > mE1 and mDL
wSS = mTD > mE1 and mDS
wLG = mTU > 0 and mTU > mTU[1] and mDL
wSG = mTD > 0 and mTD > mTD[1] and mDS
[mP, mM, mAdx] = ta.dmi(adxLen, adxLen)
mAThr = math.max(dynFloor, ta.percentile_linear_interpolation(mAdx, dynLen, dynPct))
mRise = mAdx > mAdx[1]
aL = mAdx > mAThr and mRise and mP > mM
aS = mAdx > mAThr and mRise and mM > mP
mVA = ta.sma(volume, volLen)
mRV = mVA > 0 ? volume / mVA : na
mVThr = math.max(1.0, ta.percentile_linear_interpolation(mRV, dynVolLen, dynVolPct))
vS = nz(ta.barssince(mRV > volMult), 9999) <= win
vL = nz(ta.barssince(mRV > mVThr and close > open), 9999) <= win
vH = nz(ta.barssince(mRV > mVThr and close < open), 9999) <= win
hTf = htfSel == "Auto" ? (tfS <= 300 ? "60" : tfS <= 3600 ? "240" : tfS <= 14400 ? "D" : tfS <= 86400 ? "W" : "M") : htfSel == "1H" ? "60" : htfSel == "4H" ? "240" : htfSel == "1D" ? "D" : htfSel == "1W" ? "W" : "M"
hEma = request.security(syminfo.tickerid, hTf, ta.ema(close, htfLen)[1], lookahead=barmerge.lookahead_on)
mAtr = ta.atr(atrLen)
mOk = not waitClose or barstate.isconfirmed
bL = allowL and close > mvw and mRecU and mOk
bS = allowS and close < mvw and mRecD and mOk
hL = close > hEma
hS = close < hEma
var sPos = array.new<int>(NC, 0)
var sEp = array.new<float>(NC, na)
var sSt = array.new<float>(NC, na)
var sN = array.new<int>(NC, 0)
var sGW = array.new<float>(NC, 0.0)
var sGL = array.new<float>(NC, 0.0)
var sCum = array.new<float>(NC, 0.0)
var sPk = array.new<float>(NC, 1.0)
var sEq = array.new<float>(NC, 1.0)
var sDD = array.new<float>(NC, 0.0)
var sSc = array.new<float>(NC, -1e9)
var int act = 0
if filtMode == "Autopilot"
bv = array.max(sSc)
cv = array.get(sSc, act)
if bv > -1e8 and (cv <= -1e8 or bv > cv + math.abs(cv) * switchPct / 100.0)
act := array.indexof(sSc, bv)
else
act := manualIdx
// main system on this timeframe
var int p0 = 0
var float e0 = na
var float s0 = na
var int tN = 0
var int tW = 0
var float gW = 0.0
var float gL = 0.0
var float cmT = 0.0
var float eqT = 1.0
var float pkT = 1.0
var float mdT = 0.0
var int t0m = time
lcA = cond(bL, wLS, wLG, aL, vS, vL, hL, act)
scA = cond(bS, wSS, wSG, aS, vS, vH, hS, act)
int cd0 = 0
float xp0 = close
h0L = p0 == 1 and useAtr and not na(s0) and low <= s0 and mOk
h0S = p0 == -1 and useAtr and not na(s0) and high >= s0 and mOk
if h0L or h0S
cd0 := p0
xp0 := h0L ? math.min(open, s0) : math.max(open, s0)
p0 := 0
else if (p0 == 1 and close < mExD and mOk) or (p0 == -1 and close > mExU and mOk)
cd0 := p0
p0 := 0
l0 = lcA and p0 != 1
n0 = scA and p0 != -1
if l0
if p0 == -1
cd0 := -1
p0 := 1
else if n0
if p0 == 1
cd0 := 1
p0 := -1
if cd0 != 0 and not na(e0)
r0 = cd0 * (xp0 - e0) / e0 * 100 - 2 * fee
tN += 1
if r0 > 0
tW += 1
gW += r0
else
gL -= r0
eqT := math.max(0.0, eqT * (1 + r0 / 100 * posPct / 100))
pkT := math.max(pkT, eqT)
mdT := math.max(mdT, pkT > 0 ? (pkT - eqT) / pkT * 100 : 0.0)
cmT := (eqT - 1) * 100
if l0 or n0
e0 := close
s0 := useAtr ? (l0 ? close - atrMult * mAtr : close + atrMult * mAtr) : na
if p0 == 0
s0 := na
// all combinations on this timeframe (for its own Autopilot)
for c = 0 to NC - 1
lc = cond(bL, wLS, wLG, aL, vS, vL, hL, c)
sc = cond(bS, wSS, wSG, aS, vS, vH, hS, c)
p = array.get(sPos, c)
ep = array.get(sEp, c)
st = array.get(sSt, c)
int cd = 0
float xp = close
hLc = p == 1 and useAtr and not na(st) and low <= st and mOk
hSc = p == -1 and useAtr and not na(st) and high >= st and mOk
if hLc or hSc
cd := p
xp := hLc ? math.min(open, st) : math.max(open, st)
p := 0
else if (p == 1 and close < mExD and mOk) or (p == -1 and close > mExU and mOk)
cd := p
p := 0
ls = lc and p != 1
ss = sc and p != -1
if ls
if p == -1
cd := -1
p := 1
else if ss
if p == 1
cd := 1
p := -1
if cd != 0 and not na(ep)
r = cd * (xp - ep) / ep * 100 - 2 * fee
array.set(sN, c, array.get(sN, c) + 1)
if r > 0
array.set(sGW, c, array.get(sGW, c) + r)
else
array.set(sGL, c, array.get(sGL, c) - r)
eqC = math.max(0.0, array.get(sEq, c) * (1 + r / 100 * posPct / 100))
pk = math.max(array.get(sPk, c), eqC)
cm = (eqC - 1) * 100
array.set(sEq, c, eqC)
array.set(sCum, c, cm)
array.set(sPk, c, pk)
array.set(sDD, c, math.max(array.get(sDD, c), pk > 0 ? (pk - eqC) / pk * 100 : 0.0))
array.set(sSc, c, calcScore(array.get(sN, c), array.get(sGW, c), array.get(sGL, c), cm, array.get(sDD, c)))
if ls or ss
ep := close
st := useAtr ? (ls ? close - atrMult * mAtr : close + atrMult * mAtr) : na
if p == 0
st := na
array.set(sPos, c, p)
array.set(sEp, c, ep)
array.set(sSt, c, st)
pfR = gL > 0 ? gW / gL : gW > 0 ? 99.0 : na
[float(tN), pfR, cmT, mdT, tN > 0 ? tW * 100.0 / tN : na, float(t0m)]
tfNames = array.from("15m", "1H", "4H", "1D")
mN = array.new<float>(4, na)
mPF = array.new<float>(4, na)
mCm = array.new<float>(4, na)
mDd = array.new<float>(4, na)
mWr = array.new<float>(4, na)
mT0 = array.new<float>(4, na)
setTf(int i, float n, float pf, float cm, float dd, float wr, float t) =>
array.set(mN, i, n)
array.set(mPF, i, pf)
array.set(mCm, i, cm)
array.set(mDd, i, dd)
array.set(mWr, i, wr)
array.set(mT0, i, t)
if showMtf
[n1, f1, c1, d1, w1, t1a] = request.security(syminfo.tickerid, "15", mtfRun())
setTf(0, n1, f1, c1, d1, w1, t1a)
[n2, f2, c2, d2, w2, t2a] = request.security(syminfo.tickerid, "60", mtfRun())
setTf(1, n2, f2, c2, d2, w2, t2a)
[n3, f3, c3, d3, w3, t3a] = request.security(syminfo.tickerid, "240", mtfRun())
setTf(2, n3, f3, c3, d3, w3, t3a)
[n4, f4, c4, d4, w4, t4a] = request.security(syminfo.tickerid, "D", mtfRun())
setTf(3, n4, f4, c4, d4, w4, t4a)
tfScore(int i) =>
n = array.get(mN, i)
pf = array.get(mPF, i)
float s = -1e9
if not na(n) and n >= minTr
s := autoMetric == "Profit factor" ? nz(pf, 0) : array.get(mCm, i) / math.max(array.get(mDd, i), 1.0)
s
int bestTf = -1
if showMtf and barstate.islast
float bs = -1e8
for i = 0 to 3
sc = tfScore(i)
if sc > bs
bs := sc
bestTf := i
curTf = tfSec == 900 ? 0 : tfSec == 3600 ? 1 : tfSec == 14400 ? 2 : tfSec == 86400 ? 3 : -1
// ---------------------------------------------------------------------
// Plots
// ---------------------------------------------------------------------
plot(vw, "VWAP", color=close > vw ? cUp : cDn, linewidth=2)
plot(showBands ? vwU : na, "VWAP Upper Band", color=color.new(color.gray, 40))
plot(showBands ? vwL : na, "VWAP Lower Band", color=color.new(color.gray, 40))
plot(fHtf ? htfEma : na, "HTF EMA", color=color.new(color.yellow, 30), linewidth=1, style=plot.style_stepline)
pUp = plot(showChan ? up : na, "Turtle Upper", color=color.new(cUp, 50), style=plot.style_stepline)
pDn = plot(showChan ? dn : na, "Turtle Lower", color=color.new(cDn, 50), style=plot.style_stepline)
fill(pUp, pDn, color=color.new(color.gray, 94), title="Turtle Fill")
chanStop = pos == 1 ? exDn : pos == -1 ? exUp : na
plot(showStop ? chanStop : na, "Channel Stop", color=pos == 1 ? color.orange : color.fuchsia,
style=plot.style_linebr, linewidth=1)
plot(showStop and useAtr ? stopPx : na, "ATR Stop", color=color.new(color.red, 0), style=plot.style_circles, linewidth=1)
plotshape(longSig, "BUY", shape.labelup, location.belowbar, color=cUp, text="BUY", textcolor=color.white, size=size.small)
plotshape(shortSig, "SELL", shape.labeldown, location.abovebar, color=cDn, text="SELL", textcolor=color.white, size=size.small)
// EXIT label hidden when an opposite signal fires on the same bar (BUY/SELL already flips the position)
plotshape(showExit and chL and not hitL and not shortSig, "Long Exit", shape.xcross, location.abovebar, color=color.orange, text="EXIT", textcolor=color.orange, size=size.tiny)
plotshape(showExit and chS and not hitS and not longSig, "Short Exit", shape.xcross, location.belowbar, color=color.fuchsia, text="EXIT", textcolor=color.fuchsia, size=size.tiny)
plotshape(showExit and hitL, "Long Stop", shape.xcross, location.belowbar, color=color.red, text="STOP", textcolor=color.red, size=size.tiny)
plotshape(showExit and hitS, "Short Stop", shape.xcross, location.abovebar, color=color.red, text="STOP", textcolor=color.red, size=size.tiny)
// ---------------------------------------------------------------------
// Table helpers
// ---------------------------------------------------------------------
row(table tbl, int r, string k, string v, color c) =>
table.cell(tbl, 0, r, k, text_color=color.silver, bgcolor=BG, text_size=size.small, text_halign=text.align_left)
table.cell(tbl, 1, r, v, text_color=c, bgcolor=BG, text_size=size.small, text_halign=text.align_right)
cc(table tbl, int col, int r, string txt, color c) =>
table.cell(tbl, col, r, txt, text_color=c, bgcolor=BG, text_size=size.tiny, text_halign=col == 0 ? text.align_left : text.align_right)
fp(float x) =>
na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(x, "#.##") + "%"
fc(float x) =>
na(x) ? color.gray : x >= 0 ? cUp : cDn
posOf(string s) =>
s == "Bottom right" ? position.bottom_right : s == "Bottom left" ? position.bottom_left : s == "Top center" ? position.top_center : position.top_left
// ---------------------------------------------------------------------
// Status table
// ---------------------------------------------------------------------
var table tb = table.new(position.top_right, 2, 12, border_width=1)
if showTable and barstate.islast
adxOkNow = adxDL or adxDS
volThrNow = fVol == 1 ? volMult : volDyn
volOkNow = fVol == 1 ? volRecS : (volRecL or volRecH)
row(tb, 0, "VSP", filtMode + (dirMode == "Both" ? "" : " · " + dirMode), filtMode == "Autopilot" ? color.yellow : color.silver)
row(tb, 1, "VWAP (" + anchorNm + ")", close > vw ? "Above" : "Below", close > vw ? cUp : cDn)
row(tb, 2, "Turtle", recUp ? "Upper breakout" : recDn ? "Lower breakout" : "Inside channel", recUp ? cUp : recDn ? cDn : color.gray)
row(tb, 3, "WAE (" + (fLoose ? "Loose" : "Strict") + ")", (fLoose ? waeLG : waeLS) ? "Confirm ↑" : (fLoose ? waeSG : waeSS) ? "Confirm ↓" : "Weak",
(fLoose ? waeLG : waeLS) ? cUp : (fLoose ? waeSG : waeSS) ? cDn : color.gray)
row(tb, 4, fAdx ? "ADX (Dynamic)" : "ADX",
not fAdx ? "Off" : str.tostring(adxV, "#") + " / thr " + str.tostring(adxDyn, "#") + (adxOkNow ? (diP > diM ? " ↑" : " ↓") : ""),
not fAdx ? color.gray : not adxOkNow ? color.gray : diP > diM ? cUp : cDn)
row(tb, 5, fVol == 2 ? "Volume (Dynamic)" : fVol == 1 ? "Volume (Fixed)" : "Volume",
fVol == 0 ? "Off" : str.tostring(relVol, "#.#") + "× / thr " + str.tostring(volThrNow, "#.#") + (volOkNow ? " ✓" : ""),
fVol == 0 ? color.gray : volOkNow ? cUp : color.gray)
row(tb, 6, "HTF (" + htfNm + ")", not fHtf ? "Off" : htfL ? "Bullish" : "Bearish", not fHtf ? color.gray : htfL ? cUp : cDn)
row(tb, 7, "Position", pos == 1 ? "LONG" : pos == -1 ? "SHORT" : "FLAT", pos == 1 ? cUp : pos == -1 ? cDn : color.gray)
row(tb, 8, "ATR stop", not useAtr ? "Off" : na(stopPx) ? "—" : str.tostring(stopPx, format.mintick), useAtr and not na(stopPx) ? color.red : color.gray)
row(tb, 9, "Active filter", cName(active), color.yellow)
row(tb, 10, "Best TF", not showMtf ? "Off" : bestTf < 0 ? "—" : array.get(tfNames, bestTf) + (curTf == bestTf ? " ✓" : " ⚠ chart is not on it"),
not showMtf or bestTf < 0 ? color.gray : curTf == bestTf ? cUp : color.yellow)
if noVol
row(tb, 11, "⚠ No volume", "VWAP unreliable", color.yellow)
else
table.clear(tb, 0, 11, 1, 11)
// ---------------------------------------------------------------------
// Statistics panel (signals actually produced)
// ---------------------------------------------------------------------
var table ts = table.new(posOf(statPos), 2, 12, border_width=1)
if showStats and barstate.islast
winR = nTr > 0 ? nWin * 100.0 / nTr : na
lR = nL > 0 ? nLW * 100.0 / nL : na
sR = nS > 0 ? nSW * 100.0 / nS : na
pf = grossL > 0 ? grossW / grossL : na
avg = nTr > 0 ? sumR / nTr : na
row(ts, 0, "STATISTICS", str.format_time(t0, "dd.MM.yyyy", syminfo.timezone) + " →", color.silver)
row(ts, 1, "Trades", str.tostring(nTr), color.white)
row(ts, 2, "Win rate", na(winR) ? "—" : str.tostring(winR, "#") + "%", na(winR) ? color.gray : winR >= 50 ? cUp : cDn)
row(ts, 3, "Long", str.tostring(nLW) + "/" + str.tostring(nL) + (na(lR) ? "" : " " + str.tostring(lR, "#") + "%"), color.white)
row(ts, 4, "Short", str.tostring(nSW) + "/" + str.tostring(nS) + (na(sR) ? "" : " " + str.tostring(sR, "#") + "%"), color.white)
row(ts, 5, "Total", fp(nTr > 0 ? cum : na), fc(nTr > 0 ? cum : na))
row(ts, 6, "Avg trade", fp(avg), fc(avg))
row(ts, 7, "Profit factor", na(pf) ? (grossW > 0 ? "∞" : "—") : str.tostring(pf, "#.##"), na(pf) ? color.gray : pf >= 1 ? cUp : cDn)
row(ts, 8, "Max DD", nTr > 0 ? "-" + str.tostring(maxDD, "#.##") + "%" : "—", nTr > 0 ? cDn : color.gray)
row(ts, 9, "Best / worst", fp(best) + " / " + fp(worst), color.white)
row(ts, 10, "ATR stop exits", useAtr ? str.tostring(nStop) : "Off", color.white)
row(ts, 11, "Open trade", fp(openRet), fc(openRet))
// ---------------------------------------------------------------------
// Filter comparison table (24 combinations, sorted by metric)
// ---------------------------------------------------------------------
var table tc = table.new(posOf(cmpPos), 6, NC + 2, border_width=1)
if showCmp and barstate.islast
cc(tc, 0, 0, "COMPARISON", color.white)
cc(tc, 1, 0, "", color.white)
cc(tc, 2, 0, "", color.white)
cc(tc, 3, 0, "", color.white)
cc(tc, 4, 0, "sort: " + (autoMetric == "Profit factor" ? "PF" : "R/DD"), color.silver)
cc(tc, 5, 0, "min " + str.tostring(minTr), color.silver)
cc(tc, 0, 1, "Filter", color.silver)
cc(tc, 1, 1, "Trades", color.silver)
cc(tc, 2, 1, "Win", color.silver)
cc(tc, 3, 1, "PF", color.silver)
cc(tc, 4, 1, "Total", color.silver)
cc(tc, 5, 1, "DD", color.silver)
idx = array.sort_indices(aSc, order.descending)
for i = 0 to cmpRows - 1
c = array.get(idx, i)
n = array.get(aN, c)
gw = array.get(aGW, c)
gl = array.get(aGL, c)
cm = array.get(aCum, c)
dd = array.get(aDD, c)
qual = n >= minTr
isAc = c == active
txtC = isAc ? color.yellow : qual ? color.white : color.gray
pfV = gl > 0 ? gw / gl : n > 0 ? 99.0 : na
cc(tc, 0, i + 2, (isAc ? "▶ " : "") + cName(c), txtC)
cc(tc, 1, i + 2, str.tostring(n), txtC)
cc(tc, 2, i + 2, n > 0 ? str.tostring(array.get(aW, c) * 100.0 / n, "#") + "%" : "—", txtC)
cc(tc, 3, i + 2, na(pfV) ? "—" : pfV >= 99 ? "∞" : str.tostring(pfV, "#.##"), na(pfV) or not qual ? color.gray : pfV >= 1 ? cUp : cDn)
cc(tc, 4, i + 2, n > 0 ? fp(cm) : "—", n > 0 and qual ? fc(cm) : color.gray)
cc(tc, 5, i + 2, n > 0 ? "-" + str.tostring(dd, "#.#") + "%" : "—", n > 0 and qual ? cDn : color.gray)
if cmpRows < NC
table.clear(tc, 0, cmpRows + 2, 5, NC + 1)
// ---------------------------------------------------------------------
// Timeframe summary table
// ---------------------------------------------------------------------
var table tt = table.new(posOf(mtfPos), 7, 6, border_width=1)
if showMtf and barstate.islast
cc(tt, 0, 0, "TIMEFRAMES", color.white)
for k = 1 to 5
cc(tt, k, 0, "", color.white)
cc(tt, 6, 0, "★ = best", color.silver)
cc(tt, 0, 1, "TF", color.silver)
cc(tt, 1, 1, "Since", color.silver)
cc(tt, 2, 1, "Trades", color.silver)
cc(tt, 3, 1, "Win", color.silver)
cc(tt, 4, 1, "PF", color.silver)
cc(tt, 5, 1, "Total", color.silver)
cc(tt, 6, 1, "DD", color.silver)
for i = 0 to 3
n = array.get(mN, i)
pf = array.get(mPF, i)
cm = array.get(mCm, i)
dd = array.get(mDd, i)
wr = array.get(mWr, i)
t = array.get(mT0, i)
has = not na(n) and n > 0
qual = has and n >= minTr
isB = i == bestTf
txtC = isB ? color.yellow : qual ? color.white : color.gray
cc(tt, 0, i + 2, (isB ? "★ " : "") + array.get(tfNames, i) + (i == curTf ? " ◀" : ""), txtC)
cc(tt, 1, i + 2, na(t) ? "—" : str.format_time(int(t), "MM.yyyy", syminfo.timezone), color.gray)
cc(tt, 2, i + 2, na(n) ? "—" : str.tostring(n, "#"), txtC)
cc(tt, 3, i + 2, has ? str.tostring(wr, "#") + "%" : "—", txtC)
cc(tt, 4, i + 2, not has or na(pf) ? "—" : pf >= 99 ? "∞" : str.tostring(pf, "#.##"), not qual or na(pf) ? color.gray : pf >= 1 ? cUp : cDn)
cc(tt, 5, i + 2, has ? fp(cm) : "—", qual ? fc(cm) : color.gray)
cc(tt, 6, i + 2, has ? "-" + str.tostring(dd, "#.#") + "%" : "—", qual ? cDn : color.gray)
// ---------------------------------------------------------------------
// Alerts
// ---------------------------------------------------------------------
alertcondition(longSig, "BUY", "VSP: BUY — {{ticker}} {{interval}} @ {{close}}")
alertcondition(shortSig, "SELL", "VSP: SELL — {{ticker}} {{interval}} @ {{close}}")
alertcondition(longExit, "Long Exit", "VSP: Long exit/stop — {{ticker}} @ {{close}}")
alertcondition(shortExit, "Short Exit", "VSP: Short exit/stop — {{ticker}} @ {{close}}")