Untitled

 avatar
unknown
plain_text
16 days ago
37 kB
7
Indexable
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
strategy('Kule Trend Strategy Long Multi 3TP zamansal '
         , shorttitle           = 'Kule Trend Strategy Long Multi 3TP zamansal' 
         , overlay              = true) 
        //  , initial_capital      = 10000
        //  , default_qty_type     = strategy.fixed
        //  , default_qty_value    = 500
        //  , pyramiding           = 0
        //  , commission_value     = 0.03
        //  , commission_type      = strategy.commission.percent)


tutar = input.float(title="Tutar (TL)", defval=10000, minval=1)

var float islemLotu = na      
var float sonGirisLotu = na   
var int pozisyonDurumu = 0    
lotHesapla() =>
    math.floor(tutar / close)


APIKEY = input.string(title="API Key", defval="")

// Date Input Parameters
startDate = input.time(timestamp("2024-08-01"), "Start Date")
endDate = input.time(timestamp("2025-12-31"), "End Date")




// ---------------------------- 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)


fastLength = 12
slowLength = 26
signalLength = 9


[macdLine, signalLine, _] = ta.macd(close, fastLength, slowLength, signalLength)


macdAboveZero = macdLine > signalLine

// ------------------------- Trend State ------------------------------------ //
// Code Author: © Koalafied_3
showtrend = true
showbc = input(true, title='Bar Boyama Göster?',group=grhts)
ts1 = 66
ts2 = 37
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)

// RSI 50 Line
// @ LazyBear
obLevelM = 50
src = close
length = 14
ep = 2 * length - 1
auc = ta.ema(math.max(src - src[1], 0), ep)
adc = ta.ema(math.max(src[1] - src, 0), ep)

x7 = (length - 1) * (adc * obLevelM / (100 - obLevelM) - auc)
ub4 = x7 >= 0 ? src + x7 : src + x7 * (100 - obLevelM) / obLevelM
plot(ub4, title='Rsn Mov', color=color.new(ub4>ub4[1]?color.green:ub4<ub4[1]?color.red:color.white, 25), linewidth=3,display = display.none)

// Targets
// ATR TP & SL
// 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 = 55
per = atrPeriod

// ATR çarpanı
atrMultiplier = 3

// 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*8)
ATRlower2=srcATR - atr * (atrMultiplier*8)
ATRupper3=srcATR + atr * (atrMultiplier*3)
ATRlower3=srcATR - atr * (atrMultiplier*3)
ATRupper4=srcATR + atr * (atrMultiplier*2)
ATRlower4=srcATR - atr * (atrMultiplier*2)
ATRupper5=srcATR + atr * (atrMultiplier*0.5)
ATRlower5=srcATR - atr * (atrMultiplier*0.5)
ATRupper6=srcATR + atr * (atrMultiplier*0.382)
ATRlower6=srcATR - atr * (atrMultiplier*0.382)
ATRupper7=srcATR + atr * (atrMultiplier*0.236)
ATRlower7=srcATR - atr * (atrMultiplier*0.236)
ATRupper8=srcATR + atr * (atrMultiplier*0.146)
ATRlower8=srcATR - atr * (atrMultiplier*0.146)
bearse=srcATR + atr * (atrMultiplier*0.146)
bullse=srcATR - atr * (atrMultiplier*0.146)
bearse2=srcATR + atr * (atrMultiplier*0.236)
bullse2=srcATR - atr * (atrMultiplier*0.236)
bearse3=srcATR + atr * (atrMultiplier*0.5)
bullse3=srcATR - atr * (atrMultiplier*0.5)



bgrad = 80
tgrad = 95



//-----------------------------Liquidation levels-----------------------------//
// @ mabonyi
i_show_x1 = false
i_nonlinear = false
i_maintmargin = 0.05
maint_margin = 1 - i_maintmargin
i_x1 = 100
i_showlast = 0
i_offset = 0 
i_label_offset = 0

// Calculations
f_leveraged(_price, _x) =>
    _xlong = i_nonlinear ? _x + 1 : _x
    _xshort = i_nonlinear ? _x - 1 : _x
    _liq_long = _price * (1 - 1 / _xlong * maint_margin)
    _liq_short = _price * (1 + 1 / _xshort * maint_margin)
    [_liq_long, _liq_short]

f_print(_y, _txt, _c) =>
    t = time_close + (i_offset + i_label_offset) * timeframe.multiplier * 60 * 1000
    var _lbl = label.new(t, _y, _txt, xloc.bar_time, yloc.price, color.white, label.style_none, _c, size.small)
    label.set_xy(_lbl, t, _y)
    label.set_text(_lbl, _txt)

[x1_long, x1_short] = f_leveraged(close, i_x1)



// var label dca3 = na
// if state==1 and long_short==1 and barstate.islast
//     dca3 := label.new(bar_index, y=vwbullse3, text=str.tostring(truncateprice(vwbullse3, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 0), tooltip="📍: " + str.tostring(truncateprice(vwbullse3, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.382, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(bullt8profit, pricedecimals)) + " %")
//     label.delete(dca3[1])
// if state==2 and long_short==-1 and barstate.islast
//     dca3 := label.new(bar_index, y=vwbearse3, text=str.tostring(truncateprice(vwbearse3, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 0), tooltip="📍: " + str.tostring(truncateprice(vwbearse3, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.382, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(beart8profit, pricedecimals)) + " %")
//     label.delete(dca3[1])
// var label cp = na
// if state==1 and long_short==0 and barstate.islast
//     cp := label.new(bar_index, y=high, text=str.tostring(truncateprice(bullxprofit*leverage, pricedecimals)) + " %", size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(green,0), tooltip="🚦 Giriş: " + str.tostring(truncateprice(bullentry, pricedecimals)) + "\n💵 Kar:  " + str.tostring(curbullprof, '#.##') + "\n📈 Kar Yüzde: " + str.tostring(bullcprofit*leverage, '#.## %') + (i_show_x1?("\n💯 Leverage: " + str.tostring(leverage) + "x"):na) + info) // + (automan=="Auto"?optMAtip:na) + info) //, tooltip=str.tostring(truncateprice(bullt8profit, pricedecimals)) + " %")
//     label.delete(cp[1])
// if state==2 and long_short==0 and barstate.islast
//     cp := label.new(bar_index, y=low, text=str.tostring(truncateprice(bearxprofit*leverage, pricedecimals)) + " %", size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(red,0), tooltip="🚦 Giriş: " + str.tostring(truncateprice(bearentry, pricedecimals)) + "\n💵 Kar:  " + str.tostring(curbearprof, '#.##') + "\n📈 Kar Yüzde: " + str.tostring(bearcprofit*leverage, '#.## %')+ (i_show_x1?("\n💯 Leverage: " + str.tostring(leverage) + "x"):na) + info) // + (automan=="Auto"?optMAtip:na) + info) //, tooltip=str.tostring(truncateprice(beart8profit, pricedecimals)) + " %")
//     label.delete(cp[1])
// var label liq = na
// if state==1 and long_short==1 and i_show_x1 and barstate.islast
//     liq := label.new(bar_index, y=longLiquidation, text=str.tostring(truncateprice(longLiquidation, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor= longLiquidation < vwbullse3 ? color.yellow : brightred, tooltip=lastlliq)
//     label.delete(liq[1])
// if state==2 and long_short==-1 and i_show_x1 and barstate.islast
//     liq := label.new(bar_index, y=shortLiquidation, text=str.tostring(truncateprice(shortLiquidation, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor= shortLiquidation > vwbearse3 ? color.yellow : brightred, tooltip=lastsliq)
//     label.delete(liq[1])


// Plot Trend State
barcolor(state==1 and rsi>50?brightgreen: state==1 and rsi<50?darkgreen: state==2 and rsi<50 ?brightred: state==2 and rsi>50 ?darkred:color.new(color.from_gradient(rsi, ts2, ts1, brightred, brightgreen),0),title="Chart Bar Color", display = showbc ? display.all : display.none, editable=false)


srcat = input(hl2, title='Source')
Periods = input(title='ATR Length', defval=10)
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0)
mav = input.string(title='Moving Average Type', defval='EMA', options=['SMA', 'EMA', 'WMA', 'TMA', 'VAR', 'WWMA', 'ZLEMA', 'TSF'])
lengthat = input.int(10, 'Moving Average Length', minval=1)
// Sadece kesişim sinyalleri kullanılacak
changeATR = input(title='Change ATR Calculation Method ?', defval=true)
showsupport = input(title='Show Moving Average?', defval=true)
//showsignalsk = input(title="Show Crossing Signals?", type=input.bool, defval=true)
//showsignalsc = input(title="Show Price/Pmax Crossing Signals?", type=input.bool, defval=false)
highlighting = input(title='Highlighter On/Off ?', defval=true)
// long_short parametresini kaldırdık, sadece long işlemler için

atr2 = ta.sma(ta.tr, Periods)
atrat = changeATR ? ta.atr(Periods) : atr2
valpha = 2 / (length + 1)
vud1 = srcat > srcat[1] ? srcat - srcat[1] : 0
vdd1 = srcat < srcat[1] ? srcat[1] - srcat : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz((vUD - vDD) / (vUD + vDD))
VAR = 0.0
VAR := nz(valpha * math.abs(vCMO) * srcat) + (1 - valpha * math.abs(vCMO)) * nz(VAR[1])
wwalpha = 1 / length
WWMA = 0.0
WWMA := wwalpha * srcat + (1 - wwalpha) * nz(WWMA[1])
zxLag = length / 2 == math.round(length / 2) ? length / 2 : (length - 1) / 2
zxEMAData = srcat + srcat - srcat[zxLag]
ZLEMA = ta.ema(zxEMAData, length)
lrc = ta.linreg(srcat, length, 0)
lrc1 = ta.linreg(srcat, length, 1)
lrs = lrc - lrc1
TSF = ta.linreg(srcat, length, 0) + lrs
getMA(srcat, length) =>
    ma = 0.0
    if mav == 'SMA'
        ma := ta.sma(srcat, length)
        ma

    if mav == 'EMA'
        ma := ta.ema(srcat, length)
        ma

    if mav == 'WMA'
        ma := ta.wma(srcat, length)
        ma

    if mav == 'TMA'
        ma := ta.sma(ta.sma(srcat, math.ceil(length / 2)), math.floor(length / 2) + 1)
        ma

    if mav == 'VAR'
        ma := VAR
        ma

    if mav == 'WWMA'
        ma := WWMA
        ma

    if mav == 'ZLEMA'
        ma := ZLEMA
        ma

    if mav == 'TSF'
        ma := TSF
        ma
    ma

MAvg = getMA(srcat, length)
longStop = MAvg - Multiplier * atrat
longStopPrev = nz(longStop[1], longStop)
longStop := MAvg > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = MAvg + Multiplier * atrat
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := MAvg < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir
PMax = dir == 1 ? longStop : shortStop
plot(showsupport ? MAvg : na, color=color.new(#0585E1, 0), linewidth=2, title='Moving Avg Line')
pALL = plot(PMax, color=color.new(color.white, 0), linewidth=2, title='PMax')
buySignalk = ta.crossover(MAvg, PMax)
//plotshape(buySignalk and showsignalsk ? PMax*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallk = ta.crossunder(MAvg, PMax)
//plotshape(sellSignallk and showsignalsk ? PMax*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
buySignalc = ta.crossover(src, PMax)
//plotshape(buySignalc and showsignalsc ? PMax*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
sellSignallc = ta.crossunder(src, PMax)
//plotshape(sellSignallc and showsignalsc ? PMax*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none)
longFillColor = highlighting ? MAvg > PMax ? color.green : na : na
shortFillColor = highlighting ? MAvg < PMax ? color.red : na : na
// fill(mPlot, pALL, title='UpTrend Highligter', color=longFillColor, transp=90)
// fill(mPlot, pALL, title='DownTrend Highligter', color=shortFillColor, transp=90)


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

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

// Strateji sadece belirtilen tarih aralığında çalışacak
isInDateRange = (currentTime >= startDate and currentTime <= endDate)
//////////////////////////////////////////////////////////////////   TİMUR İNCİ //////////////////////////////////////////////////////////////////////////////////////
// TP Yöntemini Seçme
tpMethod = input.string("ATR_Standart", "TP Hesaplama Yöntemi", options=["ATR_Standart", "Fibonacci", "Swing", "ADM", "Bollinger", "Pivot", "Zaman_Bazli", "Harmonik", "RSI_Bazli"])


// Diğer Hesaplama Parametreleri
lookbackPeriod = input.int(55, "Lookback Periyodu")
basisPeriod = input.int(20, "Basis Periyodu")
pivotLeftBars = input.int(5, "Pivot Sol Barlar")
pivotRightBars = input.int(5, "Pivot Sağ Barlar")

// TP Oranları
tp1Oran = input.float(0.40, "TP1 Oran", minval=0.01, maxval=1.0, step=0.01)  
tp2Oran = input.float(0.30, "TP2 Oran", minval=0.01, maxval=1.0, step=0.01)  
tp3Oran = input.float(0.30, "TP3 Oran", minval=0.01, maxval=1.0, step=0.01)  





// Pozisyon Durum Değişkenleri
var bool positionActive = false    
var bool tp1Executed = false       
var bool tp2Executed = false       
var float tp1Lot = na              
var float tp2Lot = na              
var float tp3Lot = na              
var float kalanLot = na            



// Fibonacci Uzantıları ile Hesaplama
calculateFibonacci(entryPrice) =>
    moveSize = atr * atrMultiplier
    tp1 = entryPrice + moveSize * 0.618
    tp2 = entryPrice + moveSize * 1.0
    tp3 = entryPrice + moveSize * 1.618
    [tp1, tp2, tp3]

calculateSwing() =>
    swingLow = ta.lowest(low, lookbackPeriod)
    swingHigh = ta.highest(high, lookbackPeriod)
    priceRange = swingHigh - swingLow
    entryPrice = close  // Add this line to define entryPrice
    tp1 = entryPrice + priceRange * 0.33
    tp2 = entryPrice + priceRange * 0.66
    tp3 = entryPrice + priceRange * 1.0
    [tp1, tp2, tp3]

// Ortalama Hareket Mesafesi (ADM) Kullanımı
calculateADM() =>
    dailyRange = high - low
    avgDailyRange = ta.sma(dailyRange, lookbackPeriod)
    entryPrice = close
    tp1 = entryPrice + avgDailyRange * 1.0
    tp2 = entryPrice + avgDailyRange * 2.0
    tp3 = entryPrice + avgDailyRange * 3.0
    [tp1, tp2, tp3]

// Bollinger Bantları Tabanlı Hedefler
calculateBollinger() =>
    basis = ta.sma(close, basisPeriod)
    dev = ta.stdev(close, basisPeriod)
    tp1 = basis + dev * 1
    tp2 = basis + dev * 2
    tp3 = basis + dev * 3
    [tp1, tp2, tp3]

// Pivot Noktaları Tabanlı Hedefler
calculatePivot() =>
    pivotHigh = ta.pivothigh(high, pivotLeftBars, pivotRightBars)
    pivotLow = ta.pivotlow(low, pivotLeftBars, pivotRightBars)
    var float lastPivotHigh = na
    var float lastPivotLow = na
    
    if (pivotHigh)
        lastPivotHigh := high[pivotRightBars]
    if (pivotLow)
        lastPivotLow := low[pivotRightBars]
        
    priceRange = lastPivotHigh - lastPivotLow
    entryPrice = close
    tp1 = entryPrice + priceRange * 0.33
    tp2 = entryPrice + priceRange * 0.66
    tp3 = entryPrice + priceRange * 1.0
    [tp1, tp2, tp3]

// Zaman Bazlı Faktörler Ekleme
calculateTimeBasedFactors() =>
    isVolatileSession = dayofweek == 1 or dayofweek == 5
    volatilityMultiplier = isVolatileSession ? 1.5 : 1.0
    entryPrice = close
    tp1 = entryPrice + (atr * 2 * volatilityMultiplier)
    tp2 = entryPrice + (atr * 4 * volatilityMultiplier)
    tp3 = entryPrice + (atr * 6 * volatilityMultiplier)
    [tp1, tp2, tp3]

// Harmonik Desenler ile Hedef Belirleme
calculateHarmonic() =>
    moveAB = ta.highest(high, lookbackPeriod) - ta.lowest(low, lookbackPeriod)
    entryPrice = close
    tp1 = entryPrice + moveAB * 0.382
    tp2 = entryPrice + moveAB * 0.618
    tp3 = entryPrice + moveAB * 0.786
    [tp1, tp2, tp3]

// RSI Tabanlı Dinamik Ayarlama
calculateRSIBased() =>
    rsiValue = ta.rsi(close, 14)
    rsiMultiplier = rsiValue < 37 ? 1.5 : (rsiValue > 66 ? 0.8 : 1.0)
    entryPrice = close
    tp1 = entryPrice + (atr * 2 * rsiMultiplier)
    tp2 = entryPrice + (atr * 4 * rsiMultiplier)
    tp3 = entryPrice + (atr * 6 * rsiMultiplier)
    [tp1, tp2, tp3]

// Seçilen Yönteme Göre TP Seviyelerini Hesapla
[tp1Level, tp2Level, tp3Level] = 
  switch tpMethod
    "ATR_Standart" => [ta.valuewhen(buySignalk, ATRupper4, 0), ta.valuewhen(buySignalk, ATRupper3, 0), ta.valuewhen(buySignalk, ATRupper2, 0)]
    "Fibonacci" => calculateFibonacci(ta.valuewhen(buySignalk, close, 0))
    "Swing" => calculateSwing()
    "ADM" => calculateADM()
    "Bollinger" => calculateBollinger()
    "Pivot" => calculatePivot()
    "Zaman_Bazli" => calculateTimeBasedFactors()
    "Harmonik" => calculateHarmonic()
    "RSI_Bazli" => calculateRSIBased()
    => [ta.valuewhen(buySignalk, ATRupper4, 0), ta.valuewhen(buySignalk, ATRupper3, 0), ta.valuewhen(buySignalk, ATRupper2, 0)] // Default

// Stop Seviyesi
stopLevel = ta.valuewhen(buySignalk, srcATR - atr, 0)

// TP Tetikleme Kontrolleri
tp1Hit = ta.crossover(high, tp1Level) and positionActive and not tp1Executed
tp2Hit = ta.crossover(high, tp2Level) and positionActive and tp1Executed and not tp2Executed
tp3Hit = ta.crossover(high, tp3Level) and positionActive and tp1Executed and tp2Executed
stopHit = ta.crossunder(low, stopLevel) and positionActive



// Strateji Giriş ve Çıkış Koşulları
if (isInDateRange and buySignalk and not positionActive) and barstate.isconfirmed
    sonGirisLotu := lotHesapla()
    kalanLot := sonGirisLotu
    tp1Lot := math.floor(sonGirisLotu * tp1Oran)
    tp2Lot := math.floor(sonGirisLotu * tp2Oran)
    tp3Lot := sonGirisLotu - tp1Lot - tp2Lot 
    
    strategy.entry("Long", strategy.long, qty=sonGirisLotu)
    alert('{"name": "🚀' + "İşleme girdi" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "mktbest", "price": "' + str.tostring(close) + '", "quantity": "' + str.tostring(sonGirisLotu) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '"}', alert.freq_once_per_bar_close)
    positionActive := true
    tp1Executed := false
    tp2Executed := false

if (isInDateRange and tp1Hit) 
    strategy.exit("TP1", "Long", qty=tp1Lot, limit=tp1Level, comment="TP1")
    alert('{"name": "💸' + "TP1 - İlk Kısmi Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(tp1Level) + '", "quantity": "' + str.tostring(tp1Lot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '"}', alert.freq_once_per_bar_close)
    kalanLot := kalanLot - tp1Lot
    tp1Executed := true

if (isInDateRange and tp2Hit)
    strategy.exit("TP2", "Long", qty=tp2Lot, limit=tp2Level, comment="TP2")
    alert('{"name": "💸' + "TP2 - İkinci Kısmi Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(tp2Level) + '", "quantity": "' + str.tostring(tp2Lot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '"}', alert.freq_once_per_bar_close)
    kalanLot := kalanLot - tp2Lot
    tp2Executed := true

// BearCross'ta kalan lotları çıkış
if (isInDateRange and sellSignallk and positionActive) 
    strategy.close("Long", comment="Bear Cross")
    alert('{"name": "🔄' + "Trend Değişimi - Çıkış" + '", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "mktbest", "price": "' + str.tostring(close) + '", "quantity": "' + str.tostring(kalanLot) + '", "timeInForce": "day", "apiKey": "' + APIKEY + '"}', alert.freq_once_per_bar_close)
    kalanLot := 0
    positionActive := false
    tp1Executed := false
    tp2Executed := false

// Çizimler
p_tp1 = plot(positionActive ? tp1Level : na, "TP1 Seviyesi", color=color.new(color.green, 0), style=plot.style_line, linewidth=2, show_last=55)
p_tp2 = plot(positionActive ? tp2Level : na, "TP2 Seviyesi", color=color.new(color.blue, 0), style=plot.style_line, linewidth=2, show_last=55)
// p_tp3 = plot(positionActive ? tp3Level : na, "TP3 Seviyesi", color=color.new(color.purple, 0), style=plot.style_line, linewidth=2, show_last=55)
p_stop = plot(positionActive ? stopLevel : na, "Stop Seviyesi", color=color.new(color.red, 0), style=plot.style_line, linewidth=2, show_last=55)

// Son barda etiket gösterimi
if (barstate.islast)
    label.new(bar_index, tp1Level, "TP1 ", style=label.style_label_right, color=color.green, textcolor=color.white)
    label.new(bar_index, tp2Level, "TP2 ", style=label.style_label_right, color=color.blue, textcolor=color.white)
    // label.new(bar_index, tp3Level, "TP3 ", style=label.style_label_right, color=color.purple, textcolor=color.white)
    label.new(bar_index, stopLevel, "STOP ", style=label.style_label_right, color=color.red, textcolor=color.white)
//////////////////////////////////////////////////////////////////   TİMUR İNCİ //////////////////////////////////////////////////////////////////////////////////////



// // Copy below code to end of the desired strategy script
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //                                 monthly pnl performance  by Dr. Maurya @MAURYA_ALGO_TRADER                        //
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// show_performance = input.bool(true, 'AYLIK PERFORMANS TABLOSU ?', group='AYLIK Performance')

// dash_loc_mp = input.session("Bottom Right","Location"  ,options=["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"]  ,group='AYLIK Performance', inline = "performance")

// text_size_mp = input.session('Small',"Size"  ,options=["Tiny","Small","Normal","Large"]  ,group='AYLIK Performance', inline = "performance")

// bg_c = input.color( color.rgb(91, 91, 94, 38), "Background Color", group='AYLIK Performance')

// text_head_color = input.color( #ffffff, "Month/Year Heading Color", group='AYLIK Performance')

// tab_month_c = input.color( color.white, "Month PnL Data Color", group='AYLIK Performance')

// tab_year_c = input.color( color.rgb(0,0,0), "Year PnL Data Color", group='AYLIK Performance')

// border_c = input.color( color.white, "Table Border Color", group='AYLIK Performance')

// var table_position_mp = dash_loc_mp == 'Top Left' ? position.top_left :
//   dash_loc_mp == 'Bottom Left' ? position.bottom_left :
//   dash_loc_mp == 'Middle Right' ? position.middle_right :
//   dash_loc_mp == 'Bottom Center' ? position.bottom_center :
//   dash_loc_mp == 'Top Right' ? position.top_right : position.bottom_right
  
// var table_text_size_mp = text_size_mp == 'Tiny' ? size.tiny :
//   text_size_mp == 'Small' ? size.small :
//   text_size_mp == 'Normal' ? size.normal : size.large

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

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

// // 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

// var testTable = table.new(position = table_position_mp, columns = 14, rows = 40, bgcolor = bg_c, border_color = border_c, border_width = 1)
// if barstate.islastconfirmedhistory and show_performance
//     table.cell(table_id = testTable, column = 0, row = 0, text = "YIL", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 1, row = 0, text = "OCK", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 2, row = 0, text = "SBT", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 3, row = 0, text = "MAR", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 4, row = 0, text = "NİS", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 5, row = 0, text = "MAY", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 6, row = 0, text = "HAZ", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 7, row = 0, text = "TEM", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 8, row = 0, text = "AUG", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 9, row = 0, text = "EYL", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 10, row = 0, text = "EKM", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 11, row = 0, text = "KAS", text_color = text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 12, row = 0, text = "ARL", text_color =text_head_color, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, column = 13, row = 0, text = "YIL P/L", text_color = text_head_color, text_size=table_text_size_mp)

//     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 = testTable, 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 ? color.green : array.get(y_pnl_array , i) < 0 ? color.red : color.gray, text_color = tab_year_c, text_size=table_text_size_mp)
//     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 = testTable, 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 ? color.green : curr_y_pnl < 0 ? color.red : color.gray, text_color = tab_year_c, text_size=table_text_size_mp)
    

//     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 = testTable, 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 ? color.green : monthly_profit < 0 ? color.red : color.gray, text_color = tab_month_c, text_size=table_text_size_mp)
//         table.cell(table_id = testTable, column = 0, row =row_month_time, text = str.tostring(year(array.get(month_time_array, i)), "##.##"), text_color = text_head_color, text_size=table_text_size_mp)
       
//     // curr_row_m = 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 = testTable, 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 ? color.green : curr_m_pnl < 0 ? color.red : color.gray, text_color = tab_month_c, text_size=table_text_size_mp)
//     table.cell(table_id = testTable, 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_text_size_mp)

//============================================================================================================================================================================

// Kullanıcı Ayarı - Tabloyu Göster/Gizle
show_table = input.bool(defval=true, title="Tabloyu Göster")

// Değişken tanımlamaları
var float peakEquity = na
var float maxDrawdownValue = 0.0
var float maxDrawdownPercent = 0.0
var float firstTradePrice = na
var table tablePerformance = table.new(position=position.top_center, columns=2, rows=10, border_color=color.gray, border_width=2, bgcolor=color.rgb(0, 0, 0), frame_color=color.rgb(71, 71, 71), frame_width=1)

// 📌 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 : math.abs(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 := (drawdown / 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

// Eğer yeni bir maksimum kayıp oluşursa güncelle
if drawdown > maxDrawdownValue
    maxDrawdownValue := drawdown
    maxDrawdownPercent := (maxDrawdownValue / peakEquity) * 100  // Yüzde olarak hesapla

// 🔹 **Buy & Hold Getirisi (Tutar ve Yüzde)**
if na(firstTradePrice) and strategy.position_size != 0
    firstTradePrice := close  // İlk işlem anındaki kapanış fiyatını al
 
// Tabloya Ekleme
if (bar_index % 5 == 0) and show_table
    // Strateji İsmi
    table.cell(tablePerformance, 0, 0, "⚙️ STRATEJİ: Kule Muti 3TP zamansal", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    
    // Net Kâr + Yüzdesi
    table.cell(tablePerformance, 0, 1, "NET KAZANÇ", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 1, str.tostring(netProfit, "#.##") + " TRY (" + str.tostring(netProfitPercent, "#.##") + "%)", bgcolor=netProfit > 0 ? color.rgb(0, 150, 0) : color.rgb(150, 0, 0), text_color=color.white)

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

    // Karlılık Oranı
    table.cell(tablePerformance, 0, 3, "KARLI %", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 3, str.tostring(percentProfitable, "#.##") + "%", 
              bgcolor=color.rgb(0, 0, 150), text_color=color.white)

    // Al Tut
    table.cell(tablePerformance, 0, 4, "AL TUT", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 4, str.tostring(buyHoldReturnAmount, "#.##") + " TRY (" + str.tostring(buyHoldReturnPercent, "#.##") + "%)",  bgcolor=buyHoldReturnAmount > 0 ? color.rgb(0, 150, 0) : color.rgb(150, 0, 0), text_color=color.white)

    // Kazanç Katsayısı
    table.cell(tablePerformance, 0, 5, "KAZANÇ KTS.", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 5, str.tostring(profitFactor, "#.##"), bgcolor=color.rgb(0, 0, 150), text_color=color.white)

    // Açık Pozisyonlar
    table.cell(tablePerformance, 0, 6, "AÇIK PZS.", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 6, str.tostring(openTrades), bgcolor=color.rgb(0, 0, 150), text_color=color.white)

    // Kapanmış Pozisyonlar
    table.cell(tablePerformance, 0, 7, "KAPANMIŞ PZS.", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 7, str.tostring(closedTrades), bgcolor=color.rgb(0, 0, 150), text_color=color.white)

    // Kazançlı Pozisyonlar
    table.cell(tablePerformance, 0, 8, "KARLI İŞL.", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 8, str.tostring(winTrades), bgcolor=color.rgb(0, 150, 0), text_color=color.white)

    // Kayıplı Pozisyonlar
    table.cell(tablePerformance, 0, 9, "ZARARLI İŞL.", bgcolor=color.rgb(27, 27, 27), text_color=color.white)
    table.cell(tablePerformance, 1, 9, str.tostring(loseTrades), bgcolor=color.rgb(150, 0, 0), text_color=color.white)

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