SMART MA SELECTOR - TREND LAB

Seckin_Tuncay · study · 872 行 · 点赞 36 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
// SMART MA SELECTOR - TREND LAB · v1.0  (varsayılan: EN, tek çizgi, Lab tablosu sağ alt, günlük 200 SMA ince/soluk · 9 EMA / 30 WMA TREND ENGINE v19.0 tabanlı · v19.0 Mod: MA Lab Önerisi + Lab yarı kontrolü · v18.9 menüde İngilizce + panelde Lab önerisi · v18.8 MA Lab · v18.7 tek çizgi modu · v18.6 ad büyük harf · v18.5 göstergede sürüm adı gizlendi · v18.1 Mobil panel · v18.2 üst dilim yumuşatma · v18.3 panelde tarz + önerilen dilim · v18.4 Mod: Orijinal / Oto Preset / Manuel)
// 9 EMA - 30 WMA Hareketli Ortalama Stratejisi'nden yola çıkılarak geliştirilmiştir.
//
// KARAR NOTLARI (QCE / KKO ölçümlerinden taşınan kurallar)
// 1. Trend takipçisinde sinyal filtrelenmez; pozisyon rejim bozulana kadar tutulur.
//    → RSI ve hacim filtreleri çıkarıldı. Sabit TP varsayılan KAPALI (kuyruğu keser).
// 2. Kuyruğu kesen değil büyüten kabul edilir → Kazanana Ekleme varsayılan AÇIK
//    (+1R'de 0.5 risk payıyla ikinci ve son dilim, kendi 2. stopu).
// 3. Altın, gümüş, kripto ve BIST'te short ölçümlerde negatif çıktı
//    → Yön "Oto" = bu piyasalarda Sadece Long.
// 4. 200'lük yön filtresi KKO'da en iyi erken girişleri kesti
//    → 3. ortalama varsayılan yalnız GÖRSEL; filtre isteğe bağlı ve kapalı.
// 5. İstatistikler R cinsinden ve maliyet düşülmüş. Değerlendirme: Ort. R, PF,
//    Max DD, Top 5 Hariç, İlk/Son Yarı. 30 işlemin altı yetersiz örneklem.
// ============================================================================
indicator("SMART MA SELECTOR - TREND LAB", shorttitle="SMART MA SELECTOR - TREND LAB", overlay=true, max_labels_count=500)
 
// ============================================================================
// 0 · DİL
// ============================================================================
grpLang = "0 · Dil · Language"
langIn  = input.string("EN", "Dil / Language", options=["EN", "TR"], group=grpLang)
isTR    = langIn == "TR"
tx(string tr, string en) => isTR ? tr : en
 
// ============================================================================
// 1 · ORTALAMA
// ============================================================================
grpMA  = "1 · Ortalama · Moving Average"
maMode = input.string("MA Lab Önerisi / Use MA Lab Pick", "Mod / Mode",
     options=["MA Lab Önerisi / Use MA Lab Pick", "Orijinal · 9 EMA / 30 WMA", "Oto Preset / Auto Preset", "Manuel / Manual"], group=grpMA,
     tooltip="TR: Orijinal = her piyasada 9 EMA / 30 WMA (min. fark ve maliyet piyasaya göre ayarlanır).\nOto Preset = piyasada yaygın kabul gören çiftler, piyasa ve tarza göre otomatik: Scalp 9/21 EMA (forex-emtia 5/13) · Gün İçi 8/21 EMA · Swing 20/50 EMA (kripto-emtia 21/55) · Pozisyon 50/200 SMA.\nManuel = aşağıdaki iki ortalama (örn. HMA 50 / HMA 200).\nMA Lab Önerisi = 300 çiftlik MA Lab'ın o ana kadarki en iyi çiftini kullanır. Seçim yalnız geçmişteki kapanmış işlemlere bakar ve yalnız pozisyon kapalıyken değişir; paneldeki sonuç bu yöntemin gerçekçi sonucudur.\nEN: Original = 9 EMA / 30 WMA everywhere. Auto Preset = widely used pairs by market and style. Manual = your own pair. Use MA Lab Pick = trades the best pair the 300-pair MA Lab has found so far. It only looks at past closed trades and switches only while flat, so the panel shows the realistic result of following the Lab.")
styleIn = input.string("Oto / Auto", "Tarz (Oto Preset) / Style (Auto Preset)", options=["Oto / Auto", "Scalp", "Gün İçi / Day", "Swing", "Pozisyon / Position"], group=grpMA,
     tooltip="TR: Oto = zaman diliminden: ≤15dk Scalp · ≤1sa Gün İçi · ≤1G Swing · üstü Pozisyon. Yalnız Oto Preset modunda kullanılır.\nEN: Auto = from chart timeframe: ≤15m Scalp · ≤1h Day · ≤1D Swing · above Position. Used only in Auto Preset mode.")
manFastType = input.string("EMA", "Manuel Hızlı / Manual Fast", options=["EMA", "WMA", "SMA", "RMA", "HMA"], group=grpMA, inline="mf")
manFastLen  = input.int(9, "", minval=1, group=grpMA, inline="mf")
manSlowType = input.string("WMA", "Manuel Yavaş / Manual Slow", options=["EMA", "WMA", "SMA", "RMA", "HMA"], group=grpMA, inline="ms")
manSlowLen  = input.int(30, "", minval=1, group=grpMA, inline="ms")
 
// ============================================================================
// 2 · GİRİŞ
// ============================================================================
grpEn         = "2 · Giriş · Entry"
entryStrategy = input.string("Hepsi / All", "Giriş Türü / Entry Type", options=["Hepsi / All", "Sadece Kesişim / Crossover", "Sadece Düzeltme / Pullback"], group=grpEn)
crossConfirm  = input.int(5, "Kesişim Onay Penceresi (mum) / Cross Window (bars)", minval=1, group=grpEn,
     tooltip="TR: Kesişimden sonra bu kadar mum içinde ortalamalar min. fark kadar açılırsa MOMENTUM girişi verilir.\nEN: A MOMENTUM entry fires if the MAs separate by the min gap within this many bars after the cross.")
autoGap = input.bool(true, "Oto Min. Fark (piyasa) / Auto Min Gap", group=grpEn,
     tooltip="TR: Kripto %0.25 · BIST %0.20 · emtia ve forex %0.10 · diğer %0.15\nEN: Crypto 0.25% · BIST 0.20% · metals and forex 0.10% · other 0.15%")
manGap     = input.float(0.15, "Min. Fark % / Min Gap %", minval=0, step=0.01, group=grpEn)
useReEntry = input.bool(true, "TP Sonrası Yeniden Giriş / Re-Entry after TP", group=grpEn, tooltip="TR: Yalnız Sabit TP açıkken çalışır.\nEN: Works only when Fixed TP is on.")
 
// ============================================================================
// 3 · İŞLEM · RİSK
// ============================================================================
grpRisk = "3 · İşlem · Risk"
dirMode = input.string("Oto / Auto", "Yön / Direction", options=["Oto / Auto", "Long & Short", "Sadece Long / Long Only", "Sadece Short / Short Only"], group=grpRisk,
     tooltip="TR: Oto = altın, gümüş, kripto ve BIST'te Sadece Long (ölçümlerde short negatif); forex ve diğerlerinde iki yön.\nEN: Auto = long only on gold, silver, crypto and BIST (shorts tested negative); both directions on forex and others.")
atrLen = input.int(14, "ATR Periyodu / ATR Length", minval=1, group=grpRisk)
slMult = input.float(1.5, "Stop × ATR", minval=0.1, step=0.1, group=grpRisk, tooltip="TR: 1R = bu stop mesafesi.\nEN: 1R = this stop distance.")
useTP  = input.bool(false, "Sabit TP / Fixed TP", group=grpRisk, inline="tp",
     tooltip="TR: Varsayılan kapalı — çıkış rejime bırakılır (fiyat yavaş ortalamayı ters yönde keserse). Sabit TP trendin kuyruğunu keser.\nEN: Off by default — exit is left to the regime (price crossing the slow MA against the trade). A fixed TP cuts the tail of the trend.")
tpMult   = input.float(3.0, "× ATR", minval=0.1, step=0.1, group=grpRisk, inline="tp")
autoCost = input.bool(true, "Oto Maliyet / Auto Cost", group=grpRisk, tooltip="TR: Gidiş-dönüş: BIST ve kripto %0.10 · emtia %0.03 · forex %0.02\nEN: Round trip: BIST and crypto 0.10% · metals 0.03% · forex 0.02%")
manCost  = input.float(0.10, "Maliyet % (gidiş-dönüş) / Cost % round-trip", minval=0, step=0.01, group=grpRisk)
 
// ============================================================================
// 4 · KAZANANA EKLEME
// ============================================================================
grpAdd   = "4 · Kazanana Ekleme · Pyramiding"
useAdd   = input.bool(true, "Ekleme / Enable", group=grpAdd,
     tooltip="TR: Pozisyon +Tetik R'ye gelince aynı yönde ikinci ve son dilim. Kendi stopu var, ana stop yerinde kalır. R'si ana işleme eklenir.\nEN: When the position reaches +Trigger R, a second and final unit is added. It has its own stop; the main stop stays. Its R is added to the main trade.")
addTrig  = input.float(1.0, "Tetik (R) / Trigger (R)", minval=0.1, step=0.1, group=grpAdd)
addShare = input.float(0.5, "Risk Payı / Risk Share", minval=0.1, maxval=1.0, step=0.05, group=grpAdd)
 
// ============================================================================
// 5 · GENEL TREND (3. ORTALAMA)
// ============================================================================
grpTr     = "5 · Genel Trend · Major Trend"
showTrend = input.bool(true, "Göster / Show", group=grpTr)
trendType = input.string("SMA", "Tür / Type", options=["SMA", "EMA", "WMA", "HMA", "RMA"], group=grpTr, inline="tr")
trendLen  = input.int(200, "", minval=1, group=grpTr, inline="tr")
trendSrc  = input.string("Günlük / Daily", "Kaynak Dilim / Source TF", options=["Günlük / Daily", "Grafik / Chart", "Üst Dilim (oto) / Higher TF (auto)"], group=grpTr,
     tooltip="TR: Üst dilim: ≤15dk → 1sa · <4sa → 4sa · <1G → Günlük · üstü → Haftalık. Günlük = her grafikte günlük grafiğin ortalaması (varsayılan; en çok takip edilen 200 SMA). Kapanmış mumdan okunur, repaint yok.\nEN: Higher TF: ≤15m → 1h · <4h → 4h · <1D → Daily · above → Weekly. Daily = the daily chart's MA on every timeframe (default; the widely watched 200 SMA). Read from closed bars, no repaint.")
useTrendFilter = input.bool(false, "Filtre olarak kullan / Use as filter", group=grpTr,
     tooltip="TR: Açıksa long yalnız fiyat 3. ortalamanın üstündeyken, short altındayken. Varsayılan kapalı — KKO testinde 200'lük yön filtresi en iyi erken girişleri kesti. Açmadan önce ölçün.\nEN: When on, longs only above the 3rd MA and shorts only below it. Off by default — in testing a 200 MA direction filter cut the best early entries. Measure before using.")
trendSmooth = input.bool(true, "Üst Dilim Çizgisini Yumuşat / Smooth HTF Line", group=grpTr,
     tooltip="TR: Üst dilim değeri her üst mum boyunca sabit kaldığı için çizgi basamak/zikzak görünür. Açıkken bir üst mum uzunluğunda ortalanarak düz çizgi olur (çok küçük ek gecikme).\nEN: The higher-TF value stays flat for each higher bar, so the line looks stepped. When on, it is averaged over one higher bar into a smooth line (very small extra lag).")
trendWidth = input.int(1, "Kalınlık / Width", minval=1, maxval=5, group=grpTr, inline="tw")
trendTransp = input.int(55, "Şeffaflık / Transparency %", minval=0, maxval=100, group=grpTr, inline="tw")
 
// ============================================================================
// 6 · TEST
// ============================================================================
grpTest   = "6 · Test · Backtest"
useStart  = input.bool(false, "Başlangıç Tarihi / Start Date", group=grpTest, inline="st",
     tooltip="TR: Eski verinin (altın, BIST) istatistiği bozmaması için. Örn. 2005.\nEN: Keeps very old data (gold, BIST) from distorting the statistics. E.g. 2005.")
startTime = input.time(timestamp("01 Jan 2005 00:00 +0000"), "", group=grpTest, inline="st")
 
// ============================================================================
// 7 · POZİSYON BÜYÜKLÜĞÜ
// ============================================================================
grpSize = "7 · Pozisyon Büyüklüğü · Position Size"
acct    = input.float(1000, "Kasa / Account", minval=0, group=grpSize)
riskPct = input.float(1.0, "İşlem Başına Risk % / Risk per Trade %", minval=0.01, step=0.1, group=grpSize,
     tooltip="TR: Panel, stop mesafesine göre kaç adet/ons açılacağını ve pozisyon değerini gösterir. Vadelide teminat = değer ÷ kaldıraç.\nEN: The panel shows how many units to trade for the stop distance and the position value. Futures margin = value ÷ leverage.")
 
// ============================================================================
// 8 · GÖRSEL
// ============================================================================
grpVis      = "8 · Görsel · Visuals"
singleLine  = input.bool(true, "Tek Çizgi (Yeşil / Kırmızı) / Single Line", group=grpVis, inline="sl",
     tooltip="TR: Açıkken iki ortalama yerine ikisinin ortası tek çizgi olarak çizilir. Hızlı ortalama yavaşın üstündeyse yeşil, altındaysa kırmızı. Sinyallere ve istatistiklere etkisi yoktur.\nEN: Draws one line (midpoint of both MAs) instead of two. Green when fast > slow, red otherwise. Visual only.")
singleWidth = input.int(3, "Kalınlık / Width", minval=1, maxval=6, group=grpVis, inline="sl")
singleUp    = input.color(color.new(#00e676, 0), "Yükseliş / Up", group=grpVis, inline="sc")
singleDn    = input.color(color.new(#ff5252, 0), "Düşüş / Down", group=grpVis, inline="sc")
fastColor   = input.color(color.rgb(30, 144, 255), "Hızlı / Fast", group=grpVis, inline="c1")
slowColor   = input.color(color.rgb(255, 152, 0), "Yavaş / Slow", group=grpVis, inline="c1")
showCloud   = input.bool(true, "Bulut / Cloud", group=grpVis, inline="cl")
cloudTransp = input.int(85, "Şeffaflık / Transparency %", minval=0, maxval=100, group=grpVis, inline="cl")
showBarCol  = input.bool(true, "Mum Boyama / Bar Color", group=grpVis)
showTrigLbl = input.bool(true, "Tetik Etiketleri / Trigger Labels", group=grpVis)
lblSizeOpt  = input.string("Küçük / Tiny", "Etiket Boyutu / Label Size", options=["Küçük / Tiny", "Orta / Small", "Büyük / Normal"], group=grpVis)
 
// ============================================================================
// 9 · PANEL
// ============================================================================
grpPan    = "9 · Panel"
showPanel = input.bool(true, "Panel", group=grpPan)
panelMode = input.string("Sade / Simple", "Mod / Mode", options=["Mobil / Mobile", "Sade / Simple", "Detaylı / Detailed"], group=grpPan,
     tooltip="TR: Mobil = telefon için tek sütun, 6 kısa satır. Boyutu Küçük ve konumu alt köşe seçmek önerilir.\nEN: Mobile = single column for phones. Tiny size and a bottom corner are recommended.")
panelSize = input.string("Orta / Small", "Boyut / Size", options=["Küçük / Tiny", "Orta / Small", "Büyük / Normal"], group=grpPan)
panelPos  = input.string("Sağ Üst / Top Right", "Konum / Position", options=["Sağ Üst / Top Right", "Sağ Alt / Bottom Right", "Sol Üst / Top Left", "Sol Alt / Bottom Left"], group=grpPan)
 
// ============================================================================
// 10 · ALARM · BOT
// ============================================================================
grpBot   = "10 · Alarm · Alerts"
msgLong  = input.string("LONG {{ticker}} {{close}}",  "Long Mesajı / Message",  group=grpBot,
     tooltip="TR: {{ticker}}, {{exchange}}, {{close}} kod tarafından doldurulur. 3Commas JSON'u da yapıştırabilirsiniz. Webhook TradingView'in ücretli planlarında vardır.\nEN: {{ticker}}, {{exchange}}, {{close}} are filled in by the script. You can paste 3Commas JSON. Webhooks require a paid TradingView plan.")
msgShort = input.string("SHORT {{ticker}} {{close}}", "Short Mesajı / Message", group=grpBot)
msgExit  = input.string("EXIT {{ticker}} {{close}}",  "Çıkış Mesajı / Exit",    group=grpBot)
 
// ============================================================================
// PİYASA · TARZ · ORTALAMA ÇİFTİ
// ============================================================================
tfMin = timeframe.in_seconds() / 60.0
 
tk       = syminfo.ticker
isMetal  = str.contains(tk, "XAU") or str.contains(tk, "XAG") or str.contains(tk, "GOLD") or str.contains(tk, "SILVER") or str.contains(tk, "XPT") or str.contains(tk, "XPD")
isBIST   = syminfo.prefix == "BIST"
isCrypto = syminfo.type == "crypto" and not isMetal
isFx     = (syminfo.type == "forex" or syminfo.type == "cfd") and not isMetal
isIndex  = syminfo.type == "index" and not isBIST
 
string mktName = isMetal ? tx("Emtia", "Metals") : isBIST ? "BIST" : isCrypto ? tx("Kripto", "Crypto") : isFx ? "Forex" : isIndex ? tx("Endeks", "Index") : tx("Diğer", "Other")
 
string autoStyle = tfMin <= 15 ? "Scalp" : tfMin <= 60 ? "Day" : tfMin <= 1440 ? "Swing" : "Position"
string styleKey  = styleIn == "Oto / Auto" ? autoStyle : styleIn == "Scalp" ? "Scalp" : styleIn == "Gün İçi / Day" ? "Day" : styleIn == "Swing" ? "Swing" : "Position"
string styleName = styleKey == "Scalp" ? "Scalp" : styleKey == "Day" ? tx("Gün İçi", "Day") : styleKey == "Swing" ? "Swing" : tx("Pozisyon", "Position")
string styleRange = styleKey == "Scalp" ? tx("1–15dk", "1–15m") : styleKey == "Day" ? tx("30dk–1sa", "30m–1h") : styleKey == "Swing" ? tx("2sa–1G", "2h–1D") : tx("Haftalık+", "1W+")
bool   styleMatch = styleKey == autoStyle
string styleTag   = styleName + " · " + tx("önerilen ", "recommended ") + styleRange + (styleMatch ? " ✓" : " ⚠")
 
bool isOrig = maMode == "Orijinal · 9 EMA / 30 WMA"
bool isStd  = maMode == "Oto Preset / Auto Preset"
 
string stdType    = styleKey == "Position" ? "SMA" : "EMA"
int    stdFastLen = styleKey == "Scalp" ? ((isFx or isMetal) ? 5 : 9) : styleKey == "Day" ? 8 : styleKey == "Swing" ? ((isCrypto or isMetal) ? 21 : 20) : 50
int    stdSlowLen = styleKey == "Scalp" ? ((isFx or isMetal) ? 13 : 21) : styleKey == "Day" ? 21 : styleKey == "Swing" ? ((isCrypto or isMetal) ? 55 : 50) : 200
 
string fixFastType = isOrig ? "EMA" : isStd ? stdType : manFastType
int    fixFastLen  = isOrig ? 9 : isStd ? stdFastLen : manFastLen
string fixSlowType = isOrig ? "WMA" : isStd ? stdType : manSlowType
int    fixSlowLen  = isOrig ? 30 : isStd ? stdSlowLen : manSlowLen
 
 
float minGap  = autoGap ? (isCrypto ? 0.25 : isBIST ? 0.20 : (isMetal or isFx) ? 0.10 : 0.15) : manGap
float costPct = autoCost ? (isMetal ? 0.03 : isFx ? 0.02 : 0.10) : manCost
 
bool autoLongOnly = isMetal or isCrypto or isBIST
bool allowLong    = dirMode != "Sadece Short / Short Only"
bool allowShort   = dirMode == "Oto / Auto" ? not autoLongOnly : (dirMode == "Long & Short" or dirMode == "Sadece Short / Short Only")
bool shortWarn    = allowShort and autoLongOnly
 
// ============================================================================
// 11 · MA LAB — girişler ve ortalama havuzu (açılıp kapanır)
// ============================================================================
grpLab  = "11 · MA Lab · Optimizer"
labOn   = input.bool(true, "Lab Tablosu / Lab Table", group=grpLab,
     tooltip="TR: 300 ortalama çiftini (5 tür × 5 tür × hızlı 5/9/13 × yavaş 21/30/50/100) aynı anda basit kurallarla test eder (kesişimde giriş, ters kesişimde çıkış, ATR stop, maliyet dahil; düzeltme girişi ve ekleme yok) ve son N işlemdeki PF'ye göre sıralar. '1. Yarı | 2. Yarı' sütunu çiftin grafiğin ilk ve ikinci yarısındaki PF'sidir: ikisi de iyiyse sonuç tesadüf değildir. Ağır bir hesaptır, işin bitince kapatın.\nEN: Tests 300 MA pairs at once with simple rules (cross entry, opposite-cross exit, ATR stop, costs) and ranks them by PF over their last N trades. '1st | 2nd Half' = PF in the first and second half of the chart; good in both = not luck. Heavy calculation, turn it off when done.")
labN    = input.int(100, "Son N İşlem / Last N Trades", minval=20, maxval=300, group=grpLab)
labMinN = input.int(30, "Min. İşlem (sıralamaya girmek için) / Min Trades", minval=5, group=grpLab)
labTop  = input.int(10, "Gösterilecek Sıra / Rows", minval=3, maxval=15, group=grpLab)
labPosIn = input.string("Sağ Alt / Bottom Right", "Konum / Position", options=["Sağ Üst / Top Right", "Sağ Alt / Bottom Right", "Sol Üst / Top Left", "Sol Alt / Bottom Left"], group=grpLab)
 
labF = array.from(ta.ema(close, 5), ta.ema(close, 9), ta.ema(close, 13), ta.wma(close, 5), ta.wma(close, 9), ta.wma(close, 13), ta.sma(close, 5), ta.sma(close, 9), ta.sma(close, 13), ta.rma(close, 5), ta.rma(close, 9), ta.rma(close, 13), ta.hma(close, 5), ta.hma(close, 9), ta.hma(close, 13))
labS = array.from(ta.ema(close, 21), ta.ema(close, 30), ta.ema(close, 50), ta.ema(close, 100), ta.wma(close, 21), ta.wma(close, 30), ta.wma(close, 50), ta.wma(close, 100), ta.sma(close, 21), ta.sma(close, 30), ta.sma(close, 50), ta.sma(close, 100), ta.rma(close, 21), ta.rma(close, 30), ta.rma(close, 50), ta.rma(close, 100), ta.hma(close, 21), ta.hma(close, 30), ta.hma(close, 50), ta.hma(close, 100))
 
var string[] LAB_T  = array.from("EMA", "WMA", "SMA", "RMA", "HMA")
var int[]    LAB_FL = array.from(5, 9, 13)
var int[]    LAB_SL = array.from(21, 30, 50, 100)
var int[]    cF  = array.new<int>()
var int[]    cS  = array.new<int>()
var string[] cNm = array.new<string>()
if barstate.isfirst
    for tf = 0 to 4
        for ts = 0 to 4
            for f = 0 to 2
                for s = 0 to 3
                    array.push(cF, tf * 3 + f)
                    array.push(cS, ts * 4 + s)
                    array.push(cNm, str.tostring(array.get(LAB_FL, f)) + " " + array.get(LAB_T, tf) + " / " + str.tostring(array.get(LAB_SL, s)) + " " + array.get(LAB_T, ts))
 
bool isLabMode = maMode == "MA Lab Önerisi / Use MA Lab Pick"
bool labRun    = labOn or isLabMode
var int curC        = 17    // başlangıç: 9 EMA / 30 WMA
var int labSwitches = 0
bool justSwitched = curC != nz(curC[1], curC)
int labTf = math.floor(curC / 60)
int labTs = math.floor(curC / 12) % 5
int labFi = math.floor(curC / 4) % 3
int labSi = curC % 4
 
f_ma(string type, float src, int len) =>
    switch type
        "EMA" => ta.ema(src, len)
        "WMA" => ta.wma(src, len)
        "SMA" => ta.sma(src, len)
        "RMA" => ta.rma(src, len)
        "HMA" => ta.hma(src, len)
        => ta.ema(src, len)
 
string fastType = isLabMode ? array.get(LAB_T, labTf) : fixFastType
int    fastLen  = isLabMode ? array.get(LAB_FL, labFi) : fixFastLen
string slowType = isLabMode ? array.get(LAB_T, labTs) : fixSlowType
int    slowLen  = isLabMode ? array.get(LAB_SL, labSi) : fixSlowLen
string modeName = isLabMode ? "MA Lab" : isOrig ? tx("Orijinal", "Original") : isStd ? "Oto Preset" : tx("Manuel", "Manual")
string pairText = str.tostring(fastLen) + " " + fastType + " / " + str.tostring(slowLen) + " " + slowType
 
fixedFast = f_ma(fixFastType, close, fixFastLen)
fixedSlow = f_ma(fixSlowType, close, fixSlowLen)
fastMA = isLabMode ? array.get(labF, labTf * 3 + labFi) : fixedFast
slowMA = isLabMode ? array.get(labS, labTs * 4 + labSi) : fixedSlow
atr    = ta.atr(atrLen)
 
// ============================================================================
// GENEL TREND (3. ORTALAMA)
// ============================================================================
bool   isDailySrc = trendSrc == "Günlük / Daily"
string htf    = isDailySrc ? "D" : tfMin <= 15 ? "60" : tfMin < 240 ? "240" : tfMin < 1440 ? "D" : "W"
bool useHtfTr = (isDailySrc and tfMin < 1440) or trendSrc == "Üst Dilim (oto) / Higher TF (auto)"
trendChart    = f_ma(trendType, close, trendLen)
trendHtf      = request.security(syminfo.tickerid, htf, f_ma(trendType, close, trendLen)[1], lookahead=barmerge.lookahead_on)
int htfBars   = math.max(1, math.round(timeframe.in_seconds(htf) / timeframe.in_seconds()))
trendHtfAvg   = ta.sma(trendHtf, htfBars)
trendHtfS     = trendSmooth and htfBars > 1 and not na(trendHtfAvg) ? trendHtfAvg : trendHtf
trendMA       = useHtfTr ? trendHtfS : trendChart
trendBull     = close > trendMA
trendRising   = trendMA > trendMA[10]
trendCol      = trendBull and trendRising ? color.new(#00e676, trendTransp) : (not trendBull and not trendRising) ? color.new(#ff5252, trendTransp) : color.new(color.gray, trendTransp)
 
trendLongOK  = not useTrendFilter or na(trendMA) or close > trendMA
trendShortOK = not useTrendFilter or na(trendMA) or close < trendMA
 
inWindow = not useStart or time >= startTime
 
// ============================================================================
// POZİSYON DURUMU
// ============================================================================
var int   pos       = 0      // 1 long · -1 short · 0 nakit
var float entryPx   = na
var float stopDist  = na
var float slLvl     = na
var float tpLvl     = na
var int   entryBar  = na
var int   entryType = 0      // 0 momentum · 1 düzeltme · 2 yeniden giriş
var bool  added     = false
var bool  addActive = false
var float addPx     = na
var float addDist   = na
var float addSL     = na
var float addRDone  = 0.0
var bool  waitReL   = false
var bool  waitReS   = false
 
// ============================================================================
// GİRİŞ MOTORU
// ============================================================================
gapPct = math.abs((fastMA - slowMA) / slowMA) * 100
sep    = gapPct >= minGap
 
xUp    = ta.crossover(fastMA, slowMA)
xDn    = ta.crossunder(fastMA, slowMA)
cuSlow = ta.crossunder(close, slowMA)
coSlow = ta.crossover(close, slowMA)
 
var int lastUp = na
var int lastDn = na
if xUp
    lastUp := bar_index
    lastDn := na
if xDn
    lastDn := bar_index
    lastUp := na
if justSwitched
    lastUp := na
    lastDn := na
 
crossUp   = not na(lastUp) and (bar_index - lastUp <= crossConfirm) and fastMA > slowMA and sep and trendLongOK
crossDown = not na(lastDn) and (bar_index - lastDn <= crossConfirm) and fastMA < slowMA and sep and trendShortOK
 
trigL = pos == 0 and fastMA > slowMA and sep and close[1] > fastMA[1] and close < fastMA and close > slowMA and trendLongOK
trigS = pos == 0 and fastMA < slowMA and sep and close[1] < fastMA[1] and close > fastMA and close < slowMA and trendShortOK
 
var float trigHigh = na
var float trigLow  = na
var bool  waitBrkL = false
var bool  waitBrkS = false
 
if trigL and allowLong
    trigHigh := high
    waitBrkL := true
    waitBrkS := false
if trigS and allowShort
    trigLow  := low
    waitBrkS := true
    waitBrkL := false
 
pbLong  = waitBrkL and high > trigHigh and not trigL
pbShort = waitBrkS and low < trigLow and not trigS
 
if pbLong
    waitBrkL := false
    trigHigh := na
if pbShort
    waitBrkS := false
    trigLow  := na
if close < slowMA or fastMA < slowMA
    waitBrkL := false
    trigHigh := na
if close > slowMA or fastMA > slowMA
    waitBrkS := false
    trigLow  := na
 
bool allowCross = entryStrategy != "Sadece Düzeltme / Pullback"
bool allowPB    = entryStrategy != "Sadece Kesişim / Crossover"
 
reL = useReEntry and useTP and waitReL and close > fastMA and fastMA > slowMA and close > open and trendLongOK
reS = useReEntry and useTP and waitReS and close < fastMA and fastMA < slowMA and close < open and trendShortOK
 
longSig  = allowLong and inWindow and not justSwitched and pos == 0 and not na(atr) and ((allowCross and crossUp) or (allowPB and pbLong) or reL)
shortSig = allowShort and inWindow and not justSwitched and pos == 0 and not na(atr) and not longSig and ((allowCross and crossDown) or (allowPB and pbShort) or reS)
 
int lType = reL ? 2 : (allowCross and crossUp) ? 0 : 1
int sType = reS ? 2 : (allowCross and crossDown) ? 0 : 1
 
// Momentum penceresi bir kez kullanılınca kapanır
if crossUp
    lastUp := na
if crossDown
    lastDn := na
 
if longSig
    pos       := 1
    entryPx   := close
    stopDist  := atr * slMult
    slLvl     := close - stopDist
    tpLvl     := useTP ? close + atr * tpMult : na
    entryBar  := bar_index
    entryType := lType
    added     := false
    addActive := false
    addRDone  := 0.0
    waitReL   := false
 
if shortSig
    pos       := -1
    entryPx   := close
    stopDist  := atr * slMult
    slLvl     := close + stopDist
    tpLvl     := useTP ? close - atr * tpMult : na
    entryBar  := bar_index
    entryType := sType
    added     := false
    addActive := false
    addRDone  := 0.0
    waitReS   := false
 
// ============================================================================
// ÇIKIŞ · EKLEME · İSTATİSTİK
// ============================================================================
lblSize = lblSizeOpt == "Küçük / Tiny" ? size.tiny : lblSizeOpt == "Orta / Small" ? size.small : size.normal
 
var array<float> aR    = array.new<float>()
var array<int>   aType = array.new<int>()
var array<int>   aDir  = array.new<int>()
var float cumR       = 0.0
var float peakR      = 0.0
var float maxDD      = 0.0
var float addContrib = 0.0
var int   addCount   = 0
 
post      = pos != 0 and bar_index > entryBar
hitSL     = post and (pos == 1 ? low <= slLvl : high >= slLvl)
hitTP     = post and useTP and not hitSL and (pos == 1 ? high >= tpLvl : low <= tpLvl)
regExit   = post and (pos == 1 ? cuSlow : coSlow)
exitNow   = hitSL or hitTP or regExit
addHitNow = post and addActive and (pos == 1 ? low <= addSL : high >= addSL)
 
if exitNow
    float exitPx = hitSL ? slLvl : hitTP ? tpLvl : close
    float mainR  = pos * (exitPx - entryPx) / stopDist - (costPct / 100 * entryPx) / stopDist
    if addActive
        float aPx = addHitNow ? addSL : exitPx
        addRDone += addShare * (pos * (aPx - addPx) / addDist) - addShare * (costPct / 100 * addPx) / addDist
    float totalR = mainR + addRDone
 
    array.push(aR, totalR)
    array.push(aType, entryType)
    array.push(aDir, pos)
    if array.size(aR) > 2000
        array.shift(aR)
        array.shift(aType)
        array.shift(aDir)
    cumR  += totalR
    peakR := math.max(peakR, cumR)
    maxDD := math.min(maxDD, cumR - peakR)
    if added
        addContrib += addRDone
        addCount   += 1
 
    string reason = hitSL ? "SL" : hitTP ? "TP" : tx("Rejim", "Regime")
    bool wasLong  = pos == 1
    label.new(bar_index, wasLong ? high : low, tx("✖ ÇIKIŞ", "✖ EXIT") + " · " + reason + " · " + str.tostring(totalR, "+0.00;-0.00") + "R",
         style=wasLong ? label.style_label_down : label.style_label_up,
         color=color.new(totalR > 0 ? #26a69a : color.gray, 20), textcolor=color.white, size=lblSize)
 
    if hitTP and wasLong
        waitReL := true
    if hitTP and not wasLong
        waitReS := true
 
    pos       := 0
    slLvl     := na
    tpLvl     := na
    entryBar  := na
    addActive := false
    addSL     := na
else if addHitNow
    addRDone  += addShare * (pos * (addSL - addPx) / addDist) - addShare * (costPct / 100 * addPx) / addDist
    addActive := false
    addSL     := na
 
// Kazanana ekleme: pozisyon hâlâ açıksa ve +Tetik R'ye kapanış geldiyse
if useAdd and post and not exitNow and pos != 0 and not added
    float trigLvl = entryPx + pos * addTrig * stopDist
    if (pos == 1 and close >= trigLvl) or (pos == -1 and close <= trigLvl)
        added     := true
        addActive := true
        addPx     := close
        addDist   := atr * slMult
        addSL     := close - pos * addDist
        label.new(bar_index, pos == 1 ? low : high, tx("+ EKLE", "+ ADD"),
             style=pos == 1 ? label.style_label_up : label.style_label_down,
             color=color.new(#7e57c2, 15), textcolor=color.white, size=lblSize)
 
if close < fastMA or fastMA < slowMA
    waitReL := false
if close > fastMA or fastMA > slowMA
    waitReS := false
 
// ============================================================================
// ÇİZİMLER & ETİKETLER
// ============================================================================
pFast = plot(singleLine ? na : fastMA, "Hızlı / Fast", color=fastColor, linewidth=2)
pSlow = plot(singleLine ? na : slowMA, "Yavaş / Slow", color=slowColor, linewidth=2)
fill(pFast, pSlow, color=showCloud and not singleLine ? (fastMA >= slowMA ? color.new(#26a69a, cloudTransp) : color.new(#ef5350, cloudTransp)) : na, title="Bulut / Cloud")
 
midMA = (fastMA + slowMA) / 2
plot(singleLine ? midMA : na, "Tek Çizgi / Single Line", color=fastMA >= slowMA ? singleUp : singleDn, linewidth=singleWidth)
 
plot(showTrend ? trendMA : na, "Genel Trend / 3rd MA", color=trendCol, linewidth=trendWidth)
 
plot(pos != 0 ? slLvl : na, "Stop Loss", color=color.red, style=plot.style_linebr, linewidth=2)
plot(pos != 0 and useTP ? tpLvl : na, "Take Profit", color=color.green, style=plot.style_linebr, linewidth=2)
plot(pos != 0 and addActive ? addSL : na, "Ekleme Stop / Add Stop", color=color.new(#7e57c2, 0), style=plot.style_linebr, linewidth=1)
 
if showTrigLbl and trigL and allowPB and allowLong and inWindow
    label.new(bar_index, high, tx("🔫 TETİK", "🔫 TRIGGER"), style=label.style_label_down, color=color.new(#ff9800, 25), textcolor=color.white, size=lblSize)
if showTrigLbl and trigS and allowPB and allowShort and inWindow
    label.new(bar_index, low, tx("🔫 TETİK", "🔫 TRIGGER"), style=label.style_label_up, color=color.new(#ff9800, 25), textcolor=color.white, size=lblSize)
 
if longSig
    string lt = lType == 2 ? tx("🔄 YENİDEN AL", "🔄 RE-ENTRY LONG") : lType == 0 ? tx("⚡ MOMENTUM AL", "⚡ MOMENTUM LONG") : tx("▲ DÜZELTME AL", "▲ PULLBACK LONG")
    label.new(bar_index, low, lt, style=label.style_label_up, color=color.new(#26a69a, 10), textcolor=color.white, size=lblSize)
if shortSig
    string st = sType == 2 ? tx("🔄 YENİDEN SAT", "🔄 RE-ENTRY SHORT") : sType == 0 ? tx("⚡ MOMENTUM SAT", "⚡ MOMENTUM SHORT") : tx("▼ DÜZELTME SAT", "▼ PULLBACK SHORT")
    label.new(bar_index, high, st, style=label.style_label_down, color=color.new(#ef5350, 10), textcolor=color.white, size=lblSize)
 
barcolor(showBarCol ? (fastMA > slowMA ? color.new(#26a69a, 70) : color.new(#ef5350, 70)) : na)
 
// ============================================================================
// 11 · MA LAB — simülasyon, seçim ve tablo
// ============================================================================
var int[]   lPos  = array.new<int>(300, 0)
var float[] lEp   = array.new<float>(300, na)
var float[] lDist = array.new<float>(300, na)
var float[] lSt   = array.new<float>(300, na)
var bool[]  lH2   = array.new<bool>(300, false)
var int[]   lCnt  = array.new<int>(300, 0)
var float[] lRing = array.new<float>(300 * labN, 0.0)
var float[] rGp   = array.new<float>(300, 0.0)
var float[] rGl   = array.new<float>(300, 0.0)
var float[] rS    = array.new<float>(300, 0.0)
var float[] h1Gp  = array.new<float>(300, 0.0)
var float[] h1Gl  = array.new<float>(300, 0.0)
var int[]   h1N   = array.new<int>(300, 0)
var float[] h2Gp  = array.new<float>(300, 0.0)
var float[] h2Gl  = array.new<float>(300, 0.0)
var int[]   h2N   = array.new<int>(300, 0)
var float[] pF    = array.new<float>(15, na)
var float[] pS    = array.new<float>(20, na)
 
var int labFirst = na
if inWindow and na(labFirst)
    labFirst := bar_index
int labSplit = na(labFirst) ? na : labFirst + math.floor((last_bar_index - labFirst) / 2)
 
f_labPf(float gp, float gl) =>
    gl > 0 ? gp / gl : gp > 0 ? 99.0 : 0.0
 
float labPc = close[1]
if labRun
    bool h2Now = not na(labSplit) and bar_index >= labSplit
    for c = 0 to 299
        int   fi = array.get(cF, c)
        int   si = array.get(cS, c)
        float fN = array.get(labF, fi)
        float sN = array.get(labS, si)
        float fP = array.get(pF, fi)
        float sP = array.get(pS, si)
        if na(fN) or na(sN) or na(fP) or na(sP)
            continue
        int p = array.get(lPos, c)
        if p != 0
            float ep = array.get(lEp, c)
            float ds = array.get(lDist, c)
            float st = array.get(lSt, c)
            float px = na
            if p == 1
                px := low <= st ? st : (close < sN and labPc >= sP) ? close : na
            else
                px := high >= st ? st : (close > sN and labPc <= sP) ? close : na
            if not na(px)
                float r    = p * (px - ep) / ds - costPct / 100 * ep / ds
                int   cnt  = array.get(lCnt, c)
                int   slot = c * labN + cnt % labN
                if cnt >= labN
                    float old = array.get(lRing, slot)
                    array.set(rS, c, array.get(rS, c) - old)
                    if old > 0
                        array.set(rGp, c, array.get(rGp, c) - old)
                    else
                        array.set(rGl, c, array.get(rGl, c) + old)
                array.set(lRing, slot, r)
                array.set(rS, c, array.get(rS, c) + r)
                if r > 0
                    array.set(rGp, c, array.get(rGp, c) + r)
                else
                    array.set(rGl, c, array.get(rGl, c) - r)
                if array.get(lH2, c)
                    array.set(h2N, c, array.get(h2N, c) + 1)
                    if r > 0
                        array.set(h2Gp, c, array.get(h2Gp, c) + r)
                    else
                        array.set(h2Gl, c, array.get(h2Gl, c) - r)
                else
                    array.set(h1N, c, array.get(h1N, c) + 1)
                    if r > 0
                        array.set(h1Gp, c, array.get(h1Gp, c) + r)
                    else
                        array.set(h1Gl, c, array.get(h1Gl, c) - r)
                array.set(lCnt, c, cnt + 1)
                array.set(lPos, c, 0)
                p := 0
        if p == 0 and inWindow and not na(atr) and atr > 0
            int d = allowLong and fN > sN and fP <= sP ? 1 : allowShort and fN < sN and fP >= sP ? -1 : 0
            if d != 0
                array.set(lPos, c, d)
                array.set(lEp, c, close)
                array.set(lDist, c, atr * slMult)
                array.set(lSt, c, close - d * atr * slMult)
                array.set(lH2, c, h2Now)
    pF := labF
    pS := labS
 
    // MA Lab modu: pozisyon kapalıyken, O ANA KADAR kapanmış işlemlere bakarak en iyi çifte geçer (geleceği görmez)
    if isLabMode and pos == 0
        float curPf  = math.min(array.get(lCnt, curC), labN) >= labMinN ? f_labPf(array.get(rGp, curC), array.get(rGl, curC)) : -1.0
        int   best   = -1
        float bestPf = -1.0
        for c = 0 to 299
            if math.min(array.get(lCnt, c), labN) >= labMinN
                float pfc = f_labPf(array.get(rGp, c), array.get(rGl, c))
                if pfc > bestPf
                    bestPf := pfc
                    best   := c
        if best >= 0 and best != curC and bestPf > curPf
            curC        := best
            labSwitches += 1
 
labPosC = labPosIn == "Sağ Üst / Top Right" ? position.top_right : labPosIn == "Sağ Alt / Bottom Right" ? position.bottom_right : labPosIn == "Sol Üst / Top Left" ? position.top_left : position.bottom_left
var string labRec    = ""
var color  labRecCol = color.gray
var table lt = table.new(labPosC, 5, 20, bgcolor=color.new(#131722, 5), border_width=1, border_color=color.new(color.gray, 60))
 
labCell(int col, int r, string t, color c) =>
    table.cell(lt, col, r, t, text_color=c, text_size=size.tiny, text_halign=text.align_left)
 
if barstate.islast and labOn
    table.clear(lt, 0, 0, 4, 19)
    float[] score = array.new<float>(300, -1.0)
    for c = 0 to 299
        int k = math.min(array.get(lCnt, c), labN)
        array.set(score, c, k >= labMinN ? f_labPf(array.get(rGp, c), array.get(rGl, c)) : -1.0)
    int[] ord = array.sort_indices(score, order.descending)
 
    table.cell(lt, 0, 0, tx("MA LAB · son ", "MA LAB · last ") + str.tostring(labN) + tx(" işlem PF sıralaması", " trades, ranked by PF"), bgcolor=color.new(#7e57c2, 20), text_color=color.white, text_size=size.tiny)
    table.merge_cells(lt, 0, 0, 4, 0)
    labCell(0, 1, "#", color.gray)
    labCell(1, 1, tx("Çift", "Pair"), color.gray)
    labCell(2, 1, tx("PF (işlem)", "PF (n)"), color.gray)
    labCell(3, 1, tx("Ort. R", "Avg R"), color.gray)
    labCell(4, 1, tx("1. Yarı | 2. Yarı PF", "1st | 2nd Half PF"), color.gray)
 
    int lrow = 2
    for k = 0 to labTop - 1
        int c = array.get(ord, k)
        if array.get(score, c) < 0
            break
        float pf  = array.get(score, c)
        int   n   = math.min(array.get(lCnt, c), labN)
        float avg = array.get(rS, c) / n
        int   n1  = array.get(h1N, c)
        int   n2  = array.get(h2N, c)
        float p1  = f_labPf(array.get(h1Gp, c), array.get(h1Gl, c))
        float p2  = f_labPf(array.get(h2Gp, c), array.get(h2Gl, c))
        string hTxt = (n1 < 10 ? "–" : str.tostring(p1, "#.##")) + " | " + (n2 < 10 ? "–" : str.tostring(p2, "#.##")) + " (" + str.tostring(n1) + "/" + str.tostring(n2) + ")"
        color  hCol = n1 < 10 or n2 < 10 ? color.gray : p1 >= 1.2 and p2 >= 1.2 ? #26a69a : p1 >= 1 and p2 >= 1 ? color.orange : #ef5350
        labCell(0, lrow, str.tostring(k + 1), color.gray)
        labCell(1, lrow, array.get(cNm, c), color.white)
        labCell(2, lrow, str.tostring(pf, "#.##") + " (" + str.tostring(n) + ")", pf >= 1.5 ? #26a69a : pf >= 1 ? color.orange : #ef5350)
        labCell(3, lrow, str.tostring(avg, "+0.00;-0.00") + "R", avg > 0 ? #26a69a : #ef5350)
        labCell(4, lrow, hTxt, hCol)
        lrow += 1
 
    // Öneri: son N'de PF'si en yüksek ve grafiğin İKİ YARISINDA da PF ≥ 1.2 olan ilk çift
    int  recC     = -1
    bool recSolid = false
    for k = 0 to 299
        int c = array.get(ord, k)
        if array.get(score, c) < 0
            break
        if array.get(h1N, c) >= 10 and array.get(h2N, c) >= 10 and f_labPf(array.get(h1Gp, c), array.get(h1Gl, c)) >= 1.2 and f_labPf(array.get(h2Gp, c), array.get(h2Gl, c)) >= 1.2
            recC     := c
            recSolid := true
            break
    if recC < 0 and array.get(score, array.get(ord, 0)) >= 0
        recC := array.get(ord, 0)
    labRec    := recC < 0 ? tx("yeterli işlem yok", "not enough trades") : array.get(cNm, recC) + " · PF " + str.tostring(array.get(score, recC), "#.##") + (recSolid ? " ✓" : tx(" ⚠ yarılardan biri zayıf", " ⚠ one half weak"))
    labRecCol := recC < 0 ? color.gray : recSolid ? color.rgb(255, 215, 0) : color.orange
 
    int iTF = array.indexof(LAB_T, fastType)
    int iTS = array.indexof(LAB_T, slowType)
    int iF  = array.indexof(LAB_FL, fastLen)
    int iS  = array.indexof(LAB_SL, slowLen)
    int act = isLabMode ? curC : iTF >= 0 and iTS >= 0 and iF >= 0 and iS >= 0 ? ((iTF * 5 + iTS) * 3 + iF) * 4 + iS : -1
    string actTxt = act < 0 ? tx("aktif çift tabloda yok", "active pair not in grid") : array.get(score, act) < 0 ? array.get(cNm, act) + tx(" · az işlem", " · few trades") : array.get(cNm, act) + " · #" + str.tostring(array.indexof(ord, act) + 1) + " / 300 · PF " + str.tostring(array.get(score, act), "#.##")
    table.cell(lt, 0, lrow, tx("Aktif: ", "Active: ") + actTxt, text_color=color.yellow, text_size=size.tiny, text_halign=text.align_left)
    table.merge_cells(lt, 0, lrow, 4, lrow)
    lrow += 1
    table.cell(lt, 0, lrow, tx("Basit test: kesişim girişi + rejim çıkışı + stop. Yarılar = grafiğin ilk ve ikinci yarısı; ikisi de iyiyse çift sağlamdır.", "Simple test: cross entry + regime exit + stop. Halves = first and second half of the chart; both good = robust pair."), text_color=color.gray, text_size=size.tiny, text_halign=text.align_left)
    table.merge_cells(lt, 0, lrow, 4, lrow)
 
// ============================================================================
// PANEL
// ============================================================================
txtSize = panelSize == "Küçük / Tiny" ? size.tiny : panelSize == "Orta / Small" ? size.small : size.normal
pPos    = panelPos == "Sağ Üst / Top Right" ? position.top_right : panelPos == "Sağ Alt / Bottom Right" ? position.bottom_right : panelPos == "Sol Üst / Top Left" ? position.top_left : position.bottom_left
 
var table tb = table.new(pPos, 2, 20, bgcolor=color.new(#1e222d, 10), border_width=1, border_color=color.new(color.gray, 60))
 
pct(string v) => isTR ? "%" + v : v + "%"
 
fR(float x) => na(x) ? "—" : str.tostring(x, "+0.00;-0.00") + "R"
 
row(int r, string lbl, string val, color col) =>
    table.cell(tb, 0, r, lbl, text_color=color.gray, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 1, r, val, text_color=col, text_size=txtSize, text_halign=text.align_left)
 
bool isMobile = panelMode == "Mobil / Mobile"
 
// --- Mobil panel: tek sütun, kısa satırlar
if barstate.islast and showPanel and isMobile
    int   mn  = array.size(aR)
    float mS  = 0.0
    float mGp = 0.0
    float mGl = 0.0
    if mn > 0
        for i = 0 to mn - 1
            float r = array.get(aR, i)
            mS += r
            if r > 0
                mGp += r
            else
                mGl += -r
    float mAvg  = mn > 0 ? mS / mn : na
    float mPf   = mGl > 0 ? mGp / mGl : na
    float mDist = pos != 0 ? stopDist : atr * slMult
    float mQty  = mDist > 0 and acct > 0 ? (acct * riskPct / 100) / mDist : na
 
    string mHead = str.tostring(fastLen) + "/" + str.tostring(slowLen) + " · " + mktName + (isStd ? " · " + styleName + (styleMatch ? " ✓" : " ⚠ " + styleRange) : "")
    string mTr   = (trendBull ? "▲ " : "▼ ") + trendType + " " + str.tostring(trendLen)
    string mPos  = pos == 1 ? "L " + str.tostring(entryPx, format.mintick) + " · SL " + str.tostring(slLvl, format.mintick) + (added ? " +E" : "") : pos == -1 ? "S " + str.tostring(entryPx, format.mintick) + " · SL " + str.tostring(slLvl, format.mintick) + (added ? " +E" : "") : tx("NAKİT", "CASH")
    string mRes  = fR(mAvg) + " · PF " + (na(mPf) ? "—" : str.tostring(mPf, "#.##"))
    string mCnt  = str.tostring(mn) + tx(" işlem", " trades") + " · DD " + str.tostring(maxDD, "#.#") + "R"
    string mSize = tx("Boyut ", "Size ") + (na(mQty) ? "—" : str.tostring(mQty, "#.####"))
 
    table.cell(tb, 0, 0, mHead, bgcolor=color.new(#2962ff, 20), text_color=color.white, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 0, 1, mTr, text_color=trendBull ? color.green : color.red, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 0, 2, mPos, text_color=pos == 1 ? color.green : pos == -1 ? color.red : color.gray, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 0, 3, mSize, text_color=color.white, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 0, 4, mRes, text_color=na(mAvg) ? color.gray : mAvg > 0 ? #26a69a : #ef5350, text_size=txtSize, text_halign=text.align_left)
    if isLabMode
        table.cell(tb, 0, 6, "MA Lab · " + str.tostring(labSwitches) + tx(" değişim", " switches"), text_color=color.rgb(255, 215, 0), text_size=txtSize, text_halign=text.align_left)
    else if labOn
        table.cell(tb, 0, 6, "Lab: " + labRec, text_color=labRecCol, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 0, 5, mCnt, text_color=mn < 30 ? color.orange : color.gray, text_size=txtSize, text_halign=text.align_left)
 
// --- Sade / Detaylı panel
if barstate.islast and showPanel and not isMobile
    int   n    = array.size(aR)
    float sumR = 0.0
    float gp   = 0.0
    float gl   = 0.0
    float best = na
    int   wins = 0
    float sL = 0.0
    float sS = 0.0
    int   nL = 0
    int   nS = 0
    float s0 = 0.0
    float s1 = 0.0
    float s2 = 0.0
    int   n0 = 0
    int   n1 = 0
    int   n2 = 0
    float h1 = 0.0
    float h2 = 0.0
    int   half = math.floor(n / 2)
 
    if n > 0
        for i = 0 to n - 1
            float r  = array.get(aR, i)
            int   ty = array.get(aType, i)
            int   dr = array.get(aDir, i)
            sumR += r
            if r > 0
                wins += 1
                gp   += r
            else
                gl   += -r
            best := na(best) ? r : math.max(best, r)
            if dr == 1
                sL += r
                nL += 1
            else
                sS += r
                nS += 1
            if ty == 0
                s0 += r
                n0 += 1
            else if ty == 1
                s1 += r
                n1 += 1
            else
                s2 += r
                n2 += 1
            if i < half
                h1 += r
            else
                h2 += r
 
    float top5 = na
    if n > 5
        srt = array.copy(aR)
        array.sort(srt, order.descending)
        float s = 0.0
        for i = 5 to n - 1
            s += array.get(srt, i)
        top5 := s / (n - 5)
 
    float avgR = n > 0 ? sumR / n : na
    float wr   = n > 0 ? wins * 100.0 / n : na
    float pf   = gl > 0 ? gp / gl : na
 
    // Pozisyon büyüklüğü
    float curDist  = pos != 0 ? stopDist : atr * slMult
    float riskAmt  = acct * riskPct / 100
    float qty      = curDist > 0 ? riskAmt / curDist : na
    float notional = qty * close
 
    string head = modeName + " · " + mktName
    table.cell(tb, 0, 0, "SMART MA", bgcolor=color.new(#2962ff, 20), text_color=color.white, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 1, 0, head, bgcolor=color.new(#2962ff, 20), text_color=color.yellow, text_size=txtSize, text_halign=text.align_left)
 
    row(1, tx("Ortalama", "MA Pair"), pairText, color.white)
    if isLabMode
        row(19, tx("Lab Seçimi", "Lab Mode"), tx("canlı seçim · ", "walk-forward · ") + str.tostring(labSwitches) + tx(" değişim", " switches"), color.rgb(255, 215, 0))
    else if labOn
        row(19, tx("Lab Önerisi", "Lab Pick"), labRec, labRecCol)
    if isStd
        row(18, tx("Tarz", "Style"), styleTag + (styleMatch ? "" : tx("  (grafik dilimi uymuyor)", "  (chart TF mismatch)")), styleMatch ? color.rgb(255, 215, 0) : color.orange)
 
    string trTxt = (trendBull ? "▲ " : "▼ ") + trendType + " " + str.tostring(trendLen) + (useHtfTr ? " · " + (htf == "D" ? "1D" : htf == "W" ? "1W" : htf == "240" ? "4H" : "1H") : "") + (useTrendFilter ? tx(" · filtre", " · filter") : "")
    row(2, tx("Genel Trend", "Major Trend"), trTxt, trendBull ? color.green : color.red)
 
    string posCore = str.tostring(entryPx, format.mintick) + " · SL " + str.tostring(slLvl, format.mintick) + (added ? " · +E" : "")
    string posTxt  = pos == 1 ? "LONG 🟢 " + posCore : pos == -1 ? "SHORT 🔴 " + posCore : tx("NAKİT ⚪", "CASH ⚪")
    row(3, tx("Pozisyon", "Position"), posTxt, pos == 1 ? color.green : pos == -1 ? color.red : color.gray)
 
    string sizeTxt = na(qty) or acct <= 0 ? "—" : str.tostring(qty, "#.####") + tx(" adet · ", " units · ") + str.tostring(notional, "#,###") + " " + syminfo.currency + " (" + pct(str.tostring(riskPct, "#.##")) + ")"
    row(4, tx("Boyut", "Size"), sizeTxt, color.white)
 
    row(5, tx("Ort. R | Kazanma", "Avg R | Win"), fR(avgR) + " | " + (na(wr) ? "—" : pct(str.tostring(wr, "#.#"))), na(avgR) ? color.gray : avgR > 0 ? #26a69a : #ef5350)
    row(6, "PF | Max DD", (na(pf) ? "—" : str.tostring(pf, "#.##")) + " | " + fR(maxDD), na(pf) ? color.gray : pf >= 1.5 ? #26a69a : pf >= 1 ? color.orange : #ef5350)
 
    if panelMode == "Detaylı / Detailed"
        row(7, tx("İşlem", "Trades"), str.tostring(n) + (n < 30 ? tx("  ⚠ az veri", "  ⚠ small sample") : ""), n < 30 ? color.orange : color.white)
        row(8, tx("Toplam R | En İyi", "Total R | Best"), fR(sumR) + " | " + fR(best), sumR > 0 ? #26a69a : #ef5350)
        row(9, tx("Top 5 Hariç", "Excl. Top 5"), fR(top5), na(top5) ? color.gray : top5 > 0 ? #26a69a : #ef5350)
        row(10, tx("İlk Yarı | Son Yarı", "1st Half | 2nd Half"), fR(h1) + " | " + fR(h2), h2 > 0 ? #26a69a : #ef5350)
        row(11, "Long | Short", fR(sL) + " (" + str.tostring(nL) + ") | " + fR(sS) + " (" + str.tostring(nS) + ")", color.white)
        row(12, tx("Momentum", "Momentum"), fR(s0) + " (" + str.tostring(n0) + ")" + (n0 > 0 ? " · ort " + fR(s0 / n0) : ""), s0 >= 0 ? #26a69a : #ef5350)
        row(13, tx("Düzeltme", "Pullback"), fR(s1) + " (" + str.tostring(n1) + ")" + (n1 > 0 ? " · ort " + fR(s1 / n1) : ""), s1 >= 0 ? #26a69a : #ef5350)
        row(14, tx("Yeniden Giriş", "Re-Entry"), fR(s2) + " (" + str.tostring(n2) + ")", s2 >= 0 ? #26a69a : #ef5350)
        row(15, tx("Ekleme · net katkı", "Add · net contribution"), useAdd ? fR(addContrib) + " (" + str.tostring(addCount) + ")" : tx("kapalı", "off"), addContrib >= 0 ? #26a69a : #ef5350)
        row(16, tx("Maliyet | Min. Fark", "Cost | Min Gap"), pct(str.tostring(costPct, "#.###")) + " | " + pct(str.tostring(minGap, "#.##")), color.orange)
        string dirTxt = (allowLong and allowShort ? "Long & Short" : allowLong ? tx("Sadece Long", "Long only") : tx("Sadece Short", "Short only")) + (dirMode == "Oto / Auto" ? " · OTO" : "") + (shortWarn ? tx("  ⚠ short bu piyasada negatif ölçüldü", "  ⚠ shorts tested negative here") : "")
        row(17, tx("Yön", "Direction"), dirTxt, shortWarn ? color.orange : color.rgb(255, 215, 0))
 
// ============================================================================
// ALARMLAR
// ============================================================================
fmtMsg(string m) =>
    string r = str.replace_all(m, "{{ticker}}", syminfo.ticker)
    r := str.replace_all(r, "{{exchange}}", syminfo.prefix)
    r := str.replace_all(r, "{{close}}", str.tostring(close))
    r
 
if longSig
    alert(fmtMsg(msgLong), alert.freq_once_per_bar_close)
if shortSig
    alert(fmtMsg(msgShort), alert.freq_once_per_bar_close)
if exitNow
    alert(fmtMsg(msgExit), alert.freq_once_per_bar_close)
 
alertcondition(longSig,  title="▲ Long",            message="LONG {{ticker}} {{close}}")
alertcondition(shortSig, title="▼ Short",           message="SHORT {{ticker}} {{close}}")
alertcondition(exitNow,  title="✖ Çıkış / Exit",    message="EXIT {{ticker}} {{close}}")

← 返回列表