Candlestick ATS - Power and Trend Tracker

onderarslantas107 · study · 995 行 · 点赞 58 · TradingView 原页

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

Pine Script

//@version=6
indicator("ATS POWER V4 | TREND TRAIL + DUAL LAB", shorttitle="ATS V4 GEZEN", overlay=true, dynamic_requests=true, max_boxes_count=450, max_lines_count=450, max_labels_count=450)
 
// Kapanis onayli ATS + bagimsiz GEZEN renk laboratuvari.
// Renk bonusu ortalama alinmadan dogrudan +10 olarak eklenir.
// TP1 ve TP2 kontrol noktalaridir; ATS trend stopu ve ters guc cikis icindir.
// Gercek emir gondermez.
 
//━━━━━━━━━━━━━━━━ CORE
g1 = "1 | Core / Cekirdek"
lang = input.string("TR", "Language", options=["EN", "TR", "DE", "FR", "ES", "PT", "RU", "AR", "JA", "ZH"], group=g1)
trendLen = input.int(55, "Organ Trend EMA", minval=2, group=g1)
momLen = input.int(10, "Organ Momentum", minval=1, group=g1)
zLen = input.int(34, "Z Lookback", minval=2, group=g1)
smoothLen = input.int(8, "Organ Smooth", minval=1, group=g1)
matcPct = input.float(2.0, "MATC Band %", minval=0.1, maxval=50, step=0.1, group=g1)
matcSmooth = input.int(5, "MATC Smooth", minval=1, group=g1)
matcMirror = input.float(1.3, "MATC Mirror", minval=0.1, step=0.1, group=g1)
atrLen = input.int(14, "ATR Length", minval=1, group=g1)
atrMult = input.float(2.4, "Trend Line ATR", minval=0.1, step=0.1, group=g1)
 
//━━━━━━━━━━━━━━━━ MTF / PVM
g2 = "2 | MTF / PVM"
useMtf = input.bool(true, "Use MTF Power", group=g2)
tf1 = input.string("15", "Fast TF", options=["1", "5", "15", "30", "60", "120", "240", "1D", "1W", "1M"], group=g2)
tf2 = input.string("60", "Mid TF", options=["1", "5", "15", "30", "60", "120", "240", "1D", "1W", "1M"], group=g2)
tf3 = input.string("240", "Macro TF", options=["1", "5", "15", "30", "60", "120", "240", "1D", "1W", "1M"], group=g2)
usePvmBoost = input.bool(true, "Use Directional PVM", group=g2)
pvmWeight = input.float(0.25, "PVM Weight (tek uygulama)", minval=0, maxval=0.60, step=0.05, group=g2)
 
//━━━━━━━━━━━━━━━━ THRESHOLDS
g3 = "3 | Thresholds / Esikler"
bullTh = input.float(60, "BUY Power Level", minval=50.1, maxval=99.9, group=g3)
bearTh = input.float(40, "SELL Power Level", minval=0.1, maxval=49.9, group=g3)
strongTh = input.float(75, "Strong Direction Level", minval=50.2, maxval=100, group=g3)
normalTh = input.float(60, "Normal Direction Level", minval=50.1, maxval=99.9, group=g3)
weakTh = input.float(45, "Fading Direction Level", minval=0, maxval=99, group=g3)
 
//━━━━━━━━━━━━━━━━ TRADE PLAN
g4 = "4 | Virtual Plan / Sanal Islem"
tradeMode = input.string("LONG + SHORT", "Islem yonu", options=["LONG + SHORT", "LONG", "SHORT"], group=g4)
stopMode = input.string("ATR", "Stop hesabi", options=["ATR", "YUZDE"], group=g4)
stopAtr = input.float(2.0, "Stop ATR carpani", minval=0.1, step=0.1, group=g4)
stopPct = input.float(0.50, "Stop (%)", minval=0.01, maxval=95, step=0.05, group=g4)
targetMode = input.string("RISK/KAZANC", "Hedef hesabi", options=["RISK/KAZANC", "YUZDE"], group=g4)
targetRR = input.float(1.5, "TP1 risk/kazanc", minval=0.1, step=0.1, group=g4)
targetPct = input.float(0.75, "TP1 (%)", minval=0.01, maxval=95, step=0.05, group=g4)
tp2Mult = input.float(2.0, "TP2 / TP1 mesafe carpani", minval=1.05, step=0.1, group=g4)
continuePower = input.float(60, "Guc uyari esigi (cikis yapmaz)", minval=50.1, maxval=100, group=g4)
breakEven = input.bool(true, "TP1 sonrasi stop girise (sonraki mum)", group=g4)
closeOnOpposite = input.bool(true, "Ters guc cikisi (1 kapanmis mum)", group=g4)
flipNextBar = input.bool(true, "Ters cikis sonrasi yeni yonde gir (sonraki kapanis)", group=g4)
oppositeBull = input.float(60, "SHORT kapat: ATS yukari guc", minval=50.1, maxval=100, group=g4)
oppositeBear = input.float(40, "LONG kapat: ATS asagi guc", minval=0, maxval=49.9, group=g4)
feeSide = input.float(0, "Tek yon komisyon (%)", minval=0, step=0.01, group=g4)
slipTicks = input.int(0, "Tek yon kayma (tick)", minval=0, group=g4)
 
//━━━━━━━━━━━━━━━━ VIEW
g5 = "5 | View / Gorunum"
showAura = input.bool(true, "Aura", group=g5)
showSignals = input.bool(true, "BUY / SELL / TP / STOP", group=g5)
showBars = input.bool(true, "Candle Color", group=g5)
showPanel = input.bool(true, "Mini Panel", group=g5)
showStar = input.bool(false, "Power Star", group=g5)
showBadge = input.bool(false, "Power Badge", group=g5)
showPlans = input.bool(true, "Islem kutulari", group=g5)
showLevels = input.bool(true, "Plan giris / hedef / stop seviyeleri", group=g5)
keepPlans = input.int(3, "Gecmisteki plan sayisi", minval=1, maxval=15, group=g5)
showPastPlans = input.bool(false, "Gecmis plan kutularini koru", group=g5)
planForward = input.int(6, "Plan seviyelerini saga uzat (bar)", minval=1, maxval=20, group=g5)
dynamicAlerts = input.bool(true, "Ayrintili alert() mesajlari", group=g5)
bullC = input.color(color.lime, "Bull Color", group=g5)
bearC = input.color(color.red, "Bear Color", group=g5)
midC = input.color(color.gray, "Neutral Color", group=g5)
goldC = input.color(color.yellow, "Power Color", group=g5)
 
//━━━━━━━━━━━━━━━━ GEZEN LAB
gLab = "6 | GEZEN 13 renk laboratuvari"
useLab = input.bool(true, "Renk basarisiyla +10 puan bonus", group=gLab)
renkoLen = input.int(14, "Renko ATR", minval=1, group=gLab)
kagiTicks = input.int(30, "Kagi donus tick", minval=1, group=gLab)
pnfLen = input.int(14, "PnF ATR", minval=1, group=gLab)
pnfRev = input.int(3, "PnF donus kutusu", minval=1, group=gLab)
rangeLen = input.int(14, "Aralik ATR", minval=1, group=gLab)
rangeMult = input.float(0.8, "Aralik ATR katsayisi", minval=0.05, step=0.05, group=gLab)
labTP = input.float(0.50, "Bagimsiz LAB TP (%)", minval=0.01, step=0.05, group=gLab)
labSL = input.float(0.50, "Bagimsiz LAB SL (%)", minval=0.01, maxval=95, step=0.05, group=gLab)
labHorizon = input.int(30, "LAB azami sure (bar)", minval=2, maxval=100, group=gLab)
labWindow = input.int(30, "Her renkte son kapanmis ornek", minval=8, maxval=100, group=gLab)
labMinSamples = input.int(8, "Asgari ornek", minval=1, maxval=100, group=gLab)
labThreshold = input.float(65, "Renk basarisi bu yuzdenin UZERINDE", minval=1, maxval=99, group=gLab)
labWarmup = input.int(200, "LAB isinma (bar)", minval=0, group=gLab)
showLabColors = input.bool(true, "GEZEN kombinasyonlarini mumda renklendir", group=gLab)
showBonusZones = input.bool(true, "Bonus LONG / SHORT bolgesi + etiket", group=gLab)
bonusKeep = input.int(25, "Gecmisteki bonus bolgesi", minval=1, maxval=80, group=gLab)
 
//━━━━━━━━━━━━━━━━ COLORS
gColors = "7 | GEZEN dizilim renkleri"
col01 = input.color(#00C853, "01 HA>AR>RK", group=gColors)
col02 = input.color(#FFD600, "02 HA>RK>AR", group=gColors)
col03 = input.color(#2962FF, "03 AR>HA>RK", group=gColors)
col04 = input.color(#FF6D00, "04 AR>RK>HA", group=gColors)
col05 = input.color(#AA00FF, "05 RK>HA>AR", group=gColors)
col06 = input.color(#00B8D4, "06 RK>AR>HA", group=gColors)
col07 = input.color(#F50057, "07 HA=AR>RK", group=gColors)
col08 = input.color(#AEEA00, "08 HA=RK>AR", group=gColors)
col09 = input.color(#8D6E63, "09 AR=RK>HA", group=gColors)
col10 = input.color(#FF80AB, "10 RK>HA=AR", group=gColors)
col11 = input.color(#90A4AE, "11 AR>HA=RK", group=gColors)
col12 = input.color(#7C4DFF, "12 HA>AR=RK", group=gColors)
col13 = input.color(#F5F5F5, "13 HA=AR=RK", group=gColors)
 
//━━━━━━━━━━━━━━━━ SCREENER
gScan = "8 | Pine Screener / Tarama"
scanMode = input.string("GUC", "Tarama kosulu", options=["GUC", "YENI ISLEM", "BONUSLU LONG", "BONUSLU SHORT"], group=gScan)
scanPower = input.float(65, "Tarama asgari YON gucu", minval=50.1, maxval=100, group=gScan)
scanOnlyBonus = input.bool(false, "GUC taramasinda aktif bonus da gerekli", group=gScan)
 
if barstate.isfirst
    if not chart.is_standard or timeframe.isticks
        runtime.error("Standart, zaman tabanli mum/cubuk grafigi secin.")
    if not (weakTh < normalTh and normalTh < strongTh)
        runtime.error("Esikler: Fading < Normal < Strong olmali.")
    if labMinSamples > labWindow
        runtime.error("LAB asgari ornek pencere sayisindan buyuk olamaz.")
 
//━━━━━━━━━━━━━━━━ HELPERS
t(string en, string tr) =>
    lang == "TR" ? tr : en
 
f_clamp(float value, float lo, float hi) =>
    math.max(lo, math.min(hi, value))
 
f_z(float src, int length) =>
    float mean = ta.sma(src, length)
    float dev = ta.stdev(src, length)
    not na(src) and not na(mean) and not na(dev) ? (dev > 0 ? (src - mean) / dev : 0.0) : na
 
f_pvm_value(float trend, float momentum, float flow, bool volumeOK, float intensity) =>
    float denominator = volumeOK ? 1.0 : 0.65
    float direction = (0.40 * trend + 0.25 * momentum + (volumeOK ? 0.35 * flow : 0.0)) / denominator
    50.0 + 50.0 * f_clamp(direction * (1.0 + 0.5 * intensity), -1.0, 1.0)
 
f_mix(float score, float pvm) =>
    usePvmBoost and pvmWeight > 0 ? score * (1.0 - pvmWeight) + pvm * pvmWeight : score
 
//━━━━━━━━━━━━━━━━ ATS ENGINE
f_engine() =>
    float emaTrend = ta.ema(close, trendLen)
    float trendRaw = ta.change(emaTrend)
    float momRaw = ta.roc(close, momLen)
    float atrLocal = ta.atr(atrLen)
    float ema20 = ta.ema(close, 20)
    float priceDirection = close > ema20 ? 1.0 : close < ema20 ? -1.0 : 0.0
    float atrRaw = ta.change(atrLocal) * priceDirection
 
    float change = ta.change(close)
    float signedVolume = not na(volume) and not na(change) ? math.sign(change) * volume : na
    float volumeBase = ta.ema(volume, 34)
    float volumeSeen = ta.lowest(na(volume) or volume < 0 ? 0.0 : 1.0, zLen)
    bool volumeOK = bar_index >= math.max(zLen, 34) and volumeSeen == 1 and not na(volumeBase) and volumeBase > 0
 
    float trendZ = f_z(trendRaw, zLen)
    float momZ = f_z(momRaw, zLen)
    float obvZ = f_z(signedVolume, zLen)
    float atrZ = f_z(atrRaw, zLen)
 
    float organRaw = (trendZ * 2.0 + momZ * 1.5 + atrZ * 0.5 + (volumeOK ? obvZ : 0.0)) * (volumeOK ? 1.0 : 1.25)
    float organ = ta.ema(organRaw, smoothLen)
    float organPct = f_clamp(organ / 6.0 * 50.0 + 50.0, 0.0, 100.0)
 
    float src = hl2
    float dist = src * matcPct / 100.0
    float resist = ta.ema(src + dist * matcMirror, matcSmooth)
    float support = ta.ema(src - dist * matcMirror, matcSmooth)
    float matcMid = (resist + support) / 2.0
    float matcRange = math.max(resist - support, syminfo.mintick)
    float matcScore = f_clamp((close - matcMid) / matcRange * 50.0 + 50.0, 0.0, 100.0)
 
    float emaFast = ta.ema(close, 21)
    float emaSlow = ta.ema(close, 55)
    float ribbon = emaFast > emaSlow ? 65.0 : emaFast < emaSlow ? 35.0 : 50.0
 
    float rsi = ta.rsi(close, 14)
    float rsiScore = bar_index >= 14 ? nz(rsi, 50.0) : na
 
    int warmup = math.max(55, math.max(trendLen, math.max(zLen + momLen, atrLen + zLen))) + smoothLen
    bool coreReady = bar_index >= warmup and not na(organRaw) and not na(organ) and not na(matcScore) and not na(rsiScore)
 
    float score = coreReady ? organPct * 0.40 + matcScore * 0.25 + ribbon * 0.20 + rsiScore * 0.15 : na
 
    float atr14 = ta.atr(14)
    float atrBase = ta.ema(atr14, 34)
    float safeAtr = math.max(atr14, syminfo.mintick)
    float trendDirection = f_clamp((emaFast - emaSlow) / safeAtr, -1.0, 1.0)
    float momentumDirection = f_clamp((close - close[14]) / (safeAtr * math.sqrt(14.0)), -1.0, 1.0)
 
    float flowMean = ta.ema(signedVolume, 34)
    float flow = volumeOK ? f_clamp(flowMean / volumeBase, -1.0, 1.0) : 0.0
 
    float expansion = atr14 / math.max(atrBase, syminfo.mintick)
    float relVolume = volumeOK ? volume / volumeBase : 1.0
    float atrIntensity = f_clamp(expansion - 1.0, 0.0, 1.0)
    float volIntensity = f_clamp(relVolume - 1.0, 0.0, 1.0)
    float intensity = volumeOK ? (atrIntensity + volIntensity) / 2.0 : atrIntensity
 
    float pvmRaw = f_pvm_value(trendDirection, momentumDirection, flow, volumeOK, intensity)
    float pvmSmooth = ta.ema(pvmRaw, 9)
    float pvm = coreReady and not na(pvmRaw) ? pvmSmooth : na
 
    [score, pvm, volumeOK]
 
//━━━━━━━━━━━━━━━━ MTF
f_previous_engine() =>
    [score, pvm, vol] = f_engine()
    [score[1], pvm[1], vol[1]]
 
f_timed_engine() =>
    [score, pvm, vol] = f_engine()
    [score, pvm, vol, time_close]
 
f_tf(simple string tf, float localScore, float localPvm, bool localVolume) =>
    if timeframe.in_seconds(tf) == timeframe.in_seconds()
        [localScore, localPvm, localVolume]
    else if timeframe.in_seconds(tf) > timeframe.in_seconds()
        request.security(syminfo.tickerid, tf, f_previous_engine(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
    else
        [scores, pvms, volumes, ends] = request.security_lower_tf(syminfo.tickerid, tf, f_timed_engine())
        int index = array.size(scores) - 1
 
        while index >= 0
            int endTime = array.get(ends, index)
            if not na(endTime) and endTime <= time_close
                break
            index -= 1
 
        float score = index >= 0 ? array.get(scores, index) : na
        float pvm = index >= 0 ? array.get(pvms, index) : na
        bool vol = index >= 0 ? array.get(volumes, index) : false
 
        [score, pvm, vol]
 
[baseScore, basePvm, localVolume] = f_engine()
 
float s1 = baseScore
float s2 = baseScore
float s3 = baseScore
float p1 = basePvm
float p2 = basePvm
float p3 = basePvm
bool v1 = localVolume
bool v2 = localVolume
bool v3 = localVolume
 
if useMtf
    [a, b, v] = f_tf(tf1, baseScore, basePvm, localVolume)
    [d, e, w] = f_tf(tf2, baseScore, basePvm, localVolume)
    [f, g, x] = f_tf(tf3, baseScore, basePvm, localVolume)
 
    s1 := a
    p1 := b
    v1 := v
    s2 := d
    p2 := e
    v2 := w
    s3 := f
    p3 := g
    v3 := x
 
float localPower = f_mix(baseScore, basePvm)
float tf1Power = f_mix(s1, p1)
float tf2Power = f_mix(s2, p2)
float tf3Power = f_mix(s3, p3)
 
float rawScore = useMtf ? baseScore * 0.45 + (s1 * 0.30 + s2 * 0.35 + s3 * 0.35) * 0.55 : baseScore
float rawPvm = useMtf ? basePvm * 0.45 + (p1 * 0.30 + p2 * 0.35 + p3 * 0.35) * 0.55 : basePvm
 
float calculatedPower = f_clamp(f_mix(rawScore, rawPvm), 0.0, 100.0)
float calculatedAverage = useMtf ? (localPower + tf1Power + tf2Power + tf3Power) / 4.0 : localPower
bool ready = not na(calculatedPower) and not na(calculatedAverage)
 
float atr = ta.atr(atrLen)
float basis = ta.ema(close, 34)
float bullBase = math.min(basis - atr * atrMult, close - syminfo.mintick)
float bearBase = math.max(basis + atr * atrMult, close + syminfo.mintick)
bool pricesOK = not na(open) and not na(high) and not na(low) and not na(close) and close > syminfo.mintick
 
var float powerPct = na
var float avgPower = na
var float pvmPower = na
var bool publishedReady = false
var int cascade = 0
var bool publishedVolume = false
var int trendDir = 0
var float trendLine = na
 
f_follow(int oldDir, float oldLine, float power, float lower, float upper) =>
    int direction = power >= bullTh ? 1 : power <= bearTh ? -1 : oldDir
    float level = oldLine
 
    if direction != oldDir
        level := direction == 1 ? lower : upper
    else if direction == 1
        level := math.max(nz(oldLine, lower), lower)
    else if direction == -1
        level := math.min(nz(oldLine, upper), upper)
 
    [direction, level]
 
//━━━━━━━━━━━━━━━━ TRADE HELPERS
f_stop(int side, float entry, float currentAtr) =>
    float distance = stopMode == "ATR" ? currentAtr * stopAtr : entry * stopPct / 100.0
    float raw = math.round_to_mintick(entry - side * distance)
    side == 1 ? math.max(syminfo.mintick, math.min(math.round_to_mintick(entry - syminfo.mintick), raw)) : math.max(math.round_to_mintick(entry + syminfo.mintick), raw)
 
f_target(int side, float entry, float stop) =>
    float distance = targetMode == "RISK/KAZANC" ? math.abs(entry - stop) * targetRR : entry * targetPct / 100.0
    float requested = entry + side * distance
    float raw = math.round_to_mintick(requested)
    side == 1 ? math.max(math.round_to_mintick(entry + syminfo.mintick), raw) : requested < syminfo.mintick ? na : math.max(syminfo.mintick, math.min(math.round_to_mintick(entry - syminfo.mintick), raw))
 
f_outcome(int side, float stop, float target) =>
    int reason = 0
    float fillPrice = na
 
    if side == 1
        if open <= stop
            reason := 2
            fillPrice := open
        else if open >= target
            reason := 1
            fillPrice := open
        else if low <= stop
            reason := 2
            fillPrice := stop
        else if high >= target
            reason := 1
            fillPrice := target
    else if side == -1
        if open >= stop
            reason := 2
            fillPrice := open
        else if open <= target
            reason := 1
            fillPrice := open
        else if high >= stop
            reason := 2
            fillPrice := stop
        else if low <= target
            reason := 1
            fillPrice := target
 
    [reason, fillPrice]
 
f_net(int side, float entry, float exitPrice) =>
    100.0 * side * (exitPrice / entry - 1.0) - 2.0 * feeSide - 200.0 * slipTicks * syminfo.mintick / entry
 
var array<int> counts = array.new_int(3, 0)
var array<int> wins = array.new_int(3, 0)
var array<float> netSum = array.new_float(3, 0)
var array<float> equity = array.new_float(3, 100)
 
f_record(int id, float result) =>
    array.set(counts, id, array.get(counts, id) + 1)
    array.set(wins, id, array.get(wins, id) + (result > 0 ? 1 : 0))
    array.set(netSum, id, array.get(netSum, id) + result)
    array.set(equity, id, math.max(0.0, array.get(equity, id) * (1.0 + result / 100.0)))
 
//━━━━━━━━━━━━━━━━ GEZEN LAB
var array<string> labNames = array.from("HA>AR>RK", "HA>RK>AR", "AR>HA>RK", "AR>RK>HA", "RK>HA>AR", "RK>AR>HA", "HA=AR>RK", "HA=RK>AR", "AR=RK>HA", "RK>HA=AR", "AR>HA=RK", "HA>AR=RK", "HA=AR=RK")
var array<color> labPalette = array.from(col01, col02, col03, col04, col05, col06, col07, col08, col09, col10, col11, col12, col13)
 
f_lab_color(int cat) =>
    cat >= 0 and cat < 13 ? array.get(labPalette, cat) : midC
 
f_dir(float op, float cl) =>
    na(op) or na(cl) ? 0 : cl > op ? 1 : cl < op ? -1 : 0
 
f_category(int a, int b, int r) =>
    int result = 12
 
    if a == b and b == r
        result := 12
    else if a == b
        result := a < r ? 6 : 9
    else if a == r
        result := a < b ? 7 : 10
    else if b == r
        result := b < a ? 8 : 11
    else if a < b and b < r
        result := 0
    else if a < r and r < b
        result := 1
    else if b < a and a < r
        result := 2
    else if b < r and r < a
        result := 3
    else if r < a and a < b
        result := 4
    else
        result := 5
 
    result
 
f_eligible(int sampleCount, int winCount) =>
    sampleCount >= labMinSamples and 100.0 * winCount > labThreshold * sampleCount
 
f_bonus(int lastBar, int nowBar) =>
    na(lastBar) ? 0 : int(math.max(0, math.min(10, 10 - (nowBar - lastBar))))
 
f_lab() =>
    string base = ticker.standard(syminfo.tickerid)
 
    [ho, hc] = request.security(ticker.heikinashi(base), timeframe.period, [open, close], lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
    [ko, kc] = request.security(ticker.kagi(base, syminfo.mintick * kagiTicks), timeframe.period, [open, close], lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
    [ro, rc] = request.security(ticker.renko(base, "ATR", renkoLen), timeframe.period, [open, close], lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
    [po, pc] = request.security(ticker.pointfigure(base, "hl", "ATR", pnfLen, pnfRev), timeframe.period, [open, close], lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
 
    int ha = f_dir(ho, hc)
    int kg = f_dir(ko, kc)
    int rk = f_dir(ro, rc)
    int pf = f_dir(po, pc)
    float rangeAtr = ta.atr(rangeLen)
    float step = math.max(nz(rangeAtr, syminfo.mintick) * rangeMult, syminfo.mintick)
 
    var float anchor = na
    var int ar = 0
    var int tHAUp = na
    var int tARUp = na
    var int tRKUp = na
    var int tHADn = na
    var int tARDn = na
    var int tRKDn = na
 
    if barstate.isconfirmed and not na(close)
        if na(anchor)
            anchor := close
        else
            float move = close - anchor
            if move >= step
                anchor += math.floor(move / step) * step
                ar := 1
            else if move <= -step
                anchor -= math.floor(-move / step) * step
                ar := -1
 
        tHAUp := ha == 1 ? (na(tHAUp) ? bar_index : tHAUp) : na
        tARUp := ar == 1 ? (na(tARUp) ? bar_index : tARUp) : na
        tRKUp := rk == 1 ? (na(tRKUp) ? bar_index : tRKUp) : na
        tHADn := ha == -1 ? (na(tHADn) ? bar_index : tHADn) : na
        tARDn := ar == -1 ? (na(tARDn) ? bar_index : tARDn) : na
        tRKDn := rk == -1 ? (na(tRKDn) ? bar_index : tRKDn) : na
 
    int mask = (ha == 1 ? 1 : 0) + (kg == 1 ? 2 : 0) + (ar == 1 ? 4 : 0) + (rk == 1 ? 8 : 0) + (pf == 1 ? 16 : 0)
    bool dataReady = not na(rangeAtr) and not na(ho) and not na(hc) and not na(ko) and not na(kc) and not na(ro) and not na(rc) and not na(po) and not na(pc)
 
    // Orijinal LONG mask=13; SHORT bunun aynadaki karsiligi mask=18.
    int side = dataReady and mask == 13 ? 1 : dataReady and mask == 18 ? -1 : 0
    int cat = side == 1 and not na(tHAUp) and not na(tARUp) and not na(tRKUp) ? f_category(tHAUp, tARUp, tRKUp) : side == -1 and not na(tHADn) and not na(tARDn) and not na(tRKDn) ? f_category(tHADn, tARDn, tRKDn) : -1
    bool fresh = cat >= 0 and mask != nz(mask[1], 0)
 
    // Yonlerin verileri ASLA karistirilmaz. 0..12 LONG, 13..25 SHORT.
    var array<int> samples = array.new_int(26, 0)
    var array<int> won = array.new_int(26, 0)
    var array<int> heads = array.new_int(26, 0)
    var array<int> history = array.new_int(26 * labWindow, 0)
    var array<bool> active = array.new_bool(26, false)
    var array<float> entries = array.new_float(26, na)
    var array<int> born = array.new_int(26, -1)
 
    int bucket = cat >= 0 ? cat + (side == -1 ? 13 : 0) : -1
    int n = bucket >= 0 ? array.get(samples, bucket) : 0
    int win = bucket >= 0 ? array.get(won, bucket) : 0
    float rate = n > 0 ? 100.0 * win / n : na
    bool qualified = fresh and f_eligible(n, win) and bar_index >= labWarmup
 
    if barstate.isconfirmed and not na(open) and not na(high) and not na(low) and not na(close) and close > syminfo.mintick
        for i = 0 to 25
            if array.get(active, i) and bar_index > array.get(born, i)
                float ep = array.get(entries, i)
                int labSide = i < 13 ? 1 : -1
                float stopRaw = math.round_to_mintick(ep * (1.0 - labSide * labSL / 100.0))
                float goalRaw = math.round_to_mintick(ep * (1.0 + labSide * labTP / 100.0))
                float stop = labSide == 1 ? math.max(syminfo.mintick, math.min(ep - syminfo.mintick, stopRaw)) : math.max(ep + syminfo.mintick, stopRaw)
                float goal = labSide == 1 ? math.max(ep + syminfo.mintick, goalRaw) : math.max(syminfo.mintick, math.min(ep - syminfo.mintick, goalRaw))
 
                [why, fill] = f_outcome(labSide, stop, goal)
                if why == 0 and bar_index - array.get(born, i) >= labHorizon
                    why := 3
                    fill := close
 
                if why > 0
                    int result = f_net(labSide, ep, fill) > 0 ? 1 : 0
                    int count = array.get(samples, i)
                    int head = array.get(heads, i)
                    int slot = i * labWindow + head
                    int previous = count >= labWindow ? array.get(history, slot) : 0
                    array.set(won, i, array.get(won, i) - previous + result)
                    array.set(samples, i, math.min(count + 1, labWindow))
                    array.set(history, slot, result)
                    array.set(heads, i, (head + 1) % labWindow)
                    array.set(active, i, false)
 
        if fresh and bucket >= 0 and bar_index >= labWarmup and not array.get(active, bucket)
            array.set(active, bucket, true)
            array.set(entries, bucket, close)
            array.set(born, bucket, bar_index)
 
    [side, cat, qualified, rate, n]
 
int currentLabSide = 0
int currentLabCat = -1
bool qualifiedColor = false
float currentLabRate = na
int currentLabSamples = 0
 
if useLab
    [side, cat, qualifies, rate, n] = f_lab()
    currentLabSide := side
    currentLabCat := cat
    qualifiedColor := qualifies
    currentLabRate := rate
    currentLabSamples := n
 
f_target2(int side, float entry, float tp1) =>
    float requested = entry + side * math.abs(tp1 - entry) * tp2Mult
    float rounded = math.round_to_mintick(requested)
    side == 1 ? math.max(math.round_to_mintick(tp1 + syminfo.mintick), rounded) : requested < syminfo.mintick or tp1 <= syminfo.mintick ? na : math.min(math.round_to_mintick(tp1 - syminfo.mintick), rounded)
 
//━━━━━━━━━━━━━━━━ PLAN STATE
var int position = 0
var int planSide = 0
var float entryPrice = na
var float initialStop = na
var float stopPrice = na
var float targetPrice = na
var float target2Price = na
var bool tp1Done = false
var bool tp2Done = false
var int entryBar = -1
var int planNumber = 0
var int rejectedPlans = 0
var int pendingSide = 0
var int pendingBar = -1
 
var float basePowerPct = na
var int lastBonusBar = na
var int bonusPoints = 0
var int bonusSide = 0
var int bonusCat = -1
var float bonusRate = na
var int bonusSamples = 0
 
bool wasOpen = position != 0
bool buySignal = false
bool sellSignal = false
bool tp1Signal = false
bool tp2Signal = false
bool slSignal = false
bool beSignal = false
bool trailExitSignal = false
bool oppositeSignal = false
bool strongBullEvent = false
bool strongBearEvent = false
bool bonusEvent = false
bool bonusLongEvent = false
bool bonusShortEvent = false
bool weakPowerWarning = false
float exitPrice = na
float exitNet = na
 
//━━━━━━━━━━━━━━━━ MAIN ENGINE
if barstate.isconfirmed
    publishedReady := ready
    bonusPoints := useLab ? f_bonus(lastBonusBar, bar_index) : 0
 
    if useLab and ready and qualifiedColor and bonusPoints == 0
        lastBonusBar := bar_index
        bonusPoints := 10
        bonusSide := currentLabSide
        bonusCat := currentLabCat
        bonusRate := currentLabRate
        bonusSamples := currentLabSamples
        bonusEvent := true
 
    if ready
        bool wasStrongBull = not na(powerPct) and powerPct >= strongTh
        bool wasStrongBear = not na(powerPct) and powerPct <= 100.0 - strongTh
        basePowerPct := calculatedPower
        // LONG: +10. SHORT: -10. Her iki durumda da YON gucune +10.
        powerPct := f_clamp(basePowerPct + bonusSide * bonusPoints, 0.0, 100.0)
        avgPower := calculatedAverage
        pvmPower := rawPvm
        strongBullEvent := powerPct >= strongTh and not wasStrongBull
        strongBearEvent := powerPct <= 100.0 - strongTh and not wasStrongBear
        cascade := useMtf ? (tf1Power >= bullTh and tf2Power >= bullTh and tf3Power >= bullTh ? 1 : tf1Power <= bearTh and tf2Power <= bearTh and tf3Power <= bearTh ? -1 : 0) : 0
        publishedVolume := localVolume and (not useMtf or (v1 and v2 and v3))
 
    int oldDirection = trendDir
    if ready and not na(atr) and not na(basis)
        [nextDirection, nextLine] = f_follow(trendDir, trendLine, powerPct, bullBase, bearBase)
        trendDir := nextDirection
        trendLine := nextLine
 
    bool rawBuy = ready and trendDir == 1 and oldDirection != 1
    bool rawSell = ready and trendDir == -1 and oldDirection != -1
    bonusLongEvent := bonusEvent and bonusSide == 1 and trendDir == 1 and powerPct >= bullTh
    bonusShortEvent := bonusEvent and bonusSide == -1 and trendDir == -1 and powerPct <= bearTh
 
    if pricesOK and wasOpen and bar_index > entryBar
        int reason = 0
        float fillPrice = na
        // Fiyat stopa degerse oncelik stopta: mum ici sira belirsiz.
        if position == 1
            if open <= stopPrice
                reason := 2
                fillPrice := open
            else if low <= stopPrice
                reason := 2
                fillPrice := stopPrice
        else
            if open >= stopPrice
                reason := 2
                fillPrice := open
            else if high >= stopPrice
                reason := 2
                fillPrice := stopPrice
 
        // TP1/TP2 artik kapatma emri degil, kontrol noktalaridir.
        if reason == 0
            bool touched1 = position == 1 ? high >= targetPrice : low <= targetPrice
            bool touched2 = position == 1 ? high >= target2Price : low <= target2Price
            if touched1 and not tp1Done
                tp1Done := true
                tp1Signal := true
            if touched2 and not tp2Done
                tp2Done := true
                tp2Signal := true
 
        // Tek onayli kapanista kesin karsi guc: LONG <=40, SHORT >=60.
        bool reversed = ready and closeOnOpposite and (position == 1 ? powerPct <= oppositeBear : powerPct >= oppositeBull)
        if reason == 0 and reversed
            reason := 3
            fillPrice := close
            if flipNextBar
                pendingSide := -position
                pendingBar := bar_index
 
        // TP1 sonrasi zarar durdur ALSA trend cizgisine yaklastirilir.
        // YENI seviye, guncel mumda degil SONRAKI mumda gecerlidir.
        if reason == 0 and tp1Done
            weakPowerWarning := ready and (position == 1 ? powerPct < continuePower : 100.0 - powerPct < continuePower)
            float protection = stopPrice
            if breakEven
                protection := position == 1 ? math.max(protection, entryPrice) : math.min(protection, entryPrice)
            if not na(trendLine) and trendDir == position
                protection := position == 1 ? math.max(protection, trendLine) : math.min(protection, trendLine)
            // Stopu mevcut fiyatın yanlış tarafina tasimayalim.
            if position == 1 and protection < close - syminfo.mintick
                stopPrice := math.max(stopPrice, math.round_to_mintick(protection))
            if position == -1 and protection > close + syminfo.mintick
                stopPrice := math.min(stopPrice, math.round_to_mintick(protection))
 
        if reason > 0
            exitPrice := fillPrice
            exitNet := f_net(position, entryPrice, fillPrice)
            f_record(position == 1 ? 0 : 1, exitNet)
            f_record(2, exitNet)
            oppositeSignal := reason == 3
            beSignal := reason == 2 and tp1Done and math.abs(stopPrice - entryPrice) <= syminfo.mintick / 2
            trailExitSignal := reason == 2 and tp1Done and not beSignal and math.abs(stopPrice - initialStop) >= syminfo.mintick / 2
            slSignal := reason == 2 and not beSignal and not trailExitSignal
            position := 0
 
    // Kapanan planin mumunda yeniden girme; ters flip sonraki kapanista.
    if pricesOK and ready and not wasOpen and position == 0
        bool pendingValid = flipNextBar and pendingSide != 0 and bar_index == pendingBar + 1 and trendDir == pendingSide and (pendingSide == 1 ? powerPct >= oppositeBull : powerPct <= oppositeBear)
        int wanted = rawBuy ? 1 : rawSell ? -1 : pendingValid ? pendingSide : 0
        if wanted == 1 and tradeMode == "SHORT"
            wanted := 0
        if wanted == -1 and tradeMode == "LONG"
            wanted := 0
 
        if wanted != 0
            float candidateStop = f_stop(wanted, close, atr)
            float candidateTarget = f_target(wanted, close, candidateStop)
            float candidateTarget2 = f_target2(wanted, close, candidateTarget)
            if not na(candidateStop) and not na(candidateTarget) and not na(candidateTarget2)
                position := wanted
                planSide := wanted
                entryPrice := close
                initialStop := candidateStop
                stopPrice := candidateStop
                targetPrice := candidateTarget
                target2Price := candidateTarget2
                tp1Done := false
                tp2Done := false
                entryBar := bar_index
                planNumber += 1
                buySignal := wanted == 1
                sellSignal := wanted == -1
            else
                rejectedPlans += 1
 
    if pendingSide != 0 and bar_index >= pendingBar + 1
        pendingSide := 0
        pendingBar := -1
 
//━━━━━━━━━━━━━━━━ POWER DISPLAY
float directionalPower = trendDir == 1 ? powerPct : trendDir == -1 ? 100.0 - powerPct : 50.0
 
string powerState = na(powerPct) ? t("WAIT", "BEKLE") : powerPct >= strongTh ? t("STRONG BULL", "GUCLU YUKARI") : powerPct >= normalTh ? t("BULL", "YUKARI") : powerPct <= 100.0 - strongTh ? t("STRONG BEAR", "GUCLU ASAGI") : powerPct <= 100.0 - normalTh ? t("BEAR", "ASAGI") : t("NEUTRAL", "NOTR")
 
color lineColor = trendDir == 1 ? bullC : trendDir == -1 ? bearC : midC
bool strongTrend = directionalPower >= strongTh
bool mediumTrend = directionalPower >= normalTh and directionalPower < strongTh
bool weakTrend = directionalPower < normalTh
 
string strengthState = strongTrend ? t("STRONG", "GUCLU") : mediumTrend ? t("NORMAL", "NORMAL") : directionalPower >= weakTh ? t("WEAK", "ZAYIF") : t("FADING", "SONUYOR")
 
//━━━━━━━━━━━━━━━━ SCAN STATE
var bool scanLong = false
var bool scanShort = false
var bool publishedBuy = false
var bool publishedSell = false
var float publishedLabRate = na
var int publishedLabSamples = 0
bool scanLongEvent = false
bool scanShortEvent = false
 
if barstate.isconfirmed
    publishedBuy := buySignal
    publishedSell := sellSignal
    publishedLabRate := currentLabRate
    publishedLabSamples := currentLabSamples
    bool oldLong = scanLong
    bool oldShort = scanShort
    bool bonusLongActive = bonusPoints > 0 and bonusSide == 1
    bool bonusShortActive = bonusPoints > 0 and bonusSide == -1
    scanLong := ready and (scanMode == "YENI ISLEM" ? buySignal : scanMode == "BONUSLU LONG" ? bonusLongEvent : scanMode == "BONUSLU SHORT" ? false : powerPct >= scanPower and (not scanOnlyBonus or bonusLongActive))
    scanShort := ready and (scanMode == "YENI ISLEM" ? sellSignal : scanMode == "BONUSLU SHORT" ? bonusShortEvent : scanMode == "BONUSLU LONG" ? false : powerPct <= 100.0 - scanPower and (not scanOnlyBonus or bonusShortActive))
    scanLongEvent := scanLong and not oldLong
    scanShortEvent := scanShort and not oldShort
 
// Pine Screener icin ilk 10 cikti.
plot(scanLong ? 1 : 0, "01 Tarama LONG", display=display.data_window)
plot(scanShort ? 1 : 0, "02 Tarama SHORT", display=display.data_window)
plot(publishedReady ? powerPct : na, "03 ATS bonuslu puan", display=display.data_window)
plot(publishedReady ? basePowerPct : na, "04 ATS baz puan", display=display.data_window)
plot(bonusSide * bonusPoints, "05 Yonlu renk bonusu", display=display.data_window)
plot(bonusPoints > 0 ? bonusRate : publishedLabRate, "06 Renk basarisi (%)", display=display.data_window)
plot(bonusPoints > 0 ? bonusSamples : publishedLabSamples, "07 Renk ornek sayisi", display=display.data_window)
plot(publishedBuy ? 1 : 0, "08 Yeni LONG", display=display.data_window)
plot(publishedSell ? 1 : 0, "09 Yeni SHORT", display=display.data_window)
plot(position, "10 Acik plan -1 0 1", display=display.data_window)
 
//━━━━━━━━━━━━━━━━ TREND / AURA
var float confirmedPrice = na
 
if barstate.isconfirmed
    confirmedPrice := close
 
// Gizli fiyat serisinde sabit renk: gereksiz cizim sayisini azaltir.
pPrice = plot(confirmedPrice, "Confirmed Price", color=color.new(color.gray, 100), display=display.none)
pWeak = plot(weakTrend ? trendLine : na, "Weak Trend", color=lineColor, linewidth=2, style=plot.style_linebr)
pMid = plot(mediumTrend ? trendLine : na, "Medium Trend", color=lineColor, linewidth=4, style=plot.style_linebr)
pStrong = plot(strongTrend ? trendLine : na, "Strong Trend", color=lineColor, linewidth=6, style=plot.style_linebr)
 
int auraAlpha = strongTrend ? 84 : mediumTrend ? 91 : 97
 
// Tek gorunmez aura capasi ile uc fill yerine bir fill.
// Asil zayif/normal/guclu cizgiler, renkler ve yon mantigi aynen kalir.
pAura = plot(trendLine, "Aura Anchor", color=color.new(color.gray, 100), display=display.none)
fill(pPrice, pAura, color=showAura ? color.new(lineColor, auraAlpha) : na, fillgaps=false)
 
color candleColor = showLabColors and useLab and currentLabCat >= 0 ? f_lab_color(currentLabCat) : showBars and trendDir != 0 ? color.new(lineColor, strongTrend ? 15 : mediumTrend ? 35 : 60) : na
barcolor(barstate.isconfirmed ? candleColor : na)
 
//━━━━━━━━━━━━━━━━ SIGNALS
plotshape(showSignals and buySignal, "BUY", shape.labelup, location.belowbar, bullC, text="BUY", textcolor=color.black, size=size.tiny)
plotshape(showSignals and sellSignal, "SELL", shape.labeldown, location.abovebar, bearC, text="SELL", textcolor=color.white, size=size.tiny)
plotshape(showSignals and tp1Signal, "TP1 KONTROL", shape.labeldown, location.abovebar, goldC, text="TP1", textcolor=color.black, size=size.tiny)
plotshape(showSignals and tp2Signal, "TP2 KONTROL", shape.labeldown, location.abovebar, goldC, text="TP2", textcolor=color.black, size=size.tiny)
plotshape(showSignals and slSignal, "ILK STOP", shape.labeldown, location.abovebar, midC, text="STOP", textcolor=color.white, size=size.tiny)
plotshape(showSignals and trailExitSignal, "ATS TRAIL CIKIS", shape.labeldown, location.abovebar, goldC, text="TRAIL", textcolor=color.black, size=size.tiny)
plotshape(showSignals and oppositeSignal, "TERS CIKIS", shape.labeldown, location.abovebar, midC, text="TERS", textcolor=color.white, size=size.tiny)
 
//━━━━━━━━━━━━━━━━ BONUS ETIKET VE BOLGELERI
// YALNIZ GORSEL: hesaplama, LAB, ATS ve emir mantigi ayni kalir.
// BONUS etiketi ust/alt fiyat bandina konur, ince ok ilgili mumu isaretler.
// Her etiket sadece "BONUS" yazar; rengi GEZEN laboratuvar rengidir.
var array<label> oldBonusLabels = array.new<label>()
var array<line> oldBonusArrows = array.new<line>()
 
// Sabit konumlu ust/alt bantlar fiyat araliginin DISINDA tutulur.
// Pine grafik gorunur alaninin piksel koordinatini okumadigi icin,
// son 200 mumun fiyati ile otomatik mesafe hesaplanir.
float bonusVisualHi = ta.highest(high, 200)
float bonusVisualLo = ta.lowest(low, 200)
float bonusVisualAtr = math.max(nz(atr, syminfo.mintick * 10), syminfo.mintick * 10)
float bonusVisualRange = math.max(bonusVisualHi - bonusVisualLo, bonusVisualAtr * 8.0)
float bonusVisualGap = math.max(bonusVisualAtr * 2.5, bonusVisualRange * 0.22)
 
if showBonusZones and barstate.isconfirmed and (bonusLongEvent or bonusShortEvent)
    bool bonusIsLong = bonusLongEvent
    color bonusColor = f_lab_color(bonusCat)
    color bonusTxtColor = bonusCat == 1 or bonusCat == 7 or bonusCat == 12 ? color.black : color.white
    float boxY = bonusIsLong ? bonusVisualLo - bonusVisualGap : bonusVisualHi + bonusVisualGap
    float tipY = bonusIsLong ? low - bonusVisualAtr * 0.12 : high + bonusVisualAtr * 0.12
 
    // Label kendi icinde kucuk kutu ve muma donuk ok ucunu barindirir.
    label bonusLabel = label.new(x=bar_index, y=boxY, text="BONUS", xloc=xloc.bar_index, yloc=yloc.price, style=bonusIsLong ? label.style_label_up : label.style_label_down, color=bonusColor, textcolor=bonusTxtColor, size=size.tiny)
    // Okun ucu tetikleyen ASIL mumun biraz disindadir.
    line bonusArrow = line.new(x1=bar_index, y1=boxY, x2=bar_index, y2=tipY, xloc=xloc.bar_index, extend=extend.none, color=color.new(bonusColor, 65), style=line.style_arrow_right, width=1)
    array.push(oldBonusLabels, bonusLabel)
    array.push(oldBonusArrows, bonusArrow)
 
    if array.size(oldBonusLabels) > bonusKeep
        label.delete(array.shift(oldBonusLabels))
        line.delete(array.shift(oldBonusArrows))
 
//━━━━━━━━━━━━━━━━ TRADE PLAN VISUAL (PhenLabs duzeninden uyarlama)
f_note(string state) =>
    "#" + str.tostring(planNumber) + (planSide == 1 ? " LONG | " : " SHORT | ") + state + "\nGIRIS " + str.tostring(entryPrice, format.mintick) + " | STOP " + str.tostring(stopPrice, format.mintick) + "\nTP1 " + str.tostring(targetPrice, format.mintick) + (tp1Done ? " [OK]" : "") + "\nTP2 " + str.tostring(target2Price, format.mintick) + (tp2Done ? " [OK]" : "")
 
var box riskBox = na
var box rewardBox = na
var line entryLine = na
var line stopLine = na
var line tp1Line = na
var line tp2Line = na
var label entryPill = na
var label stopPill = na
var label tp1Pill = na
var label tp2Pill = na
var array<box> planBoxes = array.new<box>()
var array<line> planLines = array.new<line>()
var array<label> planLabels = array.new<label>()
 
if showPlans and (buySignal or sellSignal)
    if not showPastPlans
        for b in planBoxes
            box.delete(b)
        for ln in planLines
            line.delete(ln)
        for lb in planLabels
            label.delete(lb)
        array.clear(planBoxes)
        array.clear(planLines)
        array.clear(planLabels)
 
    int xRight = bar_index + planForward
    // Gelecek 500-bar sinirini gecmeyen 6-bar projeksiyon.
    riskBox := box.new(left=bar_index, top=math.max(entryPrice, initialStop), right=xRight, bottom=math.min(entryPrice, initialStop), xloc=xloc.bar_index, border_color=color.new(bearC, 55), bgcolor=color.new(bearC, 90))
    rewardBox := box.new(left=bar_index, top=math.max(entryPrice, target2Price), right=xRight, bottom=math.min(entryPrice, target2Price), xloc=xloc.bar_index, border_color=color.new(bullC, 55), bgcolor=color.new(bullC, 92))
    array.push(planBoxes, riskBox)
    array.push(planBoxes, rewardBox)
    if showLevels
        entryLine := line.new(bar_index, entryPrice, xRight, entryPrice, xloc=xloc.bar_index, color=chart.fg_color, width=1)
        stopLine := line.new(bar_index, stopPrice, xRight, stopPrice, xloc=xloc.bar_index, color=bearC, width=1)
        tp1Line := line.new(bar_index, targetPrice, xRight, targetPrice, xloc=xloc.bar_index, color=bullC, style=line.style_dotted)
        tp2Line := line.new(bar_index, target2Price, xRight, target2Price, xloc=xloc.bar_index, color=bullC, style=line.style_dashed)
        entryPill := label.new(xRight, entryPrice, "GIRIS " + str.tostring(entryPrice, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=color.new(chart.bg_color, 20), textcolor=chart.fg_color, size=size.tiny)
        stopPill := label.new(xRight, stopPrice, "ATS STOP " + str.tostring(stopPrice, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=color.new(bearC, 70), textcolor=chart.fg_color, size=size.tiny)
        tp1Pill := label.new(xRight, targetPrice, "TP1 " + str.tostring(targetPrice, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=color.new(bullC, 68), textcolor=chart.fg_color, size=size.tiny)
        tp2Pill := label.new(xRight, target2Price, "TP2 " + str.tostring(target2Price, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=color.new(bullC, 68), textcolor=chart.fg_color, size=size.tiny)
        array.push(planLines, entryLine)
        array.push(planLines, stopLine)
        array.push(planLines, tp1Line)
        array.push(planLines, tp2Line)
        array.push(planLabels, entryPill)
        array.push(planLabels, stopPill)
        array.push(planLabels, tp1Pill)
        array.push(planLabels, tp2Pill)
 
    while array.size(planBoxes) > keepPlans * 2
        box.delete(array.shift(planBoxes))
    while array.size(planLines) > keepPlans * 4
        line.delete(array.shift(planLines))
    while array.size(planLabels) > keepPlans * 4
        label.delete(array.shift(planLabels))
 
bool justExited = oppositeSignal or trailExitSignal or beSignal or slSignal
if showPlans and not na(rewardBox) and (position != 0 or justExited)
    int xEnd = bar_index + (position != 0 ? planForward : 2)
    box.set_right(riskBox, xEnd)
    box.set_right(rewardBox, xEnd)
    if showLevels and not na(entryLine)
        line.set_x2(entryLine, xEnd)
        line.set_x2(stopLine, xEnd)
        line.set_x2(tp1Line, xEnd)
        line.set_x2(tp2Line, xEnd)
        line.set_y1(stopLine, stopPrice)
        line.set_y2(stopLine, stopPrice)
        label.set_x(entryPill, xEnd)
        label.set_x(stopPill, xEnd)
        label.set_x(tp1Pill, xEnd)
        label.set_x(tp2Pill, xEnd)
        label.set_y(stopPill, stopPrice)
        label.set_text(stopPill, "ATS STOP " + str.tostring(stopPrice, format.mintick) + (position == 0 ? " [CIKIS]" : ""))
        label.set_text(tp1Pill, "TP1 " + str.tostring(targetPrice, format.mintick) + (tp1Done ? " ✓" : ""))
        label.set_text(tp2Pill, "TP2 " + str.tostring(target2Price, format.mintick) + (tp2Done ? " ✓ TREND" : ""))
 
//━━━━━━━━━━━━━━━━ OPTIONAL BADGES
color neutral = chart.fg_color
int drawRight = nz(time_close, time)
var label star = na
var label badge = na
 
if barstate.islastconfirmedhistory or (barstate.islast and barstate.isconfirmed)
    label.delete(star)
    label.delete(badge)
 
    if showStar and not na(trendLine)
        star := label.new(bar_index, trendLine, "✪ " + str.tostring(directionalPower, "#.0") + "/100\n" + strengthState, textcolor=lineColor, color=color.new(chart.bg_color, 100), style=label.style_label_center, size=size.small)
 
    if showBadge and not na(powerPct)
        badge := label.new(x=drawRight, y=close, text="ATS " + str.tostring(basePowerPct, "#.0") + (bonusSide == -1 ? " - " : " + ") + str.tostring(bonusPoints) + " => " + str.tostring(powerPct, "#.0") + "/100\n" + powerState, xloc=xloc.bar_time, textcolor=neutral, color=color.new(chart.bg_color, 10), style=label.style_label_left, size=size.small)
 
//━━━━━━━━━━━━━━━━ PANEL
var table panel = table.new(position.top_right, 2, 13, border_width=0)
 
f_cell(int col, int row, string txt, color fg, string tip = "") =>
    table.cell(panel, col, row, txt, text_color=fg, bgcolor=color.new(chart.bg_color, 10), text_size=size.tiny, tooltip=tip)
 
if barstate.islast and showPanel
    int n = array.get(counts, 2)
    float net = array.get(equity, 2) - 100.0
    color netColor = net > 0 ? color.lime : net < 0 ? color.red : neutral
    string mtfText = not useMtf ? "KAPALI" : not publishedReady ? "VERI BEKLE" : cascade == 1 ? "3/3 BULL" : cascade == -1 ? "3/3 BEAR" : "KARISIK"
    float holdingPower = position == 1 ? powerPct : position == -1 ? 100.0 - powerPct : directionalPower
    string sideText = bonusSide == 1 ? "LONG" : bonusSide == -1 ? "SHORT" : "YOK"
    string colorInfo = bonusCat >= 0 ? array.get(labNames, bonusCat) + " | " + str.tostring(bonusRate, "#.1") + "% N=" + str.tostring(bonusSamples) : "Henuz uygun renk yok"
    string planStatus = position == 0 ? "BOS" : (position == 1 ? "LONG #" : "SHORT #") + str.tostring(planNumber) + (tp2Done ? " ->TREND" : tp1Done ? " ->TP2" : " ->TP1")
    f_cell(0, 0, "ATS V4", neutral)
    f_cell(1, 0, publishedReady ? "ONAYLI" : "VERI BEKLE", publishedReady ? lineColor : midC)
    f_cell(0, 1, "ATS toplam", neutral)
    f_cell(1, 1, publishedReady ? str.tostring(powerPct, "#.1") + "/100" : "-", neutral, powerState)
    f_cell(0, 2, "ATS baz", neutral)
    f_cell(1, 2, publishedReady ? str.tostring(basePowerPct, "#.1") : "-", neutral, "Bonus haric ATS orijinal puani")
    f_cell(0, 3, "Renk bonusu", neutral)
    f_cell(1, 3, (bonusSide == -1 ? "-" : "+") + str.tostring(bonusPoints), bonusPoints > 0 ? f_lab_color(bonusCat) : midC, "SHORT icin puan azalir; yon gucune +puan eklenir. " + colorInfo)
    f_cell(0, 4, "Bonus tipi", neutral)
    f_cell(1, 4, bonusPoints > 0 ? "CANDLESTICK " + sideText : "PASIF", bonusPoints > 0 ? f_lab_color(bonusCat) : midC)
    f_cell(0, 5, "Renk basarisi", neutral)
    f_cell(1, 5, bonusCat >= 0 ? str.tostring(bonusRate, "#.1") + "% | N " + str.tostring(bonusSamples) : "-", bonusCat >= 0 ? f_lab_color(bonusCat) : midC, colorInfo)
    f_cell(0, 6, position != 0 ? "Plan gucu" : "Yon gucu", neutral)
    f_cell(1, 6, publishedReady ? str.tostring(holdingPower, "#.1") + "/100" : "-", lineColor)
    f_cell(0, 7, "MTF / PVM", neutral)
    f_cell(1, 7, mtfText + " / " + (usePvmBoost and pvmWeight > 0 ? str.tostring(100 * pvmWeight, "#.0") + "%" : "KAPALI"), neutral)
    f_cell(0, 8, "Hacim", neutral)
    f_cell(1, 8, not publishedReady ? "-" : publishedVolume ? "MEVCUT" : "KISMI / YOK", neutral)
    f_cell(0, 9, "Plan", neutral)
    f_cell(1, 9, planStatus, neutral)
    f_cell(0, 10, "Basari", neutral)
    f_cell(1, 10, n > 0 ? str.tostring(100.0 * array.get(wins, 2) / n, "#.1") + "% | N " + str.tostring(n) : "- | N 0", neutral, "Kapanan planlar, TP1/TP2 sadece kontrol")
    f_cell(0, 11, "Net getiri", netColor)
    f_cell(1, 11, str.tostring(net, "#.2") + "%", netColor, "Kapanan planlarin bilesik net getirisi")
    f_cell(0, 12, "Tarama", neutral)
    f_cell(1, 12, (scanLong ? "LONG " : "") + (scanShort ? "SHORT" : "") + (not scanLong and not scanShort ? "BEKLE" : ""), neutral, scanMode)
 
//━━━━━━━━━━━━━━━━ ALERTS
alertcondition(scanLongEvent, "ATS V4 TARAMA LONG", "ATS V4: yeni LONG tarama kosulu")
alertcondition(scanShortEvent, "ATS V4 TARAMA SHORT", "ATS V4: yeni SHORT tarama kosulu")
alertcondition(buySignal, "ATS V4 BUY", "ATS V4: yeni LONG plani")
alertcondition(sellSignal, "ATS V4 SELL", "ATS V4: yeni SHORT plani")
alertcondition(tp1Signal, "ATS V4 TP1", "ATS V4: TP1 kontrol; trend devam ediyor")
alertcondition(tp2Signal, "ATS V4 TP2", "ATS V4: TP2 kontrol; ATS trend stopuyla takip")
alertcondition(slSignal, "ATS V4 STOP", "ATS V4: ilk stop")
alertcondition(beSignal, "ATS V4 BREAKEVEN", "ATS V4: giris fiyati stopu")
alertcondition(trailExitSignal, "ATS V4 ATS TRAIL", "ATS V4: ATS trend stopu cikisi")
alertcondition(oppositeSignal, "ATS V4 TERS CIKIS", "ATS V4: ters guc kapanisi")
alertcondition(bonusLongEvent, "ATS V4 BONUS CANDLESTICK LONG", "ATS V4: basarili LONG mum rengi")
alertcondition(bonusShortEvent, "ATS V4 BONUS CANDLESTICK SHORT", "ATS V4: basarili SHORT mum rengi")
alertcondition(strongBullEvent, "ATS V4 GUCLU BULL", "ATS V4: guclu yukari guce gecis")
alertcondition(strongBearEvent, "ATS V4 GUCLU BEAR", "ATS V4: guclu asagi guce gecis")
 
// Ayni mumda birden fazla olay tek bildirimde birlesir.
if dynamicAlerts and barstate.isconfirmed
    string msg = ""
    if buySignal or sellSignal
        msg += f_note("ACIK") + "\n"
    if tp1Signal
        msg += "TP1 KONTROL | " + str.tostring(targetPrice, format.mintick) + "\n"
    if tp2Signal
        msg += "TP2 KONTROL | TREND TAKIP | " + str.tostring(target2Price, format.mintick) + "\n"
    if slSignal or beSignal or trailExitSignal or oppositeSignal
        string exitType = oppositeSignal ? "TERS ATS" : beSignal ? "STOP GIRIS" : trailExitSignal ? "ATS TRAIL" : "STOP"
        msg += exitType + " | CIKIS " + str.tostring(exitPrice, format.mintick) + " | NET " + str.tostring(exitNet, "#.000") + "%\n"
    if bonusLongEvent or bonusShortEvent
        msg += "BONUS CANDLESTICK " + (bonusLongEvent ? "LONG" : "SHORT") + " | " + array.get(labNames, bonusCat) + " | " + str.tostring(bonusRate, "#.1") + "% | N " + str.tostring(bonusSamples) + "\n"
    if scanLongEvent or scanShortEvent
        msg += "TARAMA " + (scanLongEvent ? "LONG" : "SHORT") + " | ATS " + str.tostring(powerPct, "#.1") + "\n"
    if msg != ""
        alert("ATS V4 | " + syminfo.ticker + " | " + timeframe.period + "\n" + msg, alert.freq_once_per_bar_close)

← 返回列表