Untitled

 avatar
unknown
plain_text
24 days ago
61 kB
7
Indexable
//@version=5
var string strategyName = "Kule Dönence Str TP v3 LS_RDO"

strategy(strategyName
         , shorttitle           = strategyName 
         , overlay              = true 
         , initial_capital      = 50000
         , default_qty_type     = strategy.cash
         , default_qty_value    = 50000
         , pyramiding           = 0
         , commission_value     = 0.03
         , commission_type      = strategy.commission.percent)

enum islemYonuEnums
    longEnum    = "Long"
    shortEnum   = "Short"
    bothEnum    = "Both"

enum tpHedefEnums
    kisaTPEnum      = "Kısa TP"
    ortaTPEnum      = "Orta TP"
    uzunTPEnum      = "Uzun TP"

enum girisTipiEnums
    tutarEnum   = "Tutar"
    adetEnum    = "Adet"


// İşlem yönü seçim menüsü eklendi
grGenel = "🔄 Genel Ayarlar 🔄"
grGiris = "💰 Giriş Miktarı Ayarları 💰"
grOnay = "🔍 İşlem Onay Ayarları 🔍"
grAlgo = "💵 Algo Ayarları 💵"
grTablolar = "🔍 Tablo Ayarları 🔍"
grHacimTablo = "🔍 Hacim Tablo 🔍"

islemYonu = input.enum(title="İşlem Yönü", defval = islemYonuEnums.longEnum, tooltip="İşlemlerin hangi yönde yapılacağını seçin: Long (Alış), Short (Satış) veya Both (Her İki Yön)", group=grGenel, inline = "grupAyarlari")
tpHedefi = input.enum(title="      TP Hedefi  ", display = display.none, defval= tpHedefEnums.kisaTPEnum, tooltip="İşlem Yönü : İşlemlerin hangi yönde yapılacağını seçin: Long (Alış), Short (Satış) veya Both (Her İki Yön)\n\nTP Hedefi: Take Profit hedefi mesafesini seçin: Kısa VADE, Orta VADE veya Uzun VADE", group=grGenel, inline = "grupAyarlari")

// Giriş miktarı seçim grubu
// ATR çarpanı için dropdown menü eklendi
girisTipi = input.enum(title="Giriş Tipi  ", display = display.none, defval= girisTipiEnums.tutarEnum, tooltip="İşleme giriş yöntemini seçin: Tutar (TL bazında) veya Adet (Sabit lot sayısı)", group=grGenel, inline = "GirişAyarlari")
girisDegeri = input.float(title="      Giriş Değeri",    defval=50000,    minval=1,     group=grGenel,     tooltip="Giriş Tipi : İşleme giriş yöntemini seçin: Tutar (TL bazında) veya Adet (Sabit lot sayısı)\n\nGiriş Değeri: Seçilen giriş tipine göre: Tutar (TL) veya Adet (Lot)", inline = "GirişAyarlari")
// TP1 ve TP2 aktifleştirme seçenekleri eklendi
tp1Aktif = true
tp2Aktif = true
tp1Oran = input.float(0.32, title="TP1 Oranı ", display = display.none, minval=0.0, maxval=1.0, step=0.01, group=grGenel, inline = "TP Ayarlari")
tp2Oran = input.float(0.32, title="      TP2 Oranı  ",display = display.none, minval=0.0, maxval=1.0, step=0.01, group=grGenel, inline = "TP Ayarlari")

// Fiyat onaylama için bar sayısı parametresi eklendi
barKontrol = input.bool(title="Giriş Bar Onayı Aktif      ", display = display.none, defval=true, tooltip="İşleme girmeden önce fiyat onayı kontrolünü aktifleştirir", group=grOnay, inline = "barKontrol")
barKontrolCikis = input.bool(title="Çıkış Bar Onayı Aktif", display = display.none, defval=true, tooltip="Giriş Bar Onayı: İşleme girmeden önce fiyat onayı kontrolünü aktifleştirir\n\nÇıkış Bar Onayı: İşlemden çıkmadan önce fiyat onayı kontrolünü aktifleştirir", group=grOnay, inline = "barKontrol")
// barSayisiCikis = input.int(title="Çıkış İçin Bar Sayısı",display = display.none,  defval=2, minval=0, maxval=10, tooltip="Çıkış için kaç bar sonra kontrolleri yapacak", group=grOnay)
// barSayisi = input.int(title="Giriş İçin Bar Sayısı",display = display.none,  defval=2, minval=0, maxval=10, tooltip="Giriş için kaç bar sonra kontrolleri yapacak", group=grOnay)
barSayisiCikis = 2
barSayisi = 2
showtrend = true
showbc = input(true, title='Bar Boyama Göster?',  display = display.none, group=grOnay)

// Günlük yüzde değişim kontrolü için açma/kapama düğmesi
enablePercentCheck = input.bool(false, "Günlük % Değişim Kontrolünü Etkinleştir",  display = display.none, group=grOnay, inline = "Değişim")
yuzdeLimit = input.float(8.0, "",  display = display.none, minval=1.0, maxval=20.0, step=0.5, group=grOnay, inline = "Değişim")
// Günlük yüzde değişimi hesapla - gerçek günlük değişim
// Günün başındaki değeri al (günlük time frame için)
dayStartPrice = request.security(syminfo.tickerid, "D", open[0], lookahead=barmerge.lookahead_on)
// Günlük yüzde değişimi hesapla
dailyPercentChange = ((close - dayStartPrice) / dayStartPrice) * 100

APIKEY = input.string(title="API Key  ",  display = display.none,  defval="", inline = "Algo Ayarlari", group = grAlgo)
TOKEN = input.string(title="      TOKEN   ",  display = display.none, defval="", inline = "Algo Ayarlari", group = grAlgo)
startDate = input.time(timestamp("2024-08-01"), "Başlama Tarihi", group = grAlgo)
endDate = input.time(timestamp("2025-12-31"), "Bitiş Tarihi", group = grAlgo)

var float islemLotu = na      
var float sonGirisLotu = na   
var int pozisyonDurumu = 0    

// Lot hesaplama işlevi - giriş tipine göre hesaplama yapılır
lotHesapla() =>
    if girisTipi == girisTipiEnums.tutarEnum
        math.round(girisDegeri / close)  // Tutar/fiyat ile lot hesaplanır ve yuvarlanır
    else
        math.round(girisDegeri)  // Doğrudan adet değeri kullanılır (integer olması için yuvarlanır)

// ---------------------------- Theme --------------------------------------- //
// Colors
red = color.red
green = color.rgb(21, 194, 122)
brightred = color.rgb(158, 43, 35)
brightgreen = color.rgb(21, 194, 122)
cautioncol = color.yellow
gray= color.gray
aqua = color.aqua
orange= color.orange
darkgreen = color.rgb(21, 194, 122)
darkred = color.rgb(165, 57, 66)

// Groups 
grma = "📈 Moving Averages 📈"
grhts = "Trend Seviyeleri"
grt = "DCA"
grll = "🩸 Leverage Liquidations 🩸"
gla= "🔔 Alerts 🔔"

// Constants
dataType = "Custom"
instructions = "Off"
smaS = "Off"
constant = 1>0
rsi=ta.rsi(close,14)

// ------------------------- Trend State ------------------------------------ //
// Code Author: © Koalafied_3

// // Define inpputs with default values
// ts1 = input.int(67, title="TS1 Period", minval=1)
// ts2 = input.int(33, title="TS2 Period", minval=1)

ts1 = 67
ts2 = 33.33333333
ts1a = 61
ts2a = 39
// Trend State
var state = 0
if ta.crossover(rsi, ts1) 
    state := 1
    state
if ta.crossunder(rsi, ts2)  
    state := 2
    state
state := state

//-----------------3 State RSI Gradient Bar Color on Chart--------------------//
cbullu = brightgreen
cbulld = darkgreen
cbearu = brightred
cbeard = darkred
cbearc = brightgreen
cbullc = brightred 

barcolor(state==1 and rsi>50?cbullu: state==1 and rsi<50?cbulld: state==2 and rsi<50 ?cbearu: state==2 and rsi>50 ?cbeard:color.new(color.from_gradient(rsi, ts2, ts1, cbearu, cbullu),0),title="Chart Bar Color", display = showbc ? display.all : display.none, editable=false)

// Define a bull/bear cross
bullcross= state==1 and state[1]==2
bearcross= state==2 and state[1]==1

// Detect what was last signal (long or short)
long_short = 0
long_last = bullcross and (nz(long_short[1]) == 0 or nz(long_short[1]) == -1)
short_last = bearcross and (nz(long_short[1]) == 0 or nz(long_short[1]) == 1)
long_short := long_last ? 1 : short_last ? -1 : long_short[1]

// Remove first bar for SL/TP (you can't enter a trade at bar close and THEN hit your SL on that same bar)
longBar1 = ta.barssince(long_last)
longBar2 = longBar1 >= 1 ? true : false
shortBar1 = ta.barssince(short_last)
shortBar2 = shortBar1 >= 1 ? true : false

// ATR hesaplama yöntemi için seçenekler
atr_method = 'hl2'

// ATR kaynağı (srcATR) - Kullanıcının seçimine göre hesaplanır
var float srcATR = na
if atr_method == "close"
    srcATR := close
else if atr_method == "hl2"
    srcATR := (high + low) / 2
else if atr_method == "hlc3"
    srcATR := (high + low + close) / 3

// ATR periyodu
atrPeriod = 9
per = atrPeriod


// TP seçeneğine göre ATR çarpanı belirleme
atrMultiplier = tpHedefi == tpHedefEnums.uzunTPEnum ? 9 : tpHedefi == tpHedefEnums.ortaTPEnum ? 6.35 : 3.7  // Uzun için 9, Orta için 6.35, Kısa için 3.7

// ATR hesaplama
atr_value = ta.atr(per)

// ATR çarpanı ile çarpılmış değer
atr_multiplied = atr_value * atrMultiplier

atr = ta.atr(atrPeriod)
ATRupper=srcATR + atr * atrMultiplier
ATRlower=srcATR - atr * atrMultiplier
ATRupper2=srcATR + atr * (atrMultiplier*6)
ATRlower2=srcATR - atr * (atrMultiplier*6)
ATRupper3=srcATR + atr * (atrMultiplier*4)
ATRlower3=srcATR - atr * (atrMultiplier*4)
ATRupper4=srcATR + atr * (atrMultiplier*2)
ATRlower4=srcATR - atr * (atrMultiplier*2)
bearse3=srcATR + atr * (atrMultiplier*0.5)
bullse3=srcATR - atr * (atrMultiplier*0.5)

ATRbulltp1=ta.valuewhen(bullcross,ATRupper4,0)
ATRbeartp1=ta.valuewhen(bearcross,ATRlower4,0)
ATRbulltp2=ta.valuewhen(bullcross,ATRupper3,0)
ATRbeartp2=ta.valuewhen(bearcross,ATRlower3,0)
ATRbulltp3=ta.valuewhen(bullcross,ATRupper3,0)
ATRbeartp3=ta.valuewhen(bearcross,ATRlower3,0)
ATRbulltp4=ta.valuewhen(bullcross,ATRupper4,0)
ATRbeartp4=ta.valuewhen(bearcross,ATRlower4,0)
vwbearse3=ta.valuewhen(bearcross,bearse3,0)
vwbullse3=ta.valuewhen(bullcross,bullse3,0)

bgrad = 80
tgrad = 95

exin = state==1 and long_short==1?ATRbulltp1:state==2 and long_short==-1?ATRbeartp1:na
excol = long_short == 1 and close<ATRbulltp1?green: long_short==-1 and close>ATRbeartp1?red:color.yellow
dca3in=state==1 and long_short==1?vwbullse3:state==2 and long_short==-1?vwbearse3:na
bgcol2 = state==1 and state[1]==2 ?color.green : state==2 and state[1]==1 ? color.red :na

// trend Alarm Koşulları
TrendAlarmal= state==1 and state[1]==2
TrendAlarmsat= state==2 and state[1]==1

longtphit = ta.crossover(high, ATRbulltp1) and longBar2
shorttphit = ta.crossunder(low, ATRbeartp1) and shortBar2

//////////////////////////////////////////////////////

// // IMBA Trend Line hesaplama ve plot etme kodu
// // Yuvarlama fonksiyonu
// RoundUp(number, decimals) =>
//     factor = math.pow(10, decimals)
//     math.ceil(number * factor) / factor

// // Risk-reward hesaplama fonksiyonu 
// calc_rr(float entry_price, float sl_price, float take_price) => 
//     entry_price > sl_price ? (take_price - entry_price) / (entry_price - sl_price) : (entry_price - take_price) / (sl_price - entry_price)

// // IMBA Trend Line oluşturma fonksiyonu
// create_trend_line(float sensitivity, float fib) =>
//     high_line = ta.highest(high, int(sensitivity))
//     low_line = ta.lowest(low, int(sensitivity))
//     channel_range = high_line - low_line
//     high_line - channel_range * fib

// // Ana hesaplama kodu
// sensitivity = 100  // Fixed value (10 * 10)
// // Fibonacci seviyeleri ve trend line hesaplamaları
// high_line = ta.highest(high, int(sensitivity))
// low_line = ta.lowest(low, int(sensitivity))
// channel_range = high_line - low_line
// fib_236 = high_line - channel_range * 0.236
// fib_382 = high_line - channel_range * 0.382
// fib_5 = high_line - channel_range * 0.5
// fib_618 = high_line - channel_range * 0.618
// fib_786 = high_line - channel_range * 0.786
// imba_trend_line = fib_382

// // Trend belirleme
// var bool is_long_trend = false
// var bool is_short_trend = false
// var bool is_long_trend_started = false
// var bool is_short_trend_started = false
// var bool is_trend_change = false
// // Değişken tanımlamaları (kodun başına ekleyin)
// var bool can_long = false
// var bool can_short = false

// // Atama kısmında := kullanın (mevcut = yerine)
// if time >= startDate
//     can_long := close >= imba_trend_line and close >= fib_236 and not is_long_trend
//     can_short := close <= imba_trend_line and close <= fib_786 and not is_short_trend
// else
//     can_long := false
//     can_short := false  

// if can_long
//     is_long_trend := true
//     is_short_trend := false
//     is_long_trend_started := is_long_trend_started ? false : true
// else if can_short
//     is_short_trend := true
//     is_long_trend := false
//     is_short_trend_started := is_short_trend_started ? false : true
// else
//     is_trend_change := false
//     can_long := false
//     can_short := false
//     is_short_trend_started := false
//     is_long_trend_started := false

// is_trend_change := is_short_trend_started or is_long_trend_started

// // Plot işlemleri
// // Trend line 
// plot(imba_trend_line, color = is_long_trend[1] ? color.green : color.red, linewidth = 2, title="Trend 1", display = display.none)
// // Trend line 
// plot(fib_5, color = is_long_trend[1] ? color.green : color.red, linewidth = 2, title="Trend 2", display = display.none)


/////////////////////////////////////////////////////
// Mevcut Barın Zamanı
currentTime = time

// Strateji sadece belirtilen tarih aralığında çalışacak
isInDateRange = (currentTime >= startDate and currentTime <= endDate)
var bool longPositionActive = false    
var bool shortPositionActive = false    
var bool longTp1Executed = false       
var bool longTp2Executed = false 
var bool shortTp1Executed = false       
var bool shortTp2Executed = false         
var float longTp1Lot = na              
var float longTp2Lot = na 
var float shortTp1Lot = na              
var float shortTp2Lot = na               
var float longTp3Lot = na
var float shortTp3Lot = na              
var float longKalanLot = na
var float shortKalanLot = na            

// Strategy execution tracking
var bool longEntryExecuted = false
var bool longExitExecuted = false
var bool shortEntryExecuted = false
var bool shortExitExecuted = false

// Take Profit Seviyeleri (ATR Değerleri)
longTp1Level = ta.valuewhen(bullcross, ATRupper4, 0)    // Long TP1 için ATRupper4
longTp2Level = ta.valuewhen(bullcross, ATRupper3, 0)    // Long TP2 için ATRupper3
longTp3Level = ta.valuewhen(bullcross, ATRupper2, 0)    // Long TP3 için ATRupper2

shortTp1Level = ta.valuewhen(bearcross, ATRlower4, 0)   // Short TP1 için ATRlower4
shortTp2Level = ta.valuewhen(bearcross, ATRlower3, 0)   // Short TP2 için ATRlower3
shortTp3Level = ta.valuewhen(bearcross, ATRlower2, 0)   // Short TP3 için ATRlower2

// TP Hedeflerine ulaşma durumu - LONG
longTp1Hit = ta.crossover(high, longTp1Level) and longPositionActive and not longTp1Executed and longBar2 and tp1Aktif
longTp2Hit = ta.crossover(high, longTp2Level) and longPositionActive and longTp1Executed and not longTp2Executed and longBar2 and tp2Aktif

// TP Hedeflerine ulaşma durumu - SHORT
shortTp1Hit = ta.crossunder(low, shortTp1Level) and shortPositionActive and not shortTp1Executed and shortBar2 and tp1Aktif
shortTp2Hit = ta.crossunder(low, shortTp2Level) and shortPositionActive and shortTp1Executed and not shortTp2Executed and shortBar2 and tp2Aktif

// tp3Oran hesaplama (tp1 ve tp2 oranlarına bağlı)
tp3Oran = 1.0 - (tp1Aktif ? tp1Oran : 0.0) - (tp2Aktif ? tp2Oran : 0.0)

// RSI Kontrolü için açma/kapama düğmesi ve seviye giriş ekle
enableRSICheck = true
rsiLevelUp = ts1    // Long için RSI seviyesi
rsiLevelDown = ts2  // Short için RSI seviyesi
rsiLength = 14

// RSI hesapla
rsiValue = ta.rsi(close, rsiLength)

// RSI geçiş kontrolleri
rsiCrossUp = ta.crossover(rsiValue, rsiLevelUp)     // RSI yukarı kırma (Long için)
rsiCrossDown = ta.crossunder(rsiValue, rsiLevelDown) // RSI aşağı kırma (Short için)

// RSI koşulları kontrolü
var bool rsiLongConditionMet = false
var bool rsiShortConditionMet = false

if enableRSICheck
    rsiLongConditionMet := rsiCrossUp
    rsiShortConditionMet := rsiCrossDown
else
    rsiLongConditionMet := true  // RSI kontrolü devre dışıysa, koşul karşılanmış kabul et
    rsiShortConditionMet := true  // RSI kontrolü devre dışıysa, koşul karşılanmış kabul et

// Bar kontrolü için değişkenler - LONG
var bool isLongBarConfirmWaiting = false
var float longEntryBarPrice = na
var int longConfirmBarCounter = 0

// Bar kontrolü için değişkenler - SHORT
var bool isShortBarConfirmWaiting = false
var float shortEntryBarPrice = na
var int shortConfirmBarCounter = 0

// Bar kontrolü için değişkenler - LONG ÇIKIŞ
var bool isLongExitBarConfirmWaiting = false
var float longExitBarPrice = na
var int longExitConfirmBarCounter = 0

// Bar kontrolü için değişkenler - SHORT ÇIKIŞ
var bool isShortExitBarConfirmWaiting = false
var float shortExitBarPrice = na
var int shortExitConfirmBarCounter = 0

// Fiyat ve RSI kontrolü fonksiyonu - LONG için
isLongEntryConfirmed() =>
    // Bar kontrolü aktif değilse true döndür
    if not barKontrol
        true
    else
        // Onay için gerekli bar sayısı tamamlanmışsa fiyat ve RSI kontrolü yap
        longConfirmBarCounter >= barSayisi and close > longEntryBarPrice and (rsiValue >= rsiLevelUp or ta.crossover(rsiValue, rsiLevelUp))

// Fiyat ve RSI kontrolü fonksiyonu - SHORT için
isShortEntryConfirmed() =>
    // Bar kontrolü aktif değilse true döndür
    if not barKontrol
        true
    else
        // Onay için gerekli bar sayısı tamamlanmışsa fiyat ve RSI kontrolü yap
        shortConfirmBarCounter >= barSayisi and close < shortEntryBarPrice and (rsiValue <= rsiLevelDown or ta.crossunder(rsiValue, rsiLevelDown))

// Fiyat ve RSI kontrolü fonksiyonu - LONG ÇIKIŞ için
isLongExitConfirmed() =>
    // Bar kontrolü aktif değilse true döndür
    if not barKontrolCikis
        true
    else
        // Onay için gerekli bar sayısı tamamlanmışsa fiyat ve RSI kontrolü yap
        longExitConfirmBarCounter >= barSayisiCikis and close < longExitBarPrice and (rsiValue <= rsiLevelDown or ta.crossunder(rsiValue, rsiLevelDown))

// Fiyat ve RSI kontrolü fonksiyonu - SHORT ÇIKIŞ için
isShortExitConfirmed() =>
    // Bar kontrolü aktif değilse true döndür
    if not barKontrolCikis
        true
    else
        // Onay için gerekli bar sayısı tamamlanmışsa fiyat ve RSI kontrolü yap
        shortExitConfirmBarCounter >= barSayisiCikis and close > shortExitBarPrice and (rsiValue >= rsiLevelUp or ta.crossover(rsiValue, rsiLevelUp))

// İşlem sinyali oluşma koşulları

longEntrySignal = isInDateRange and bullcross and rsiLongConditionMet and not longPositionActive and (not enablePercentCheck or dailyPercentChange <= yuzdeLimit) and barstate.isconfirmed and (islemYonu == islemYonuEnums.longEnum or islemYonu == islemYonuEnums.bothEnum)

shortEntrySignal = isInDateRange and bearcross and rsiShortConditionMet and not shortPositionActive and (not enablePercentCheck or dailyPercentChange >= -yuzdeLimit) and barstate.isconfirmed and (islemYonu == islemYonuEnums.shortEnum or islemYonu == islemYonuEnums.bothEnum)

// Çıkış sinyali oluşturma için değişkenler
longExitSignal = isInDateRange and bearcross and longPositionActive
shortExitSignal = isInDateRange and bullcross and shortPositionActive

// Onaylanmış işlem sinyalleri - etiket ve çizgi oluşturmak için kullanılacak
var bool longEntrySignalConfirmed = false
var bool shortEntrySignalConfirmed = false

// LONG SİNYAL İŞLEME
// Sinyal geldiğinde bar kontrolü için değerleri ayarla - LONG
if longEntrySignal and barKontrol and not isLongBarConfirmWaiting
    isLongBarConfirmWaiting := true
    longEntryBarPrice := close
    longConfirmBarCounter := 0

// LONG Bar sayacını artır
if isLongBarConfirmWaiting
    longConfirmBarCounter := longConfirmBarCounter + 1

// SHORT SİNYAL İŞLEME
// Sinyal geldiğinde bar kontrolü için değerleri ayarla - SHORT
if shortEntrySignal and barKontrol and not isShortBarConfirmWaiting
    isShortBarConfirmWaiting := true
    shortEntryBarPrice := close
    shortConfirmBarCounter := 0

// SHORT Bar sayacını artır
if isShortBarConfirmWaiting
    shortConfirmBarCounter := shortConfirmBarCounter + 1

// LONG Kontroller tamamlandığında işleme gir
if (longEntrySignal and not barKontrol) or (isLongBarConfirmWaiting and isLongEntryConfirmed())
    // Lot hesapla fonksiyonunu çağır - LONG
    sonGirisLotu := lotHesapla()
    longKalanLot := sonGirisLotu
    
    // TP1 ve TP2 lot hesaplamaları (aktiflik durumuna göre) - LONG
    if tp1Aktif
        longTp1Lot := math.round(sonGirisLotu * tp1Oran)
    else
        longTp1Lot := 0
        
    if tp2Aktif
        longTp2Lot := math.round(sonGirisLotu * tp2Oran)
    else
        longTp2Lot := 0
        
    // Kalan lot miktarını hesapla (toplam - tp1 - tp2) - LONG
    longTp3Lot := sonGirisLotu - longTp1Lot - longTp2Lot
    
    // Strateji LONG girişi yap
    strategy.entry("Long", strategy.long, qty=sonGirisLotu)
    alert('{"name": "🚀' + "LONG İşleme girdi" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "mktbest", "price": "' + str.tostring(close) + '", "quantity": "' + str.tostring(sonGirisLotu) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
    longPositionActive := true
    longTp1Executed := false
    longTp2Executed := false
    isLongBarConfirmWaiting := false
    longEntryExecuted := true
    longExitExecuted := false
    longEntrySignalConfirmed := true

// SHORT Kontroller tamamlandığında işleme gir
if (shortEntrySignal and not barKontrol) or (isShortBarConfirmWaiting and isShortEntryConfirmed())
    // Lot hesapla fonksiyonunu çağır - SHORT
    sonGirisLotu := lotHesapla()
    shortKalanLot := sonGirisLotu
    
    // TP1 ve TP2 lot hesaplamaları (aktiflik durumuna göre) - SHORT
    if tp1Aktif
        shortTp1Lot := math.round(sonGirisLotu * tp1Oran)
    else
        shortTp1Lot := 0
        
    if tp2Aktif
        shortTp2Lot := math.round(sonGirisLotu * tp2Oran)
    else
        shortTp2Lot := 0
        
    // Kalan lot miktarını hesapla (toplam - tp1 - tp2) - SHORT
    shortTp3Lot := sonGirisLotu - shortTp1Lot - shortTp2Lot
    
    // Strateji SHORT girişi yap
    strategy.entry("Short", strategy.short, qty=sonGirisLotu)
    alert('{"name": "🚀' + "SHORT İşleme girdi" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(close) + '", "quantity": "' + str.tostring(sonGirisLotu) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
    shortPositionActive := true
    shortTp1Executed := false
    shortTp2Executed := false
    isShortBarConfirmWaiting := false
    shortEntryExecuted := true
    shortExitExecuted := false
    shortEntrySignalConfirmed := true

// Bar onayı beklerken sinyaller değişirse işlem iptali
// LONG iptal
if isLongBarConfirmWaiting and bearcross
    isLongBarConfirmWaiting := false

// SHORT iptal
if isShortBarConfirmWaiting and bullcross
    isShortBarConfirmWaiting := false

// LONG ÇIKIŞ SİNYAL İŞLEME
// Sinyal geldiğinde bar kontrolü için değerleri ayarla - LONG ÇIKIŞ
if longExitSignal and barKontrolCikis and not isLongExitBarConfirmWaiting
    isLongExitBarConfirmWaiting := true
    longExitBarPrice := close
    longExitConfirmBarCounter := 0

// LONG ÇIKIŞ Bar sayacını artır
if isLongExitBarConfirmWaiting
    longExitConfirmBarCounter := longExitConfirmBarCounter + 1

// SHORT ÇIKIŞ SİNYAL İŞLEME
// Sinyal geldiğinde bar kontrolü için değerleri ayarla - SHORT ÇIKIŞ
if shortExitSignal and barKontrolCikis and not isShortExitBarConfirmWaiting
    isShortExitBarConfirmWaiting := true
    shortExitBarPrice := close
    shortExitConfirmBarCounter := 0

// SHORT ÇIKIŞ Bar sayacını artır
if isShortExitBarConfirmWaiting
    shortExitConfirmBarCounter := shortExitConfirmBarCounter + 1
    
// Bar onayı beklerken sinyaller değişirse işlem iptali - ÇIKIŞ
// LONG ÇIKIŞ iptal
if isLongExitBarConfirmWaiting and bullcross
    isLongExitBarConfirmWaiting := false

// SHORT ÇIKIŞ iptal
if isShortExitBarConfirmWaiting and bearcross
    isShortExitBarConfirmWaiting := false

// LONG TP1 Hedefi Gerçekleştiğinde
if (isInDateRange and longTp1Hit) 
    strategy.exit("LongTP1", "Long", qty=longTp1Lot, limit=longTp1Level, comment="TP1")
    alert('{"name": "💸' + "LONG TP1 - İlk Kısmi Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(longTp1Level) + '", "quantity": "' + str.tostring(longTp1Lot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
    longKalanLot := longKalanLot - longTp1Lot
    longTp1Executed := true

// LONG TP2 Hedefi Gerçekleştiğinde
if (isInDateRange and longTp2Hit)
    strategy.exit("LongTP2", "Long", qty=longTp2Lot, limit=longTp2Level, comment="TP2")
    alert('{"name": "💸' + "LONG TP2 - İkinci Kısmi Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(longTp2Level) + '", "quantity": "' + str.tostring(longTp2Lot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
    longKalanLot := longKalanLot - longTp2Lot
    longTp2Executed := true

// SHORT TP1 Hedefi Gerçekleştiğinde
if (isInDateRange and shortTp1Hit) 
    strategy.exit("ShortTP1", "Short", qty=shortTp1Lot, limit=shortTp1Level, comment="TP1")
    alert('{"name": "💸' + "SHORT TP1 - İlk Kısmi Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "mktbest", "price": "' + str.tostring(shortTp1Level) + '", "quantity": "' + str.tostring(shortTp1Lot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
    shortKalanLot := shortKalanLot - shortTp1Lot
    shortTp1Executed := true

// SHORT TP2 Hedefi Gerçekleştiğinde
if (isInDateRange and shortTp2Hit)
    strategy.exit("ShortTP2", "Short", qty=shortTp2Lot, limit=shortTp2Level, comment="TP2")
    alert('{"name": "💸' + "SHORT TP2 - İkinci Kısmi Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "mktbest", "price": "' + str.tostring(shortTp2Level) + '", "quantity": "' + str.tostring(shortTp2Lot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
    shortKalanLot := shortKalanLot - shortTp2Lot
    shortTp2Executed := true

// Trend değişimi olduğunda önce tüm pozisyonları kapat
if bearcross or bullcross
    // Tüm pozisyonları kapat
    if strategy.position_size != 0
        strategy.close_all(comment="Poz Kapatıldı.")
        
        // Hangi yöndeki pozisyonlar kapandı bilgisini ver
        if strategy.position_size > 0
            alert('{"name": "⛔' + "Trend Değişimi - LONG Kapatıldı." + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(close) + '", "quantity": "' + str.tostring(math.abs(strategy.position_size)) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
            // Kapanış etiketi ekle
            // label.new(x=bar_index, y=low - syminfo.mintick * 5, text="LONG KAPAT\n" + str.tostring(math.abs(strategy.position_size)) + " LOT", color=color.rgb(255, 66, 66, 80), style=label.style_label_up, textcolor=color.white, size=size.normal)
        else if strategy.position_size < 0
            alert('{"name": "⛔' + "Trend Değişimi - SHORT Kapatıldı." + '", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "mktbest", "price": "' + str.tostring(close) + '", "quantity": "' + str.tostring(math.abs(strategy.position_size)) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '", "token": "' + TOKEN + '"}', alert.freq_once_per_bar_close)
            // Kapanış etiketi ekle
            // label.new(x=bar_index, y=high + syminfo.mintick * 5, text="SHORT KAPAT\n" + str.tostring(math.abs(strategy.position_size)) + " LOT", color=color.rgb(66, 144, 255, 80), style=label.style_label_down, textcolor=color.white, size=size.normal)
        
        // Tüm durum değişkenlerini sıfırla
        longPositionActive := false
        shortPositionActive := false
        longTp1Executed := false
        longTp2Executed := false
        shortTp1Executed := false
        shortTp2Executed := false
        longKalanLot := 0
        shortKalanLot := 0
        longExitExecuted := true
        shortExitExecuted := true
        longEntrySignalConfirmed := false
        shortEntrySignalConfirmed := false
        isLongExitBarConfirmWaiting := false
        isShortExitBarConfirmWaiting := false

// Stratejiye göre mum renklendirme
// Yeşil: Strateji LONG almış ve hala pozisyonda
// Mavi: Strateji SHORT almış ve hala pozisyonda
// Kırmızı: Strateji çıkış yapmış
// Gri: İşlem yok
var color_candle = color.red

if strategy.position_size > 0 or longEntryExecuted
    color_candle := #1abc9c // Yeşil - LONG pozisyonda
    longEntryExecuted := false
else if strategy.position_size < 0 or shortEntryExecuted
    color_candle := #3498db // Mavi - SHORT pozisyonda
    shortEntryExecuted := false
else if longExitExecuted or shortExitExecuted
    color_candle := #e74c3c // Kırmızı - Çıkış yapıldı
    longExitExecuted := false
    shortExitExecuted := false
else
    color_candle := color.red // Gri - İşlem yok

// Mum renklendirme - stratejiye göre
plotcandle(open, high, low, close, title = 'Strategy Candles', color = color_candle, wickcolor = color_candle, bordercolor = color_candle)

// TP çizgileri ve etiketleri oluşturma - LONG
var label longTp1Label = na
var label longTp2Label = na
var line longTp1Line = na
var line longTp2Line = na

// TP çizgileri ve etiketleri oluşturma - SHORT
var label shortTp1Label = na
var label shortTp2Label = na
var line shortTp1Line = na
var line shortTp2Line = na

// Sadece onaylanmış bir LONG giriş sinyali olduğunda TP etiketlerini ekle
if longEntrySignalConfirmed and not longEntrySignalConfirmed[1]
    // Önceki etiketleri temizle - LONG
    label.delete(longTp1Label)
    label.delete(longTp2Label)
    line.delete(longTp1Line)
    line.delete(longTp2Line)
    
    // TP1 ve TP2 için yüzde hesapla - LONG
    float longTp1Yuzde = ((longTp1Level - close) / close) * 100
    float longTp2Yuzde = ((longTp2Level - close) / close) * 100
    
    // Yeni etiketler ve çizgiler oluştur - LONG
    if tp1Aktif
        longTp1Label := label.new(x=bar_index+1, y=longTp1Level, text="LONG TP1: " + str.tostring(longTp1Level, format.mintick) + " (%" + str.tostring(math.round(longTp1Yuzde, 1)) + ")", color=#4caf4f7a, style=label.style_label_right, textcolor=color.white, size=size.normal)
        longTp1Line := line.new(x1=bar_index-10, y1=longTp1Level, x2=bar_index+15, y2=longTp1Level, color=color.green, width=1, style=line.style_dashed)
    
    if tp2Aktif
        longTp2Label := label.new(x=bar_index+1, y=longTp2Level, text="LONG TP2: " + str.tostring(longTp2Level, format.mintick) + " (%" + str.tostring(math.round(longTp2Yuzde, 1)) + ")", color=#2195f37b, style=label.style_label_right, textcolor=color.white, size=size.normal)
        longTp2Line := line.new(x1=bar_index-10, y1=longTp2Level, x2=bar_index+15, y2=longTp2Level, color=color.blue, width=1, style=line.style_dashed)

// Sadece onaylanmış bir SHORT giriş sinyali olduğunda TP etiketlerini ekle
if shortEntrySignalConfirmed and not shortEntrySignalConfirmed[1]
    // Önceki etiketleri temizle - SHORT
    label.delete(shortTp1Label)
    label.delete(shortTp2Label)
    line.delete(shortTp1Line)
    line.delete(shortTp2Line)
    
    // TP1 ve TP2 için yüzde hesapla - SHORT
    float shortTp1Yuzde = ((close - shortTp1Level) / close) * 100
    float shortTp2Yuzde = ((close - shortTp2Level) / close) * 100
    
    // Yeni etiketler ve çizgiler oluştur - SHORT
    if tp1Aktif
        shortTp1Label := label.new(x=bar_index+1, y=shortTp1Level, text="SHORT TP1: " + str.tostring(shortTp1Level, format.mintick) + " (%" + str.tostring(math.round(shortTp1Yuzde, 1)) + ")", color=#e53b3b7a, style=label.style_label_right, textcolor=color.white, size=size.normal)
        shortTp1Line := line.new(x1=bar_index-10, y1=shortTp1Level, x2=bar_index+15, y2=shortTp1Level, color=color.red, width=1, style=line.style_dashed)
    
    if tp2Aktif
        shortTp2Label := label.new(x=bar_index+1, y=shortTp2Level, text="SHORT TP2: " + str.tostring(shortTp2Level, format.mintick) + " (%" + str.tostring(math.round(shortTp2Yuzde, 1)) + ")", color=#e040407a, style=label.style_label_right, textcolor=color.white, size=size.normal)
        shortTp2Line := line.new(x1=bar_index-10, y1=shortTp2Level, x2=bar_index+15, y2=shortTp2Level, color=color.orange, width=1, style=line.style_dashed)

// Trend değişiminde etiketleri ve çizgileri temizle
// LONG için
if bearcross
    line.delete(longTp1Line)
    line.delete(longTp2Line)
    label.delete(longTp1Label)
    label.delete(longTp2Label)

// SHORT için
if bullcross
    line.delete(shortTp1Line)
    line.delete(shortTp2Line)
    label.delete(shortTp1Label)
    label.delete(shortTp2Label)

// Etiketleri her 5 barda bir güncelle (çizgileri uzat) - LONG
if longPositionActive and barstate.isconfirmed and bar_index % 5 == 0
    if not na(longTp1Line) and tp1Aktif and not longTp1Executed
        line.set_x1(longTp1Line, bar_index-10)
        line.set_x2(longTp1Line, bar_index+15)
    
    if not na(longTp2Line) and tp2Aktif and not longTp2Executed
        line.set_x1(longTp2Line, bar_index-10)
        line.set_x2(longTp2Line, bar_index+15)

// Etiketleri her 5 barda bir güncelle (çizgileri uzat) - SHORT
if shortPositionActive and barstate.isconfirmed and bar_index % 5 == 0
    if not na(shortTp1Line) and tp1Aktif and not shortTp1Executed
        line.set_x1(shortTp1Line, bar_index-10)
        line.set_x2(shortTp1Line, bar_index+15)
    
    if not na(shortTp2Line) and tp2Aktif and not shortTp2Executed
        line.set_x1(shortTp2Line, bar_index-10)
        line.set_x2(shortTp2Line, bar_index+15)

// Bar onay durumu işaretleme (debug için)
// plotshape(isLongBarConfirmWaiting, title="LONG Bar Onay Bekliyor", location=location.belowbar, color=color.green, style=shape.circle, size=size.tiny, display = display.none)
// plotshape(isShortBarConfirmWaiting, title="SHORT Bar Onay Bekliyor", location=location.abovebar, color=color.red, style=shape.circle, size=size.tiny, display = display.none)

// Bar onay durumu işaretleme (debug için) - ÇIKIŞ İÇİN
// plotshape(isLongExitBarConfirmWaiting, title="LONG Çıkış Bar Onay Bekliyor", location=location.abovebar, color=color.yellow, style=shape.xcross, size=size.tiny, display = display.none)
// plotshape(isShortExitBarConfirmWaiting, title="SHORT Çıkış Bar Onay Bekliyor", location=location.belowbar, color=color.yellow, style=shape.xcross, size=size.tiny, display = display.none)

// İşlem sinyalleri için işaretler
// plotshape(longEntrySignal and not barKontrol or (isLongBarConfirmWaiting and isLongEntryConfirmed()), title="LONG İşlem Sinyali", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
// plotshape(shortEntrySignal and not barKontrol or (isShortBarConfirmWaiting and isShortEntryConfirmed()), title="SHORT İşlem Sinyali", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

// İşlem çıkış sinyalleri için işaretler
// plotshape((longExitSignal and not barKontrolCikis) or (isLongExitBarConfirmWaiting and isLongExitConfirmed()), title="LONG Çıkış Sinyali", location=location.abovebar, color=color.purple, style=shape.triangledown, size=size.small)
// plotshape((shortExitSignal and not barKontrolCikis) or (isShortExitBarConfirmWaiting and isShortExitConfirmed()), title="SHORT Çıkış Sinyali", location=location.belowbar, color=color.purple, style=shape.triangleup, size=size.small)

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                 INTEGRATED PERFORMANCE TABLES                                                     //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// COMMON TABLE SETTINGS (CONSOLIDATED)
show_performance = input.bool(false, 'Tüm Tabloları Göster?',  display = display.none, group='PERFORMANCE SETTINGS')

// Individual table toggles
show_monthly_table = input.bool(true, 'Aylık Performans',  display = display.none, group= grTablolar, inline = "AylıkTablo")
monthly_text_size = input.session('Small', "     Boyut",  display = display.none, options=["Tiny", "Small", "Normal", "Large"], group= grTablolar,  inline = "AylıkTablo")

monthly_width = 14
monthly_height = 40

monthly_table_loc = input.session("Bottom Right", " Lokasyon",  display = display.none,  options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right", "Bottom Center", "Top Center"], group= grTablolar,  inline = "AylıkTablo")
monthly_x_offset = 0
monthly_y_offset = 0

show_metrics_table = input.bool(true, 'Metrik Performans',  display = display.none, group=grTablolar, inline = "MetrikTablo")
metrics_text_size = input.session('Normal', "    Boyut",  display = display.none, options=["Tiny", "Small", "Normal", "Large"], group= grTablolar,  inline = "MetrikTablo")
metrics_width = 2
metrics_height = 10
metrics_table_loc = input.session("Bottom Left", " Lokasyon",  display = display.none, options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right", "Bottom Center", "Top Center"], group= grTablolar,  inline = "MetrikTablo")
metrics_x_offset = 0
metrics_y_offset = 0


// show_trend_table = input.bool(true, 'Çoklu Zaman Trend',  display = display.none, group=grTablolar,  inline = "TrendTable")
// trend_text_size = input.session('Small', "   Boyut",  display = display.none, options=["Tiny", "Small", "Normal", "Large"], group= grTablolar,  inline = "TrendTable")
// trend_width = 6
// trend_height = 2

// trend_table_loc = input.session("Top Right", " Lokasyon",  display = display.none, options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right", "Bottom Center", "Top Center"], group= grTablolar,  inline = "TrendTable")
// trend_x_offset = 0
// trend_y_offset = 0


// Color settings
bg_color = color.rgb(91, 91, 94, 38)
text_head_color = #ffffff
data_text_color = color.white
border_color = color.white
profit_color = color.rgb(0, 150, 0)
loss_color = color.rgb(150, 0, 0)
neutral_color = color.rgb(0, 0, 150)

table_pos(p) => 
    switch p
        "Top Right"     => position.top_right     
        "Middle Right"  => position.middle_right   
        "Bottom Right"  => position.bottom_right  
        "Top Center"    => position.top_center    
        "Middle Center" => position.middle_center
        "Bottom Center" => position.bottom_center
        "Top Left"      => position.top_left      
        "Middle Left"   => position.middle_left 
        => position.bottom_left

table_size(s) => 
    switch s
        "Auto"   => size.auto   
        "Huge"   => size.huge   
        "Large"  => size.large  
        "Normal" => size.normal 
        "Small"  => size.small
        => size.tiny

/////////////////////////////////////////////
// MONTHLY PNL PERFORMANCE LOGIC
/////////////////////////////////////////////

// var bool new_month = na
new_month = ta.change(month) //> 0 ? true : false
newest_month = new_month and strategy.closedtrades >= 1

// profit
only_profit = strategy.netprofit
initial_balance = strategy.initial_capital

// month number
var int month_number = na
month_number := (ta.valuewhen(newest_month, month(time), 0)) //and month(time) > 1 ? (ta.valuewhen(newest_month, month(time), 0) - 1) :  12 //1 to 12

//month_year
var int month_time = na
month_time := ta.valuewhen(newest_month, time, 0) - 2419200000 

var int m_counter = 0
if newest_month
    m_counter += 1

// current month values
var bool new_year = na
new_year := ta.change(year) ? true : false
curr_m_pnl = only_profit - nz(ta.valuewhen(newest_month, only_profit, 0), 0)
curr_m_number = newest_month ? ta.valuewhen(newest_month, month(time), 0) : month(time)
curr_y_pnl = (only_profit - nz(ta.valuewhen(new_year, only_profit, 0),0)) 

var float [] net_profit_array = array.new_float()
var int [] month_array = array.new_int()
var int [] month_time_array = array.new_int()

if newest_month
    array.push(net_profit_array, only_profit)
    array.push(month_array, month_number)
    array.push(month_time_array, month_time)

var float [] y_pnl_array = array.new_float()
var int [] y_number_array = array.new_int()
var int [] y_time_array = array.new_int()

newest_year = new_year and strategy.closedtrades >= 1
get_yearly_pnl = nz(ta.valuewhen(newest_year, strategy.netprofit, 0) - nz(ta.valuewhen(newest_year, strategy.netprofit, 1), 0), 0)
get_m_year = ta.valuewhen(newest_year, year(time), 2)
get_y_time = ta.valuewhen(newest_year, time, 0)

if newest_year
    array.push(y_pnl_array, get_yearly_pnl)
    array.push(y_number_array, get_m_year)
    array.push(y_time_array, get_y_time)
    
var float monthly_profit = na
var int column_month_number = na
var int row_month_time = na
var int row_y = na

// Create monthly performance table
var monthlyTable = table.new(position = table_pos(monthly_table_loc), columns = monthly_width, rows = monthly_height, bgcolor = bg_color, border_color = border_color, border_width = 1)

if barstate.islast
// Use just:
    table.set_position(monthlyTable, table_pos(monthly_table_loc))

if barstate.islastconfirmedhistory and show_performance and show_monthly_table
    table.cell(table_id = monthlyTable, column = 0, row = 0, text = "YIL", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 1, row = 0, text = "OCK", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 2, row = 0, text = "SBT", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 3, row = 0, text = "MAR", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 4, row = 0, text = "NİS", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 5, row = 0, text = "MAY", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 6, row = 0, text = "HAZ", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 7, row = 0, text = "TEM", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 8, row = 0, text = "AUG", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 9, row = 0, text = "EYL", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 10, row = 0, text = "EKM", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 11, row = 0, text = "KAS", text_color = text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 12, row = 0, text = "ARL", text_color =text_head_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 13, row = 0, text = "YIL P/L", text_color = text_head_color, text_size=table_size(monthly_text_size))

    for i = 0 to (array.size(y_number_array) == 0 ? na : array.size(y_number_array) - 1)
        row_y := year(array.get(y_time_array, i)) - year(array.get(y_time_array, 0)) + 1
        table.cell(table_id = monthlyTable, column = 13, row = row_y, text = str.tostring(array.get(y_pnl_array , i), "##.##") + '\n' + '(' + str.tostring(array.get(y_pnl_array , i)*100/initial_balance, "##.##") + ' %)', bgcolor = array.get(y_pnl_array , i) > 0 ? profit_color : array.get(y_pnl_array , i) < 0 ? loss_color : neutral_color, text_color = data_text_color, text_size=table_size(monthly_text_size))
    
    curr_row_y = array.size(month_time_array) == 0 ? 1 : (year(array.get(month_time_array, array.size(month_time_array) - 1))) - (year(array.get(month_time_array, 0))) + 1
    table.cell(table_id = monthlyTable, column = 13, row = row_y >= 0 ? row_y + 1 : 1, text = str.tostring(curr_y_pnl, "##.##") + '\n' + '(' + str.tostring(curr_y_pnl*100/initial_balance, "##.##") + ' %)', bgcolor = curr_y_pnl > 0 ? profit_color : curr_y_pnl < 0 ? loss_color : neutral_color, text_color = data_text_color, text_size=table_size(monthly_text_size))
    
    for i = 0 to (array.size(net_profit_array) == 0 ? na : array.size(net_profit_array) - 1)
        monthly_profit := i > 0 ? (array.get(net_profit_array, i) - array.get(net_profit_array, i - 1)) : array.get(net_profit_array, i) 
        column_month_number := month(array.get(month_time_array, i)) 
        row_month_time :=((year(array.get(month_time_array, i))) - year(array.get(month_time_array, 0)) ) + 1 
        table.cell(table_id = monthlyTable, column = column_month_number, row = row_month_time, text = str.tostring(monthly_profit, "##.##") + '\n' + '(' + str.tostring(monthly_profit*100/initial_balance, "##.##") + ' %)', bgcolor = monthly_profit > 0 ? profit_color : monthly_profit < 0 ? loss_color : neutral_color, text_color = data_text_color, text_size=table_size(monthly_text_size))
        table.cell(table_id = monthlyTable, column = 0, row =row_month_time, text = str.tostring(year(array.get(month_time_array, i)), "##.##"), text_color = text_head_color, text_size=table_size(monthly_text_size))
       
    table.cell(table_id = monthlyTable, column = curr_m_number, row = nz(row_month_time) <= 0 ? 1 : row_month_time, text = str.tostring(curr_m_pnl, "##.##") + '\n' + '(' + str.tostring(curr_m_pnl*100/initial_balance, "##.##") + ' %)', bgcolor = curr_m_pnl > 0 ? profit_color : curr_m_pnl < 0 ? loss_color : neutral_color, text_color = data_text_color, text_size=table_size(monthly_text_size))
    table.cell(table_id = monthlyTable, column = 0, row =nz(row_month_time) <= 0 ? 1 : row_month_time, text = str.tostring(year(time), "##.##"), text_color = text_head_color, text_size=table_size(monthly_text_size))

//============================================================================================================================================================================
// STRATEGY PERFORMANCE TABLE LOGIC
//============================================================================================================================================================================

// Değişken tanımlamaları
var float peakEquity = na
var float maxDrawdownValue = 0.0
var float maxDrawdownPercent = 0.0
var float firstTradePrice = na

// Create performance table
var tablePerformance = table.new(position=table_pos(metrics_table_loc), columns=metrics_width, rows=metrics_height, border_color=border_color, border_width=2, bgcolor=bg_color, frame_color=color.rgb(71, 71, 71), frame_width=1)

// 📌 Adjust table position based on user setting
if barstate.islast
    table.set_position(tablePerformance, table_pos(metrics_table_loc))

// 📌 Metrikler Hesaplamaları
totalTrades = strategy.closedtrades
openTrades = strategy.opentrades
closedTrades = totalTrades - openTrades
winTrades = strategy.wintrades
loseTrades = strategy.losstrades

netProfit = strategy.netprofit
initialCapital = strategy.initial_capital
netProfitPercent = (netProfit / initialCapital) * 100

profitFactor = strategy.grossloss == 0 ? na : strategy.grossprofit / strategy.grossloss
percentProfitable = totalTrades == 0 ? na : (winTrades / totalTrades) * 100

// Drawdown hesaplamaları
peakEquity := na(peakEquity) ? strategy.equity : math.max(peakEquity, strategy.equity)
drawdown = peakEquity - strategy.equity

if drawdown > maxDrawdownValue
    maxDrawdownValue := drawdown
    maxDrawdownPercent := (maxDrawdownValue / peakEquity) * 100

// Buy & Hold hesaplamaları
if na(firstTradePrice) and strategy.position_size != 0
    firstTradePrice := close

buyHoldReturnPercent = na(firstTradePrice) ? na : ((close - firstTradePrice) / firstTradePrice) * 100
buyHoldReturnAmount = na(firstTradePrice) ? na : ((close / firstTradePrice) * initialCapital) - initialCapital

// Fill performance table
if barstate.islastconfirmedhistory and show_performance and show_metrics_table
    // Strateji İsmi ve Mevcut Pozisyon
    table.cell(tablePerformance, 0, 0, "⚙️ STRATEJİ: "+ strategyName +"", bgcolor=color.rgb(27, 27, 27, 24), text_color=text_head_color, text_size=table_size(metrics_text_size))
    if strategy.position_size > 0
        float mevcutKar = ((close - strategy.position_avg_price) / strategy.position_avg_price) * 100
        table.cell(tablePerformance, 1, 0, "LONG ▲ (" + str.tostring(mevcutKar, "#.##") + "%)", 
         bgcolor=mevcutKar > 0 ? profit_color : loss_color, text_color=data_text_color, text_size=table_size(metrics_text_size))
    else
        table.cell(tablePerformance, 1, 0, "POZİSYON YOK", bgcolor=color.rgb(27, 27, 27), text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Net Kâr + Yüzdesi
    table.cell(tablePerformance, 0, 1, "NET KAZANÇ", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 1, str.tostring(netProfit, "#.##") + " TRY (" + str.tostring(netProfitPercent, "#.##") + "%)", 
     bgcolor=netProfit > 0 ? profit_color : loss_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Maksimum Kayıp + Yüzdesi
    table.cell(tablePerformance, 0, 2, "MAKS. KAYIP", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 2, str.tostring(maxDrawdownValue, "#.##") + " TRY (" + str.tostring(maxDrawdownPercent, "#.##") + "%)", 
     bgcolor=loss_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Karlılık Oranı
    table.cell(tablePerformance, 0, 3, "KARLI %", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 3, str.tostring(percentProfitable, "#.##") + "%", 
     bgcolor=neutral_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Al Tut
    table.cell(tablePerformance, 0, 4, "AL TUT", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 4, str.tostring(buyHoldReturnAmount, "#.##") + " TRY (" + str.tostring(buyHoldReturnPercent, "#.##") + "%)", 
     bgcolor=buyHoldReturnAmount > 0 ? profit_color : loss_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Kazanç Katsayısı
    table.cell(tablePerformance, 0, 5, "KAZANÇ KTS.", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 5, str.tostring(profitFactor, "#.##"), 
     bgcolor=neutral_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Açık Pozisyonlar
    table.cell(tablePerformance, 0, 6, "AÇIK PZS.", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 6, str.tostring(openTrades), 
     bgcolor=neutral_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Kapanmış Pozisyonlar
    table.cell(tablePerformance, 0, 7, "KAPANMIŞ PZS.", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 7, str.tostring(closedTrades), 
     bgcolor=neutral_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Kazançlı Pozisyonlar
    table.cell(tablePerformance, 0, 8, "KARLI İŞL.", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 8, str.tostring(winTrades), 
     bgcolor=profit_color, text_color=data_text_color, text_size=table_size(metrics_text_size))

    // Kayıplı Pozisyonlar
    table.cell(tablePerformance, 0, 9, "ZARARLI İŞL.", bgcolor=color.rgb(27, 27, 27), text_color=text_head_color, text_size=table_size(metrics_text_size))
    table.cell(tablePerformance, 1, 9, str.tostring(loseTrades), 
     bgcolor=loss_color, text_color=data_text_color, text_size=table_size(metrics_text_size))


// //============================================================================================================================================================================
// // MULTI-TIMEFRAME TREND TABLE
// //============================================================================================================================================================================

// // Colors for trend table (can use common settings)
// bullColor = profit_color
// bearColor = loss_color
// neutralColor = color.gray

// // Function to get signals from other timeframes
// getTrendSignal(timeframe) =>
//     rsiOther = request.security(syminfo.tickerid, timeframe, ta.rsi(close, 14), barmerge.gaps_off, barmerge.lookahead_off)
//     stateOther = request.security(syminfo.tickerid, timeframe, state, barmerge.gaps_off, barmerge.lookahead_off)
    
//     // For current state only (no crosses yet)
//     signalText = stateOther == 1 ? "LONG" : stateOther == 2 ? "SHORT" : "-"
//     signalColor = stateOther == 1 ? bullColor : stateOther == 2 ? bearColor : neutralColor
    
//     signal = stateOther
    
//     [signal, signalColor, signalText]

// // Get signals for different timeframes
// [signal2m, color2m, text2m] = getTrendSignal("2")
// [signal15m, color15m, text15m] = getTrendSignal("15")
// [signal30m, color30m, text30m] = getTrendSignal("30")
// [signal1h, color1h, text1h] = getTrendSignal("60")
// [signal4h, color4h, text4h] = getTrendSignal("240")
// [signal1d, color1d, text1d] = getTrendSignal("D")

// // Create the trend table with adjusted position and size
// var trendTable = table.new(table_pos(trend_table_loc), trend_width, trend_height, border_width=1, border_color=border_color, bgcolor=bg_color)
// // Update table position based on user setting
// if barstate.islast
//     table.set_position(trendTable, table_pos(trend_table_loc))

// // Update trend table on bar close
// if barstate.islast and show_performance and show_trend_table
//     // Table headers
//     table.cell(trendTable, 0, 0, "2m", bgcolor=color.new(color.blue, 100), text_color=text_head_color, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 1, 0, "15m", bgcolor=color.new(color.blue, 100), text_color=text_head_color, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 2, 0, "30m", bgcolor=color.new(color.blue, 100), text_color=text_head_color, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 3, 0, "1h", bgcolor=color.new(color.blue, 100), text_color=text_head_color, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 4, 0, "4h", bgcolor=color.new(color.blue, 100), text_color=text_head_color, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 5, 0, "D", bgcolor=color.new(color.blue, 100), text_color=text_head_color, text_size=table_size(trend_text_size))
    
//     // Signal cells
//     table.cell(trendTable, 0, 1, text2m, bgcolor=color.new(color2m, 100), text_color=color2m, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 1, 1, text15m, bgcolor=color.new(color15m, 100), text_color=color15m, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 2, 1, text30m, bgcolor=color.new(color30m, 100), text_color=color30m, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 3, 1, text1h, bgcolor=color.new(color1h, 100), text_color=color1h, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 4, 1, text4h, bgcolor=color.new(color4h, 100), text_color=color4h, text_size=table_size(trend_text_size))
//     table.cell(trendTable, 5, 1, text1d, bgcolor=color.new(color1d, 100), text_color=color1d, text_size=table_size(trend_text_size))

showTable = input.bool(true, title="Hacim Gün Sayısı", display = display.none, group=grTablolar, inline = "HacimTablo")
string s01 = syminfo.ticker  // Mevcut grafikteki sembol kullanılır
frame_color1 = #000000
frame_width1 = 2

// Parametreler
lookbackPeriod = input.int(23, title="",  display = display.none, group=grTablolar, inline="HacimTablo")

hacimTableSize = input.session('Normal', "",  display = display.none, options=["Tiny", "Small", "Normal", "Large"], group= grTablolar,  inline = "HacimTablo")
hacimTablePosition = input.session("Top Center", "",  display = display.none, options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right", "Bottom Center", "Top Center"], group= grTablolar,  inline = "HacimTablo")

// Tablo stil ayarları için sabit değerler
tableBgColor1 = #000000
tableBorderColor1 = color.orange
tableBorderWidth1 = 2

// Renk seçenekleri için sabit değerler
headerColor = color.new(color.black, 0)
buyColor = #4caf4f69
sellColor = #ff525279
resultBuyColor = #4caf4f70
resultSellColor = #ff525260
textColor = color.white

// Hacim hesaplama fonksiyonu
calculateVolumes(closeData, volumeData) =>
    float upVolumeSum = 0.0
    float downVolumeSum = 0.0

    for i = 0 to lookbackPeriod - 1
        upVolumeSum += (closeData[i] > closeData[i + 1] ? volumeData[i] : 0)
        downVolumeSum += (closeData[i] < closeData[i + 1] ? volumeData[i] : 0)

    totalVolume = upVolumeSum + downVolumeSum
    result = upVolumeSum > downVolumeSum ? "Pozitif" : "Negatif"
    [upVolumeSum, downVolumeSum, result]

// Mevcut sembol için hacim hesaplaması
// Tablo oluştur
var table volumeTable = na
if show_performance and showTable
    [up1, down1, res1] = calculateVolumes(close, volume) 
    if na(volumeTable)
        volumeTable := table.new(position=table_pos(hacimTablePosition), columns=4, rows=2, bgcolor=tableBgColor1, border_color=tableBorderColor1, border_width=tableBorderWidth1, frame_color=frame_color1, frame_width=frame_width1)

    // Başlık satırı
    if bar_index == 0
        table.cell(volumeTable, 0, 0, "Hacim Analizi", bgcolor=headerColor, text_color=textColor, text_size=table_size(hacimTableSize))
        table.cell(volumeTable, 1, 0, "Alış Hacmi", bgcolor=headerColor, text_color=textColor, text_size=table_size(hacimTableSize))
        table.cell(volumeTable, 2, 0, "Satış Hacmi", bgcolor=headerColor, text_color=textColor, text_size=table_size(hacimTableSize))
        table.cell(volumeTable, 3, 0, "Sonuç", bgcolor=headerColor, text_color=textColor, text_size=table_size(hacimTableSize))

    // Mevcut sembol verilerini tabloya ekle
    table.cell(volumeTable, 0, 1, s01, text_color=textColor, text_size=table_size(hacimTableSize))
    table.cell(volumeTable, 1, 1, str.tostring(up1, format.volume), bgcolor=buyColor, text_color=textColor, text_size=table_size(hacimTableSize))
    table.cell(volumeTable, 2, 1, str.tostring(down1, format.volume), bgcolor=sellColor, text_color=textColor, text_size=table_size(hacimTableSize))
    table.cell(volumeTable, 3, 1, res1, bgcolor=res1 == "Pozitif" ? resultBuyColor : resultSellColor, text_color=textColor, text_size=table_size(hacimTableSize))
else
    if not na(volumeTable)
        table.delete(volumeTable)
        volumeTable := na

//@strategy_alert_message {{strategy.order.alert_message}}
Editor is loading...
Leave a Comment