Untitled

 avatar
unknown
plain_text
17 days ago
178 kB
6
Indexable
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
import TradingView/Strategy/3
strategy('✅'
         , shorttitle = '✅'
         , overlay = true
         , calc_on_order_fills = false
         , commission_value = 0.01
         , initial_capital = 100000
         , default_qty_value = 1
         , default_qty_type = strategy.percent_of_equity
         , slippage = 10
         , use_bar_magnifier = false
         , fill_orders_on_standard_ohlc = true
         , max_lines_count = 500
         , max_labels_count = 500
         , pyramiding  = 1000
         , calc_on_every_tick = true
         , close_entries_rule = "ANY")


YONTEM2r  = input.string("", title="Strateji Adınızı Buraya Yazabilirsiniz.", group="💻 ÖNEMLİ")
var bool[] gridShowBuyOrder = array.new_bool()   
var bool[] gridShowSellOrder = array.new_bool()  

var bool activate_ranges = true 
var int start = 0
var int finish = 0 
var bool basla = false
var bool bitir = false

if activate_ranges
    start := input.time(title = '🕐 Başlangıç Tarihi ve Saati', defval = timestamp('21 January 2025'), group='/---GRİD BAŞLANGIÇ AYARLARI---/')
       
    finish := input.time(title = '🕑 Bitiş Tarihi ve Saati',defval = timestamp('31 August 2025'), group='/---GRİD BAŞLANGIÇ AYARLARI---/')
close_at_end_time = input.bool(defval = false, title = "⚠️ Bitiş tarihinde Tüm Pozisyonlar Kapatılsın mı ?", group='/---GRİD BAŞLANGIÇ AYARLARI---/')

apikey = input.string(defval="", title="✉️ ApiKey Gir", group = '///////////---ARACI KURUM AYARI---///////////')
token = input.string(defval="", title="💻 Token Bilgilerini Gir ", group = '///////////---ARACI KURUM AYARI---///////////')

alim_yontemi = input.string(title="Alım Yöntemi", defval="mktbest",options=["mktbest", "lmt"],tooltip="İşlem açılış yöntemini seçin", group="⚡️ STRATEJİ EMİR TİPİ SEÇİM AYARLARI")

tabloGoster = input.bool(false, "📌 İşlem Tablosunu Göster/Gizle LİMİT", group='/////////////////---TABLO AYARLARI---/////////////////')
tabloGoster1 = input.bool(false, "📌 Takip Tablosunu Göster/Gizle LİMİT", group='/////////////////---TABLO AYARLARI---/////////////////')
var int userGridCount = input.int(title="📌 Alt Grid Emir Sayısı", defval=1, minval=1, maxval=3, tooltip="Kaç alt grid seviyesine AL emri gönderilecek (1-3 arası)", group='/////////////////---LİMİT YÖNTEM AYARLARI---/////////////////')
var int userUpperGridCount = input.int(title="📌 1.Grup Üst Grid Emir Sayısı", defval=1, minval=1, maxval=10, tooltip="Kaç üst grid seviyesine SAT emri gönderilecek (1-10 arası)", group='/////////////////---LİMİT YÖNTEM AYARLARI---/////////////////')
var int userUpperGridCount10 = input.int(title="📌 2.Grup Üst Grid Emir Sayısı", defval=0, minval=0, maxval=10, tooltip="Kaç üst grid seviyesine SAT emri gönderilecek (1-10 arası)", group='/////////////////---LİMİT YÖNTEM AYARLARI---/////////////////')

[btcTime] = request.security(syminfo.tickerid, "1", [time], lookahead=barmerge.lookahead_on)

var firstFinish = input.time(title='🕑 İlk Sat Emirlerinin Gönderileceği Tarih', defval=timestamp('2025-02-05 10:01:00'), group='--ZAMAN AYARLARI--')
var firstFinish99 = input.time(title='🕑 İlk Al Emirlerinin Gönderileceği Tarih', defval=timestamp('2025-02-05 10:01:00'), group='--ZAMAN AYARLARI--')
var secondFinish = input.time(title='🕑 1.Toplu Sat Emirlerinin Gönderileceği Tarih', defval=timestamp('2025-02-05 10:05:00'), group='--ZAMAN AYARLARI--')
var secondFinish10 = input.time(title='🕑 2.Toplu Sat-1 Emirlerinin Gönderileceği Tarih', defval=timestamp('2025-02-05 10:09:00'), group='--ZAMAN AYARLARI--')
var secondFinish60 = input.time(title='🕑 2.Toplu Sat-2 Emirlerinin Gönderileceği Tarih', defval=timestamp('2025-02-05 10:09:00'), group='--ZAMAN AYARLARI--')

var firstFinish10 = input.time(title='🕑 Giriş Yapılacak  Tarih', defval=timestamp('2025-02-05 10:00:00'), group='--ZAMAN AYARLARI--')

isOrderTime() =>
    btcHour = hour(btcTime)
    btcMinute = minute(btcTime)
    targetHour = hour(firstFinish)
    targetMinute = minute(firstFinish)
    btcHour == targetHour and btcMinute == targetMinute

isOrderTime1() =>
    btcHour = hour(btcTime)
    btcMinute = minute(btcTime)
    targetHour = hour(secondFinish)
    targetMinute = minute(secondFinish)
    btcHour == targetHour and btcMinute == targetMinute

isOrderTime2() =>
    btcHour = hour(btcTime)
    btcMinute = minute(btcTime)
    targetHour = hour(secondFinish10)
    targetMinute = minute(secondFinish10)
    btcHour == targetHour and btcMinute == targetMinute

isOrderTime60() =>
    btcHour = hour(btcTime)
    btcMinute = minute(btcTime)
    targetHour = hour(secondFinish60)
    targetMinute = minute(secondFinish60)
    btcHour == targetHour and btcMinute == targetMinute

isOrderTime80() =>
    btcHour = hour(btcTime)
    btcMinute = minute(btcTime)
    targetHour = hour(firstFinish99)
    targetMinute = minute(firstFinish99)
    btcHour == targetHour and btcMinute == targetMinute

isEntryTime() =>
    btcHour = hour(btcTime)
    btcMinute = minute(btcTime)
    targetHour = hour(firstFinish10)
    targetMinute = minute(firstFinish10)
    btcHour == targetHour and btcMinute == targetMinute

var MAX_ROWS = input.int(25, "Tablo Satır Sayısı", 
     minval=5, maxval=50, 
     tooltip="Tabloda gösterilecek maksimum satır sayısını belirler (5-50 arası)", group='/////////////////---LİMİT YÖNTEM AYARLARI---/////////////////')



report_aktif_pasif = input.bool(false, title="✓ Aktif/Pasif Bilgisi Al", group='/---MKTBEST RAPOR AYARLARI---/')
report_detayli = input.bool(false, title="✓ Detaylı İşlem Bilgisi Al", group='/---MKTBEST RAPOR AYARLARI---/')
report_islem = input.bool(true, title="✓ Açık İşlem Bilgilerini Detaylandır", group='/---MKTBEST RAPOR AYARLARI---/')


historical_days = input.int(title="📊 Grid Fiyat Simgelerini Ayarla", defval=3, minval=1, maxval=365, group="LABEL AYARI")


var float longGridInterval = 0.0
var float shortGridInterval = 0.0
var float grid_aralik = 0.0  
var float son_tetiklenen_fiyat = na  

showTable = input.bool(false, title="💻 Pc İçin Tabloyu Açar Kapatır MKTBEST", group='/////////////////---TABLO AYARLARI---/////////////////')
showTable99 = input.bool(false, title="📲 Mobil İçin Tabloyu Açar Kapatır MKTBEST", group='/////////////////---TABLO AYARLARI---/////////////////')
komisyon = input.float(title="💰 İşlem Komisyon %", defval=0.01, minval=0.0, step=0.001, tooltip="Alış ve satış işlemleri için uygulanacak komisyon oranı" , group='/////////////////---SİSTEM AYARLARI---/////////////////')

calcCommission(float quantity, float price) =>
    float commission = quantity * price * (komisyon/100 )
    commission

getTotalCommission() =>
    float total = 0.0
    
    
    if strategy.position_size != 0
        total += calcCommission(math.abs(strategy.position_size), close)
        
    
    if strategy.closedtrades > 0
        for i = 0 to strategy.closedtrades - 1
            entry_comm = calcCommission(math.abs(strategy.closedtrades.size(i)), strategy.closedtrades.entry_price(i))
            exit_comm = calcCommission(math.abs(strategy.closedtrades.size(i)), strategy.closedtrades.exit_price(i))
            total += entry_comm + exit_comm
            
    total

YONTEM2 = ""
string alarm_ismi1  = "Long🔺" 
string alarm_ismi2  = "Long🔻"
string alarm_ismi3  = "STOP OLDU"  
string alarm_ismi4  = "KAR ALINDI"
string alarm_ismi5  = "Short🔺"
string alarm_ismi6  = "Short🔻"  
string alarm_ismi7  = "Zaman Doldu Long İşlemler"
string alarm_ismi8  = "Zaman Doldu Yatay İşlemler"
string alarm_ismi9  = "Zaman Doldu Short İşlemler"

var float longEntryTime = na
var float shortEntryTime = na
var float pnl = 0.0 
var bool islem_yapilabilir = true
var bool hedefe_ulasildi = false
var int bekleyenEmirler = 0 

if time >= start and time <= finish
    pnl := strategy.netprofit 

enable_profit_loss_close = input.bool(defval = false, title = "Kar/Zarar Seviyesinde Kapatmayı Etkinleştir", group = '///////////---MKTBEST KAR/ZARAR AYARLARI---///////////')
profit_target = input.float(defval = 5000, title = "Kar Hedefi", group = '///////////---MKTBEST KAR/ZARAR AYARLARI---///////////')
loss_limit = input.float(defval = -1500, title = "Zarar Limiti", group = '///////////---MKTBEST KAR/ZARAR AYARLARI---///////////')

s = input.session(title='🕐 Tetik İşlem Saati', defval='1000-1800', group = '///////////---MKTBEST BAŞLAMA AYARI---///////////')

startHour = 10
endHour = 17
endMinute = 58


currentHour = hour(time)
currentMinute = minute(time)


isTradingAllowed = (currentHour > startHour or (currentHour == startHour and currentMinute >= 0)) and (currentHour < endHour or (currentHour == endHour and currentMinute <= endMinute))

window() =>

    time >= start and time <= finish ? true : false

truncate_to_symbol_decimals(value) =>
    
    decimals = math.ceil(-math.log10(syminfo.mintick))
    
    multiplier = math.pow(10, decimals)
    
    truncatedValue = math.floor(value * multiplier) / multiplier
    truncatedValue

symbol_min_move() =>
    
    min_move_decimals = math.ceil(-math.log10(syminfo.mintick))
    min_move_decimals

symbol_decimal_str(number) =>
    result = ""
    for i=0 to number-1
        result += "0"
    result

var float investment = 100000  
var string order_size = "SABİT"  

fix_cl_per_level = input.float(title="💰 Kontrat / Lot sayısı", defval=50, minval=0, group='/////////////////---SİSTEM AYARLARI---/////////////////')
gridLevels       = input.int(title="🪜 Izgara / Grid Sayısı ", defval=100, minval=2, group='/////////////////---SİSTEM AYARLARI---/////////////////')

var string distributionType = "RAKAMSAL"  
mode             = input.string(title="🔺🔻İşlem Yönü", defval="Uzun", options=["Yatay", "Uzun", "Kısa"], group='/////////////////---SİSTEM AYARLARI---/////////////////')
entry_condition  = input.string(title="🪂 İşlem Yöntemi", defval="Malsız Başla", options=["Mal ile Başla","Malsız Başla"], group = '///////////---MKTBEST BAŞLAMA AYARI---///////////')

var string grid_calculation = "SABİT GRİD"  

var bool enable_levels = true

var topLevel_raw    = input.price(title="⚡️Yatay ve Kısa da Tepe / Uzunda Tepe Fiyatı", defval=100, group='/////////////////---İŞLEM AYARLARI---/////////////////')
var referencePrice  = input.price(title="⚡️Uzunda Tepe / Yatayda Referans Fiyatı/Kısada Tepe Fiyatı", defval=100, group='/////////////////---İŞLEM AYARLARI---/////////////////')
var bottomLevel_raw = input.price(title="⚡️Uzunda ve Yatayda Dip Fiyatı /Kısada dip fiyatı", defval=50, group='/////////////////---İŞLEM AYARLARI---/////////////////')

var int biriktirilmis_lot = 0  
var int onceki_kapanan_islem_sayisi = 0
var float total_value = 0.0  
var float average_price = 0.0  

lotStrategy = input.string(title="📈 Lot Hesaplama Stratejisi", defval="SABİT", options=["SABİT","ZAMAN BAZLI"],group = '///////////---LOT AYARLARI---///////////')

maxLotOran = 100000
minLotOran = 1

var int zamanBazliAcilisOran = input.int(title="⏰ Açılış Saati Lot Adedi (10:00-11:00)", defval=10, minval=1, maxval=10000,group='///////////---LOT AYARLARI---///////////')
var int zamanBazliNormalOran = input.int(title="⏰ Normal Saat Lot Adedi (11:00-16:00)", defval=50, minval=1, maxval=10000,group='///////////---LOT AYARLARI---///////////')
var int zamanBazliKapanisOran = input.int(title="⏰ Kapanış Saati Lot Adedi (16:00-18:00)", defval=25, minval=1, maxval=10000,group='///////////---LOT AYARLARI---///////////')

calculateLotSize(string strategy, float baseLot, int gridLevel, float currentPrice, float refPrice) =>
    int result = int(baseLot)
    
    if strategy == "SABİT"
        result := int(baseLot)
        
    else if strategy == "ZAMAN BAZLI"
        int curHour = hour(time)
        if curHour >= 10 and curHour < 11
            result := zamanBazliAcilisOran
        else if curHour >= 11 and curHour < 16
            result := zamanBazliNormalOran
        else if curHour >= 16 and curHour < 18
            result := zamanBazliKapanisOran
        else
            result := zamanBazliAcilisOran

    
    math.max(math.min(result, maxLotOran), minLotOran)

periodicReportEnabled = input.bool(title="⏰ Periyodik Rapor Gönderimi", defval=false, group='///////////---ALARM AYARLARI---///////////')
waitPeriods = input.int(title="⏰ Kaç Periyod Beklensin", defval=4, minval=1, tooltip="Her kaç periyodda bir rapor gönderilsin? Örnek: 4 girilirse, 1dk'lık grafikteyken her 4 dakikada bir rapor gönderilir.", group='///////////---ALARM AYARLARI---///////////')
alarm_saat = input.int(title="⏰ Alarm Saati", defval=10, minval=0, maxval=23, group='///////////---ALARM AYARLARI---///////////')
alarm_dakika = input.int(title="⏰ Alarm Dakikası", defval=5, minval=0, maxval=59, group='///////////---ALARM AYARLARI---///////////')

sembol_degeri = close
start12 = time[1]

mode := (topLevel_raw<referencePrice) ? "Uzun" : mode
mode := (bottomLevel_raw>referencePrice) ? "Kısa" : mode

topLevel    = mode == "Uzun"  ? referencePrice : topLevel_raw
bottomLevel = mode == "Kısa" ? referencePrice : bottomLevel_raw

enable_tp_sl = input.bool(title='Stop Aktif Olsun Mu ?', defval=false, group='/////////////////---MKTBEST STOP AYARLARI---/////////////////')


stop_mode    = input.string(title="🛑 Stop Yöntemi", defval="Tekrar İşlem Açmaz", options=["Tekrar İşlem Açabilir", "Tekrar İşlem Açmaz"], group='/////////////////---MKTBEST STOP AYARLARI---/////////////////')
upperLimit   = input.price(title="🛑 Stop Tepe Fiyatı", defval=100, group='/////////////////---MKTBEST STOP AYARLARI---/////////////////')
lowerLimit   = input.price(title="🛑 Stop Alt Fiyatı", defval=50, group='/////////////////---MKTBEST STOP AYARLARI---/////////////////')

closeAllPositions1() =>
    if mode == "Yatay"
        
        if (strategy.position_size > 0)
            strategy.cancel_all()
            strategy.close("Buy@", comment="Long Pozisyonlar Kapatıldı", alert_message='{"name": "' + alarm_ismi2 + ' Stop Tetiklendi. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔻 [LONG-STOP] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')  
                
        
        if (strategy.position_size < 0)
            strategy.cancel_all()
            strategy.close("Sell@", comment="Short Pozisyonlar Kapatıldı", alert_message='{"name": "' + alarm_ismi6 + ' Stop Tetiklendi. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔺 [SHORT-STOP] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "buy", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')  
    else
        
        if (strategy.position_size > 0)
            strategy.cancel_all()
            strategy.close_all(comment= stop_mode + "- ZARAR STOP", immediately=true, alert_message='{"name": "' + alarm_ismi3 + ' Stop Tetiklendi. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔻 [LONG-STOP] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')  
        if (strategy.position_size < 0)
            strategy.cancel_all()
            strategy.close_all(comment= stop_mode + "+ KAR AL STOP", immediately=true, alert_message='{"name": "' + alarm_ismi4 + ' Stop Tetiklendi. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔺 [SHORT-STOP] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "buy", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')  

var one_time_trigger = false
priceHitsLimits() =>
    hit = one_time_trigger == false ? false : true
    if (close >= upperLimit or close <= lowerLimit) and enable_tp_sl and window()
        strategy.cancel_all()
        closeAllPositions1()
        hit := true
        alert_message = '{"name": "' + alarm_ismi3 + ' Stop Tetiklendi. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🛑 [STOP] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}'
    hit

if stop_mode == "Tekrar İşlem Açmaz" and priceHitsLimits() and one_time_trigger == false
    one_time_trigger := true
roundToMinMove(price) => 
    minPriceMove = syminfo.minmove / 100
    multiplier = 1 / minPriceMove
    math.round(price * multiplier) / multiplier

var gridLevelsArray = array.new_float()
var longLevelsArray = array.new_float()
var shortLevelsArray = array.new_float()


calcGridLevels(float top, float bottom, float ref, int gridCount) =>
    var levels = array.new_float()
    array.clear(levels)
    
    
    float totalRange = top - bottom
    float gridStep = totalRange / (gridCount - 1)             
    if mode == "Uzun"      
        for i = 0 to gridCount - 1
            float baseLevel = ref - (i * gridStep)
            if baseLevel >= bottom
                float roundedLevel = baseLevel               
                if baseLevel < 20.00
                    roundedLevel := math.round(baseLevel * 100) / 100
                else if baseLevel < 50.00
                    roundedLevel := math.round(baseLevel * 50) / 50
                else if baseLevel < 100.00
                    roundedLevel := math.round(baseLevel * 20) / 20
                else if baseLevel < 250.00
                    roundedLevel := math.round(baseLevel * 10) / 10
                else if baseLevel < 500.00
                    roundedLevel := math.round(baseLevel * 4) / 4
                else if baseLevel < 1000.00
                    roundedLevel := math.round(baseLevel * 2) / 2
                else
                    roundedLevel := math.round(baseLevel)
                    
                array.push(levels, roundedLevel)
                
    else if mode == "Kısa"
        
        for i = 0 to gridCount - 1
            float baseLevel = top - (i * gridStep)
            if baseLevel >= ref
                float roundedLevel = baseLevel
                
                if baseLevel < 20.00
                    roundedLevel := math.round(baseLevel * 100) / 100
                else if baseLevel < 50.00
                    roundedLevel := math.round(baseLevel * 50) / 50
                else if baseLevel < 100.00
                    roundedLevel := math.round(baseLevel * 20) / 20
                else if baseLevel < 250.00
                    roundedLevel := math.round(baseLevel * 10) / 10
                else if baseLevel < 500.00
                    roundedLevel := math.round(baseLevel * 4) / 4
                else if baseLevel < 1000.00
                    roundedLevel := math.round(baseLevel * 2) / 2
                else
                    roundedLevel := math.round(baseLevel)
                    
                array.push(levels, roundedLevel)
    
    
    if array.size(levels) != gridCount
        // Eksik grid varsa tamamla
        float step = (top - bottom) / (gridCount - 1)
        array.clear(levels)
        for i = 0 to gridCount - 1
            float baseLevel = bottom + (step * i)
            float roundedLevel = baseLevel
            
            if baseLevel < 20.00
                roundedLevel := math.round(baseLevel * 100) / 100
            else if baseLevel < 50.00
                roundedLevel := math.round(baseLevel * 50) / 50
            else if baseLevel < 100.00
                roundedLevel := math.round(baseLevel * 20) / 20
            else if baseLevel < 250.00
                roundedLevel := math.round(baseLevel * 10) / 10
            else if baseLevel < 500.00
                roundedLevel := math.round(baseLevel * 4) / 4
            else if baseLevel < 1000.00
                roundedLevel := math.round(baseLevel * 2) / 2
            else
                roundedLevel := math.round(baseLevel)
                
            array.push(levels, roundedLevel)
    
    levels


var float[] storedLongGrids = array.new_float()
var float[] storedShortGrids = array.new_float()
var bool gridsPricesStored = false


if barstate.isfirst
    gridLevelsArray := calcGridLevels(topLevel, bottomLevel, referencePrice, gridLevels)
    
    if array.size(gridLevelsArray) > 0
      
        if mode == "Yatay" or mode == "Uzun"
            array.clear(storedLongGrids)
            for i = 0 to array.size(gridLevelsArray) - 1
                float level = array.get(gridLevelsArray, i)
                if not na(level) and level <= referencePrice
                    array.push(storedLongGrids, level)
    
        if mode == "Yatay" or mode == "Kısa"
            array.clear(storedShortGrids)
            for i = 0 to array.size(gridLevelsArray) - 1
                float level = array.get(gridLevelsArray, i)
                if not na(level) and level >= referencePrice
                    array.push(storedShortGrids, level)
    
        gridsPricesStored := true


if gridsPricesStored
 
    for i = 0 to array.size(storedLongGrids) - 1
        price = array.get(storedLongGrids, i)
       
        

    for i = 0 to array.size(storedShortGrids) - 1
        price = array.get(storedShortGrids, i)
       

var int startBarTime    = na 
var int finishBarTime   =  finish

var first_qty           = float(0)
var is_first_grid_calculation_completed = false

    

var int bars_back_time = na

if time >= start and time[1] < start
   
    bars_back_time := 1000 * 20 * 1 * historical_days
    startBarTime := time - bars_back_time
    first_qty := investment*1/close


if is_first_grid_calculation_completed == false and window()
    gridLevelsArray := calcGridLevels(topLevel, bottomLevel, referencePrice, gridLevels)
   
    
    if array.size(gridLevelsArray) > 0
        
        array.clear(storedLongGrids)
        array.clear(storedShortGrids) 
        array.clear(longLevelsArray)
        array.clear(shortLevelsArray)

        
        for i = 0 to array.size(gridLevelsArray) - 1
            if not na(array.get(gridLevelsArray, i))
                float level = array.get(gridLevelsArray, i)
                
                float roundedLevel = level
                if level < 20.00
                    roundedLevel := math.round(level * 100) / 100    // 0.01 adım
                else if level < 50.00
                    roundedLevel := math.round(level * 50) / 50      // 0.02 adım
                else if level < 100.00
                    roundedLevel := math.round(level * 20) / 20      // 0.05 adım
                else if level < 250.00
                    roundedLevel := math.round(level * 10) / 10      // 0.10 adım
                else if level < 500.00
                    roundedLevel := math.round(level * 4) / 4        // 0.25 adım
                else if level < 1000.00
                    roundedLevel := math.round(level * 2) / 2        // 0.50 adım
                else
                    roundedLevel := math.round(level)                // 1.00 adım

                
                if mode == "Yatay" or mode == "Uzun"
                    if roundedLevel <= referencePrice
                        array.push(longLevelsArray, roundedLevel)
                        array.push(storedLongGrids, roundedLevel)
                if mode == "Yatay" or mode == "Kısa"
                    if roundedLevel >= referencePrice
                        array.push(shortLevelsArray, roundedLevel)
                        array.push(storedShortGrids, roundedLevel)

        is_first_grid_calculation_completed := true

levelHasOpenTrade(level_comment) =>
    hasTrade = false
    for tradeId = 0 to strategy.opentrades - 1
        if strategy.opentrades.entry_comment(tradeId) == level_comment
            hasTrade := true
            break
    hasTrade

t1 = time(timeframe.period, s)

var bool[] gridHasActiveBuyOrder = array.new_bool()   
var bool[] gridHasActiveSellOrder = array.new_bool()  
var bool[] gridHasPosition = array.new_bool()         
var bool initialOrdersSent = false
var bool initialOrdersSent1 = false
var bool initialOrdersSent2 = false
var bool initialOrdersSent5 = false
var bool initialOrdersSent3 = false
var bool initialOrdersSent7 = false
var bool initialOrdersSent8 = false
var bool initialOrdersSent4 = false


pozisyonVarMi(float fiyat_seviyesi) =>
    var sonuc = false
    if strategy.position_size > 0
        for i = 0 to strategy.opentrades - 1
            if math.abs(strategy.opentrades.entry_price(i) - fiyat_seviyesi) < syminfo.mintick
                sonuc := true
                break
    sonuc

emirVarMi(float fiyat_seviyesi) =>
    var sonuc = false
    if strategy.opentrades > 0
        for i = 0 to strategy.opentrades - 1
            float tradePrice = strategy.opentrades.entry_price(i)
            string comment = strategy.opentrades.entry_comment(i)
            if (str.contains(comment, "LONG") or str.contains(comment, "SAT")) and 
               math.abs(tradePrice - fiyat_seviyesi) < syminfo.mintick
                sonuc := true
                break
    sonuc


arrayIndexValid(int index, array<bool> arr) =>
    index >= 0 and index < array.size(arr)

arrayIndexValidFloat(int index, array<float> arr) =>
    index >= 0 and index < array.size(arr)

getCurrentGridIndex(float currentPrice, array<float> levels) =>
    var int gridIndex = -1
    int maxIndex = array.size(levels) - 1
    
    if maxIndex <= 0  
        gridIndex := -1
    else
        for i = 0 to maxIndex - 1
            if arrayIndexValidFloat(i, levels) and arrayIndexValidFloat(i + 1, levels)
                float upperLevel = array.get(levels, i)
                float lowerLevel = array.get(levels, i + 1)
                if currentPrice <= upperLevel and currentPrice >= lowerLevel
                    gridIndex := i
                    break
    gridIndex


var MAX_TABLE_ROWS = 25  // Maksimum satır sayısı
var table gridTable = table.new(position.bottom_left, columns=4, rows=MAX_TABLE_ROWS+1, bgcolor=color.rgb(24, 24, 27), border_width=1)

// =================== EMOJİLER VE SEMBOLLER ===================
var string EMOJI_TIME = "🕐"       // Saat için emoji
var string EMOJI_BUY = "🟢 Emir"      // Yeşil daire - AL işaretleri için
var string EMOJI_SELL = "🔴 Emir"      // Kırmızı daire - SAT işaretleri için
var string EMOJI_POSITION = "⭐"   // Yıldız - Pozisyon için
var string EMOJI_ENTRY = "📥"     // Giriş işlemi için
var string EMOJI_EXIT = "📤"      // Çıkış işlemi için
var string EMOJI_PRICE = "💰"      // Para - Fiyat kolonu için
var string EMOJI_TYPE = "📊"       // Grafik - İşlem tipi için
var string EMOJI_STATUS = "🔄"     // Dönen oklar - Durum için
var string EMOJI_MARKET = "🔵 Piyasa"  // Piyasa emirleri için
var string EMOJI_LIMIT_BUY = "🟢 Limit"   // Limit AL emirleri için
var string EMOJI_LIMIT_SELL = "🔴 Limit"  // Limit SAT emirleri için
var string EMOJI_CLOSE = "🟠 Kapandı"     // Kapanan işlemler için
var string EMOJI_INDEPENDENT = "⭐" // Bağımsız pozisyonlar için
var string EMOJI_UPPER_GRID = "🔴 Piyasa Emir"     // Üst grid işlemleri için

// =================== BAĞIMSIZ POZİSYONLAR İÇİN REFERANS ARRAY'LER ===================
var bool[] independentPositions = array.new_bool(0)    
var float[] independentLevels = array.new_float(0)     

// =================== VERİ SAKLAMAK İÇİN ARRAY'LER ===================
var float[] priceHistory = array.new_float()
var float[] entryPriceHistory = array.new_float()
var string[] typeHistory = array.new_string()
var string[] statusHistory = array.new_string()
var string[] timeHistory = array.new_string()  // Yeni eklenen zaman array'i

// Önceki durumları saklamak için array'ler
var bool[] lastCheckedBuyOrders = array.new_bool()
var bool[] lastCheckedSellOrders = array.new_bool()
var bool[] lastCheckedPositions = array.new_bool()
var float[] positionEntryPrices = array.new_float()
var bool[] lastCheckedIndependentPositions = array.new_bool()
var float[] independentEntryPrices = array.new_float()

// Tablo başlıkları (sadece bir kez oluşturulacak)
if tabloGoster
    table.cell(gridTable, 0, 1, EMOJI_TIME + " Zaman", text_size=size.small, text_color=color.white, bgcolor=color.rgb(99, 16, 116))
    table.cell(gridTable, 1, 1, EMOJI_PRICE + " Fiyat ", text_size=size.small, text_color=color.white, bgcolor=color.rgb(99, 16, 116))
    table.cell(gridTable, 2, 1, EMOJI_TYPE + " İşlem", text_size=size.small, text_color=color.white, bgcolor=color.rgb(99, 16, 116))
    table.cell(gridTable, 3, 1, EMOJI_STATUS + " Durum", text_size=size.small, text_color=color.white, bgcolor=color.rgb(99, 16, 116))

// =================== YARDIMCI FONKSİYONLAR ===================
// Array'leri yönetmek için yardımcı fonksiyon
managePushToArray(arr, value) =>
    if array.size(arr) >= MAX_TABLE_ROWS
        array.shift(arr)
    array.push(arr, value)



// Saat formatını oluşturan fonksiyon
formatTime() =>
    hour = hour(time)
    minute = minute(time)
    second = second(time)
    hourStr = hour < 10 ? "0" + str.tostring(hour) : str.tostring(hour)
    minuteStr = minute < 10 ? "0" + str.tostring(minute) : str.tostring(minute)
    secondStr = second < 10 ? "0" + str.tostring(second) : str.tostring(second)
    hourStr + ":" + minuteStr + ":" + secondStr


       
        
       
        
        

// =================== YENİ VERİ EKLEME FONKSİYONU ===================
addNewEntry(float price, string type, string status, float entryPrice = na) =>
    currentTime = formatTime()
    managePushToArray(timeHistory, currentTime)
    managePushToArray(typeHistory, type)
    managePushToArray(statusHistory, status)
    managePushToArray(priceHistory, price)
    managePushToArray(entryPriceHistory, entryPrice)
  
    // Tabloyu güncelle
    for i = 0 to math.min(MAX_TABLE_ROWS - 2, array.size(priceHistory) - 1)
        int rowIndex = i + 2  
        int arrayIndex = array.size(priceHistory) - 1 - i
      
        // Zaman kolonu
        table.cell(gridTable, 0, rowIndex, array.get(timeHistory, arrayIndex), 
                 text_size=size.small, text_color=color.white, bgcolor=color.rgb(24, 24, 27))
       
        // Fiyat kolonu
        float currentPrice = array.get(priceHistory, arrayIndex)
        float entryPriceValue = array.get(entryPriceHistory, arrayIndex)
        string priceDisplay = ""
       
        string currentType = array.get(typeHistory, arrayIndex)
        if currentType == "🔵 Limit ⭐" or currentType == EMOJI_CLOSE
            priceDisplay := str.tostring(entryPriceValue, "#.00") + " ➜ " + str.tostring(currentPrice, "#.00")
        else
            priceDisplay := str.tostring(currentPrice, "#.00")
       
        table.cell(gridTable, 1, rowIndex, priceDisplay, 
                 text_size=size.small, text_color=color.white, bgcolor=color.rgb(24, 24, 27))
      
        // İşlem tipi kolonu
        table.cell(gridTable, 2, rowIndex, array.get(typeHistory, arrayIndex), 
                 text_size=size.small, text_color=color.white, bgcolor=color.rgb(24, 24, 27))
      
        // Durum kolonu
        table.cell(gridTable, 3, rowIndex, array.get(statusHistory, arrayIndex), 
                 text_size=size.small, text_color=color.white, bgcolor=color.rgb(24, 24, 27))

    // Kalan boş satırları temizle
    for i = math.min(array.size(priceHistory) + 2, MAX_TABLE_ROWS) to MAX_TABLE_ROWS
        if tabloGoster 
            table.cell(gridTable, 0, i, "", text_size=size.small, bgcolor=color.rgb(0, 0, 0))
            table.cell(gridTable, 1, i, "", text_size=size.small, bgcolor=color.rgb(0, 0, 0))
            table.cell(gridTable, 2, i, "", text_size=size.small, bgcolor=color.rgb(0, 0, 0))
            table.cell(gridTable, 3, i, "", text_size=size.small, bgcolor=color.rgb(0, 0, 0))

// =================== ARRAY BOYUTLARINI GÜNCELLEME ===================
updateArraySizes() =>
    if array.size(gridHasActiveBuyOrder) != array.size(lastCheckedBuyOrders) or 
       array.size(independentPositions) != array.size(lastCheckedIndependentPositions)
       
        array.clear(lastCheckedBuyOrders)
        array.clear(lastCheckedSellOrders)
        array.clear(lastCheckedPositions)
        array.clear(positionEntryPrices)
        array.clear(lastCheckedIndependentPositions)
        array.clear(independentEntryPrices)
       
        for i = 0 to array.size(gridHasActiveBuyOrder) - 1
            array.push(lastCheckedBuyOrders, false)
            array.push(lastCheckedSellOrders, false)
            array.push(lastCheckedPositions, false)
            array.push(positionEntryPrices, 0.0)
       
        for i = 0 to array.size(independentPositions) - 1
            array.push(lastCheckedIndependentPositions, false)
            array.push(independentEntryPrices, 0.0)

// =================== DURUM DEĞİŞİKLİKLERİNİ KONTROL EDEN FONKSİYON ===================
checkStateChanges() =>
    if tabloGoster
        if array.size(gridHasActiveBuyOrder) > 0
            for i = 0 to array.size(gridHasActiveBuyOrder) - 1
                if arrayIndexValid(i, gridHasActiveBuyOrder) and arrayIndexValid(i, gridHasActiveSellOrder) and arrayIndexValid(i, gridHasPosition) and arrayIndexValidFloat(i, longLevelsArray)
                    float price = array.get(longLevelsArray, i)
                  
                    bool currentBuy = array.get(gridHasActiveBuyOrder, i)
                    bool prevBuyState = i < array.size(lastCheckedBuyOrders) ? array.get(lastCheckedBuyOrders, i) : false
                    if currentBuy and not prevBuyState
                        addNewEntry(price, EMOJI_BUY, "⏳")
                  
                    bool currentSell = array.get(gridHasActiveSellOrder, i)
                    bool prevSellState = i < array.size(lastCheckedSellOrders) ? array.get(lastCheckedSellOrders, i) : false
                    if currentSell and not prevSellState
                        addNewEntry(price, EMOJI_SELL, "⏳")
                  
                    bool currentPos = array.get(gridHasPosition, i)
                    bool prevPosState = i < array.size(lastCheckedPositions) ? array.get(lastCheckedPositions, i) : false
                    if currentPos and not prevPosState
                        addNewEntry(price, "🔵 Limit ⭐", "⚡ Aktif")
                        array.set(positionEntryPrices, i, price)
                    if not currentPos and prevPosState
                        float entryPrice = array.get(positionEntryPrices, i)
                        float exitPrice = array.get(longLevelsArray, i - 1)
                        addNewEntry(exitPrice, EMOJI_CLOSE, "✅ Tamamlandı", entryPrice)
                        array.set(positionEntryPrices, i, 0.0)

        if array.size(independentPositions) > 0
            for i = 0 to array.size(independentPositions) - 1
                bool currentIndependent = array.get(independentPositions, i)
                bool prevIndependentState = i < array.size(lastCheckedIndependentPositions) ? array.get(lastCheckedIndependentPositions, i) : false
               
                if currentIndependent and not prevIndependentState
                    float currentPrice = close
                    addNewEntry(currentPrice, EMOJI_MARKET + " " + EMOJI_INDEPENDENT, "⚡ Aktif")
                    array.set(independentEntryPrices, i, currentPrice)

        if array.size(gridHasActiveBuyOrder) > 0  
            for i = 0 to array.size(gridHasActiveBuyOrder) - 1
                if i < array.size(lastCheckedBuyOrders) and i < array.size(lastCheckedSellOrders) and i < array.size(lastCheckedPositions)
                    array.set(lastCheckedBuyOrders, i, array.get(gridHasActiveBuyOrder, i))
                    array.set(lastCheckedSellOrders, i, array.get(gridHasActiveSellOrder, i))
                    array.set(lastCheckedPositions, i, array.get(gridHasPosition, i))

            for i = 0 to array.size(independentPositions) - 1
                if i < array.size(lastCheckedIndependentPositions)
                    array.set(lastCheckedIndependentPositions, i, array.get(independentPositions, i))

// =================== TABLO VE ARRAY GÜNCELLEMELERİ ===================
// Ana güncellemeler - Her tick'te çalışacak
if window() and (barstate.isrealtime or barstate.islast)  // Her tick'te güncelleme için
    updateArraySizes()
    checkStateChanges()







var int maxIndependentPositions = 5  


hasIndependentPosition() =>
    result = false
    for i = 0 to array.size(independentPositions) - 1
        if array.get(independentPositions, i)
            result := true
            break
    result



var int totalBuyOrders = 0  
var int totalSellOrders = 0  
var int totalOpenTrades = 0  
var int totalClosedTrades = 0


bool letTapeRunInput = input.bool(true, "Kayma Aktif", tooltip="Aktif olduğunda yazı kayar, pasif olduğunda sabit kalır", group='/////////////////---LİMİT YÖNTEM AYARLARI---/////////////////')
int offsetInput = input.int(0, "Başlangıç Konumu", tooltip="Yazının başlangıç pozisyonunu belirler", group='/////////////////---LİMİT YÖNTEM AYARLARI---/////////////////')


type Stat
    string name
    varip float value
    varip string valueStr
    varip float change
    varip string changeStr
    varip int upDown


makeStats() =>
    array<Stat> stats = array.new<Stat>()
    stats.push(Stat.new("Toplam AL Emirleri"))
    stats.push(Stat.new("Toplam SAT Emirleri"))
    stats.push(Stat.new("Açık Pozisyonlar"))
    stats.push(Stat.new("Kapalı Pozisyonlar"))
    stats


method update(Stat this) =>
    float currentValue = 0.0
    if this.name == "Toplam AL Emirleri"
        currentValue := float(totalBuyOrders)
    else if this.name == "Toplam SAT Emirleri"
        currentValue := float(totalSellOrders)
    else if this.name == "Açık Pozisyonlar"
        
        currentValue := float(totalOpenTrades + (strategy.position_size > 0 ? userUpperGridCount+userUpperGridCount10 : 0))
    else if this.name == "Kapalı Pozisyonlar"
        currentValue := float(totalClosedTrades)
       
    this.upDown := this.value < currentValue ? 1 : this.value > currentValue ? -1 : 0
    this.value := currentValue
    this.valueStr := str.tostring(currentValue, "#")
    this.change := currentValue - this.value[1]
    this.changeStr := str.tostring(this.change, "#")


method fillCell(Stat this, series table display, series int startCol, series int cells) =>
    table.cell(display, column = startCol, row = 0, text = this.name, text_color = chart.fg_color, text_size = size.normal, text_halign = text.align_left)
    table.cell(display, column = (startCol + 1) % cells, row = 0, text = this.valueStr, text_color = this.upDown < 0 ? color.red : this.upDown > 0 ? color.green : #000208, text_size = size.normal, text_halign = text.align_right)
    table.cell(display, column = (startCol + 2) % cells, row = 0, text = "|", text_color = chart.fg_color, text_size = size.normal, text_halign = text.align_center)





checkPriceLimit(price, bottomLevel, topLevel) =>
    price >= bottomLevel and price <= topLevel

isValidGridLevel(index, array_size) =>
    index >= 0 and index < array_size




safeArrayGet(arr, index) =>
    if array.size(arr) > 0 and index >= 0 and index < array.size(arr)
        array.get(arr, index)
    else
        float(na)



var int totalSellOrderCount = 0
var string totalSellOrderStatus = ""
var float openingPrice = na
var int gridsInPriceRange = 0
var string priceRangeGridStatus = ""
var float highestGridInRange = na
var float lowestGridInRange = na
var int gridsInUpperRange = 0
var string upperRangeGridStatus = ""
var int currentPriceUpperGridCount = 0
var string currentPriceUpperGridStatus = ""


isTargetTimeReached() =>
    int h = hour(time)
    int m = minute(time)
    h == 10 and m == 0

var bool priceInitialized = false


if isTargetTimeReached() and not priceInitialized
    openingPrice := open  
    priceInitialized := true

var int lastDay = 0
if dayofmonth(time) != lastDay and hour(time) >= 11  
    lastDay := dayofmonth(time)
    priceInitialized := false

calculateTotalSellOrders() =>
    int totalOrders = 0
    
    
    if userUpperGridCount > 0
        totalOrders += userUpperGridCount
    
    
    if userUpperGridCount10 > 0
        totalOrders += userUpperGridCount10
    
    
    int activeSellOrders = 0
    if array.size(gridHasActiveSellOrder) > 0
        for i = 0 to array.size(gridHasActiveSellOrder) - 1
            if array.get(gridHasActiveSellOrder, i)
                activeSellOrders += 1
    
    totalOrders += activeSellOrders
    
 
    string status = "Toplam SAT Emirleri: " + str.tostring(totalOrders) + "\n" +
                   "1. Grup: " + str.tostring(userUpperGridCount) + "\n" +
                   "2. Grup: " + str.tostring(userUpperGridCount10) + "\n" +
                   "Aktif: " + str.tostring(activeSellOrders)
    
    [totalOrders, status]


calculateGridsInPriceRange() =>
    if na(openingPrice)
        [0, "10:00 açılış fiyatı henüz belirlenmedi", na, na, 0, ""]
    else
        float upperLimit10 = openingPrice * 1.10  
        float lowerLimit10 = openingPrice * 0.90  
        int gridCount = 0
        int upperGridCount = 0
        
        float highest = na
        float lowest = na
        
        
        var float[] allGrids = array.new_float(0)
        array.clear(allGrids)
        
       
        if array.size(longLevelsArray) > 0
            for i = 0 to array.size(longLevelsArray) - 1
                float level = array.get(longLevelsArray, i)
                if level >= lowerLimit10 and level <= upperLimit10
                    array.push(allGrids, level)
                if level >= openingPrice and level <= upperLimit10
                    upperGridCount += 1
        
        
        if array.size(shortLevelsArray) > 0
            for i = 0 to array.size(shortLevelsArray) - 1
                float level = array.get(shortLevelsArray, i)
                if level >= lowerLimit10 and level <= upperLimit10
                    array.push(allGrids, level)
                if level >= openingPrice and level <= upperLimit10
                    upperGridCount += 1
        
        
        gridCount := array.size(allGrids)
        
        
        if gridCount > 0
            
            array.sort(allGrids)
           
            lowest := array.get(allGrids, 0)
            
            highest := array.get(allGrids, gridCount - 1)
        
        string status = "10:00 Açılış: " + str.tostring(openingPrice, "#.##") + " TL\n" +
                       "Alt Limit (%10): " + str.tostring(lowerLimit10, "#.##") + " TL\n" +
                       "Üst Limit (%10): " + str.tostring(upperLimit10, "#.##") + " TL\n" +
                       "Bu Aralıktaki Grid Sayısı: " + str.tostring(gridCount)
        
        if not na(lowest) and not na(highest)
            status += "\nEn Düşük Grid: " + str.tostring(lowest, "#.##") + " TL" +
                      "\nEn Yüksek Grid: " + str.tostring(highest, "#.##") + " TL"
        
        string upperStatus = "10:00 açılış fiyatı ile %10 üst sınır arasındaki grid sayısı: " + str.tostring(upperGridCount)
        
        [gridCount, status, highest, lowest, upperGridCount, upperStatus]


calculateCurrentPriceToOpeningUpperRange() =>
    if na(openingPrice)
        [0, "10:00 açılış fiyatı henüz belirlenmedi"]
    else
        float currentPrice = close
        float upperLimit10 = openingPrice * 1.10  
        int upperGridCount = 0
        
        
        if array.size(longLevelsArray) > 0
            for i = 0 to array.size(longLevelsArray) - 1
                float level = array.get(longLevelsArray, i)
                if level >= currentPrice and level <= upperLimit10
                    upperGridCount += 1
        
        
        if array.size(shortLevelsArray) > 0
            for i = 0 to array.size(shortLevelsArray) - 1
                float level = array.get(shortLevelsArray, i)
                if level >= currentPrice and level <= upperLimit10
                    upperGridCount += 1
                    
        string status = "Anlık Fiyat: " + str.tostring(currentPrice, "#.##") + " TL\n" + 
                       "10:00 Açılış Üst Limiti (%10): " + str.tostring(upperLimit10, "#.##") + " TL\n" +
                       "Anlık fiyat ile 10:00 açılış fiyatının %10 üst sınırı arasındaki grid sayısı: " + str.tostring(upperGridCount)
                       
        [upperGridCount, status]


if barstate.islast and window()
    [sellOrderCount, sellOrderStatus] = calculateTotalSellOrders()
    totalSellOrderCount := sellOrderCount
    totalSellOrderStatus := sellOrderStatus
    
    [inRangeGrids, rangeGridStatus, highGrid, lowGrid, inUpperRangeGrids, upperRangeStatus] = calculateGridsInPriceRange()
    gridsInPriceRange := inRangeGrids
    priceRangeGridStatus := rangeGridStatus
    highestGridInRange := highGrid
    lowestGridInRange := lowGrid
    gridsInUpperRange := inUpperRangeGrids
    upperRangeGridStatus := upperRangeStatus
    
   
    [currentUpperCount, currentUpperStatus] = calculateCurrentPriceToOpeningUpperRange()
    currentPriceUpperGridCount := currentUpperCount
    currentPriceUpperGridStatus := currentUpperStatus

var int lastOrderTime1Grid = -1 
var int lastOrderTime2Grid = -1 
var int lastProcessedSellGrid = -1  

var int currentGrid = na
var int maxIndex = na


if window() and not priceHitsLimits() and islem_yapilabilir 
    exchange_style = true  
    float currentPrice = close
    
    if alim_yontemi == "lmt"
        
        if not is_first_grid_calculation_completed
            gridLevelsArray := calcGridLevels(topLevel, bottomLevel, referencePrice, gridLevels)
           
            if array.size(gridLevelsArray) > 0
                
                array.clear(longLevelsArray)
                array.clear(shortLevelsArray)
               
                for i = 0 to array.size(gridLevelsArray) - 1
                    if arrayIndexValidFloat(i, gridLevelsArray)
                        float level = array.get(gridLevelsArray, i)
                        
                        float adjustedLevel = level
                        if level < 20.00
                            adjustedLevel := math.round(level * 100) / 100    
                        else if level < 50.00
                            adjustedLevel := math.round(level * 50) / 50      
                        else if level < 100.00
                            adjustedLevel := math.round(level * 20) / 20      
                        else if level < 250.00
                            adjustedLevel := math.round(level * 10) / 10     
                        else if level < 500.00
                            adjustedLevel := math.round(level * 4) / 4       
                        else if level < 1000.00
                            adjustedLevel := math.round(level * 2) / 2       
                        else
                            adjustedLevel := math.round(level)                

                        
                        if checkPriceLimit(adjustedLevel, bottomLevel, topLevel)
                            
                            if mode == "Yatay" or mode == "Uzun"
                                if adjustedLevel <= referencePrice
                                    array.push(longLevelsArray, adjustedLevel)
                            if mode == "Yatay" or mode == "Kısa"
                                if adjustedLevel >= referencePrice
                                    array.push(shortLevelsArray, adjustedLevel)

                is_first_grid_calculation_completed := true

        
        if array.size(gridHasActiveBuyOrder) == 0 and array.size(longLevelsArray) > 0
            gridLevels = array.size(longLevelsArray)
            
           
            array.clear(gridHasActiveBuyOrder)
            array.clear(gridHasActiveSellOrder)
            array.clear(gridHasPosition)
            array.clear(gridShowSellOrder)
            array.clear(gridShowBuyOrder)

            
            for i = 0 to gridLevels - 1
                array.push(gridHasActiveBuyOrder, false)
                array.push(gridHasActiveSellOrder, false)
                array.push(gridHasPosition, false)
                array.push(gridShowSellOrder, false)
                array.push(gridShowBuyOrder, false)

        
        if array.size(independentPositions) == 0
            for i = 0 to maxIndependentPositions - 1
                array.push(independentPositions, false)
                array.push(independentLevels, 0.0)


        
        if isEntryTime() and not initialOrdersSent1 and alim_yontemi == "lmt"
            var bool anyOrderPlaced = false
            int availableIndex = -1
            for i = 0 to array.size(independentPositions) - 1
                if not array.get(independentPositions, i)
                    availableIndex := i
                    break

            
            if userUpperGridCount > 0
                if availableIndex != -1
                    array.set(independentPositions, availableIndex, true)
                    anyOrderPlaced := true
                    initialOrdersSent1 :=true
                    alert('{"name": "💸 Piyasa Girişi Başlangıç ' + str.tostring(currentPrice) + '🔵⚡ ","symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "mktbest",' +'"price": "' + str.tostring(fix_cl_per_level * currentPriceUpperGridCount ) + '", "quantity": "' + str.tostring(fix_cl_per_level * (userUpperGridCount+userUpperGridCount10)) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
              
                
                if anyOrderPlaced
                    initialOrdersSent := true

        
        if isOrderTime() and initialOrdersSent1 and not initialOrdersSent2 and array.size(longLevelsArray) > 0
            float lotPerGrid = fix_cl_per_level 
            int currentUpperGrid = getCurrentGridIndex(currentPrice, longLevelsArray)
            int maxUpperIndex = array.size(longLevelsArray) - 1
            var bool anyOrderPlaced = false
            
           
            if currentUpperGrid != -1 and currentUpperGrid <= maxUpperIndex
                if userUpperGridCount >= 1 and (currentUpperGrid - 1) >= 0
                    if isValidGridLevel(currentUpperGrid - 1, array.size(longLevelsArray))
                        float sellLevel1 = array.get(longLevelsArray, currentUpperGrid - 1)
                        if checkPriceLimit(sellLevel1, bottomLevel, topLevel)
                            if not pozisyonVarMi(sellLevel1)
                                alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel1) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel1) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}') 
                                initialOrdersSent2 := true
                                array.set(gridHasActiveSellOrder, currentUpperGrid - 1, true)
                                array.set(gridShowSellOrder, currentUpperGrid - 1, true)
                                totalSellOrders := totalSellOrders + 1

                if userUpperGridCount >= 2 and (currentUpperGrid - 2) >= 0
                    if isValidGridLevel(currentUpperGrid - 2, array.size(longLevelsArray))
                        float sellLevel2 = array.get(longLevelsArray, currentUpperGrid - 2)
                        if checkPriceLimit(sellLevel2, bottomLevel, topLevel)
                            if not pozisyonVarMi(sellLevel2)
                                alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel2) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel2) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}') 
                                initialOrdersSent2 := true
                                array.set(gridHasActiveSellOrder, currentUpperGrid - 2, true)
                                array.set(gridShowSellOrder, currentUpperGrid - 2, true)
                                totalSellOrders := totalSellOrders + 1

                if userUpperGridCount >= 3 and (currentUpperGrid - 3) >= 0
                    if isValidGridLevel(currentUpperGrid - 3, array.size(longLevelsArray))
                        float sellLevel3 = array.get(longLevelsArray, currentUpperGrid - 3)
                        float sellLevel44 = array.get(longLevelsArray, currentUpperGrid - 4)

                        if checkPriceLimit(sellLevel3, bottomLevel, topLevel)
                            if not pozisyonVarMi(sellLevel3)
                                alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel3) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel3) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}') 
                                initialOrdersSent2 := true
                                array.set(gridHasActiveSellOrder, currentUpperGrid - 3, true)
                                array.set(gridShowSellOrder, currentUpperGrid - 3, true)
                                totalSellOrders := totalSellOrders + 1
                                lastProcessedSellGrid := currentUpperGrid - 3  

    
       
        if isOrderTime80() and initialOrdersSent1  and array.size(longLevelsArray) > 0
            
            var bool anyOrderPlaced = false
            
            int availableIndex = -1
            for i = 0 to array.size(independentPositions) - 1
                if not array.get(independentPositions, i)
                    availableIndex := i
                    break

            int maxIndex = array.size(longLevelsArray) - 1
            int currentGrid = getCurrentGridIndex(currentPrice, longLevelsArray)
            
            if currentGrid != -1
                if userGridCount >= 1 and isValidGridLevel(currentGrid + 1, array.size(longLevelsArray))
                    
                    if userGridCount >= 1
                        if currentGrid + 1 <= maxIndex
                            float buyLevel = array.get(longLevelsArray, currentGrid + 1)
                            if checkPriceLimit(buyLevel, bottomLevel, topLevel)
                                if not emirVarMi(buyLevel) and not pozisyonVarMi(buyLevel) 
                                    alert('{"name": "💥 AL Emri 🟢 ' + str.tostring(buyLevel) + ' fiyatından gönderildi","symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(buyLevel) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')
                                    
                                    array.set(gridHasActiveBuyOrder, currentGrid + 1, true)
                                    array.set(gridShowBuyOrder, currentGrid + 1, true)
                                    anyOrderPlaced := true
                                    totalBuyOrders := totalBuyOrders + 1

               
                if userGridCount >= 2
                    if currentGrid + 2 <= maxIndex
                        if userGridCount >= 2 and isValidGridLevel(currentGrid + 2, array.size(longLevelsArray))
                            float nextBuyLevel = array.get(longLevelsArray, currentGrid + 2)  
                            if checkPriceLimit(nextBuyLevel, bottomLevel, topLevel)
                                if not emirVarMi(nextBuyLevel) and not pozisyonVarMi(nextBuyLevel) 
                                    
                                    alert('{"name": "💥 AL Emri 🟢 ' + str.tostring(nextBuyLevel) + ' fiyatından gönderildi","symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(nextBuyLevel) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                    array.set(gridHasActiveBuyOrder, currentGrid + 2, true)
                                    array.set(gridShowBuyOrder, currentGrid + 2, true)
                                    anyOrderPlaced := true
                                    totalBuyOrders := totalBuyOrders + 1

               
                if userGridCount >= 3
                    if currentGrid + 3 <= maxIndex
                        if userGridCount >= 3 and isValidGridLevel(currentGrid + 3, array.size(longLevelsArray))
                            float thirdBuyLevel = array.get(longLevelsArray, currentGrid + 3)
                            if checkPriceLimit(thirdBuyLevel, bottomLevel, topLevel)
                                if not emirVarMi(thirdBuyLevel) and not pozisyonVarMi(thirdBuyLevel) 
                                    alert('{"name": "💥 AL Emri 🟢 ' + str.tostring(thirdBuyLevel) + ' fiyatından gönderildi","symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(thirdBuyLevel) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')
                                    
                                    array.set(gridHasActiveBuyOrder, currentGrid + 3, true)
                                    array.set(gridShowBuyOrder, currentGrid + 3, true)
                                    anyOrderPlaced := true
                                    totalBuyOrders := totalBuyOrders + 1

        if isOrderTime1() and initialOrdersSent1 and initialOrdersSent2 and not initialOrdersSent3 and array.size(longLevelsArray) > 0 and lastProcessedSellGrid != -1
            float lotPerGrid = fix_cl_per_level 
            int nextGrid = lastProcessedSellGrid - 1 
    
            if userUpperGridCount >= 4 and nextGrid >= 0
                if isValidGridLevel(nextGrid, array.size(longLevelsArray))
                    float sellLevel4 = array.get(longLevelsArray, nextGrid)
                    if checkPriceLimit(sellLevel4, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel4)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel4) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel4) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid, true)
                            array.set(gridShowSellOrder, nextGrid, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid

            if userUpperGridCount >= 5 and (nextGrid - 1) >= 0
                if isValidGridLevel(nextGrid - 1, array.size(longLevelsArray))
                    float sellLevel5 = array.get(longLevelsArray, nextGrid - 1)
                    if checkPriceLimit(sellLevel5, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel5)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel5) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel5) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid - 1, true)
                            array.set(gridShowSellOrder, nextGrid - 1, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid - 1

            if userUpperGridCount >= 6 and (nextGrid - 2) >= 0
                if isValidGridLevel(nextGrid - 2, array.size(longLevelsArray))
                    float sellLevel6 = array.get(longLevelsArray, nextGrid - 2)
                    if checkPriceLimit(sellLevel6, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel6)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel6) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel6) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid - 2, true)
                            array.set(gridShowSellOrder, nextGrid - 2, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid - 2

            if userUpperGridCount >= 7 and (nextGrid - 3) >= 0
                if isValidGridLevel(nextGrid - 3, array.size(longLevelsArray))
                    float sellLevel7 = array.get(longLevelsArray, nextGrid - 3)
                    if checkPriceLimit(sellLevel7, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel7)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel7) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel7) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid - 3, true)
                            array.set(gridShowSellOrder, nextGrid - 3, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid - 3

            if userUpperGridCount >= 8 and (nextGrid - 4) >= 0
                if isValidGridLevel(nextGrid - 4, array.size(longLevelsArray))
                    float sellLevel8 = array.get(longLevelsArray, nextGrid - 4)
                    if checkPriceLimit(sellLevel8, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel8)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel8) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel8) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid - 4, true)
                            array.set(gridShowSellOrder, nextGrid - 4, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid - 4

            if userUpperGridCount >= 9 and (nextGrid - 5) >= 0
                if isValidGridLevel(nextGrid - 5, array.size(longLevelsArray))
                    float sellLevel9 = array.get(longLevelsArray, nextGrid - 5)
                    if checkPriceLimit(sellLevel9, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel9)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel9) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel9) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid - 5, true)
                            array.set(gridShowSellOrder, nextGrid - 5, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid - 5

            if userUpperGridCount >= 10 and (nextGrid - 6) >= 0
                if isValidGridLevel(nextGrid - 6, array.size(longLevelsArray))
                    float sellLevel10 = array.get(longLevelsArray, nextGrid - 6)
                    if checkPriceLimit(sellLevel10, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel10)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel10) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel10) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent3 := true
                            array.set(gridHasActiveSellOrder, nextGrid - 6, true)
                            array.set(gridShowSellOrder, nextGrid - 6, true)
                            totalSellOrders := totalSellOrders + 1
                            lastProcessedSellGrid := nextGrid - 6      

        if isOrderTime2() and initialOrdersSent1 and initialOrdersSent2 and initialOrdersSent3 and not initialOrdersSent4 and array.size(longLevelsArray) > 0 and lastProcessedSellGrid != -1
            float lotPerGrid = fix_cl_per_level 
    
            
            int startLevel20 = lastProcessedSellGrid  
            if userUpperGridCount10 >= 1
                if isValidGridLevel(startLevel20 - 1, array.size(longLevelsArray))
                    float sellLevel11 = array.get(longLevelsArray, startLevel20 - 1  )
                    if checkPriceLimit(sellLevel11, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel11)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel11) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel11) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent4 := true
                            array.set(gridHasActiveSellOrder, startLevel20 - 1, true)
                            array.set(gridShowSellOrder, startLevel20 - 1, true)
                            totalSellOrders := totalSellOrders + 1
                            lastOrderTime2Grid :=startLevel20 - 1

            if userUpperGridCount10 >= 2
                if isValidGridLevel(startLevel20 - 2, array.size(longLevelsArray))
                    float sellLevel12 = array.get(longLevelsArray, startLevel20 - 2)
                    if checkPriceLimit(sellLevel12, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel12)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel12) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel12) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent4 := true
                            array.set(gridHasActiveSellOrder, startLevel20 - 2, true)
                            array.set(gridShowSellOrder, startLevel20 - 2, true)
                            totalSellOrders := totalSellOrders + 1
                            lastOrderTime2Grid :=startLevel20 - 2

            if userUpperGridCount10 >= 3
                if isValidGridLevel(startLevel20 - 3, array.size(longLevelsArray))
                    float sellLevel13 = array.get(longLevelsArray, startLevel20 - 3)
                    if checkPriceLimit(sellLevel13, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel13)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel13) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel13) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent4 := true
                            array.set(gridHasActiveSellOrder, startLevel20 - 3, true)
                            array.set(gridShowSellOrder, startLevel20 - 3, true)
                            totalSellOrders := totalSellOrders + 1
                            lastOrderTime2Grid :=startLevel20 - 3

            if userUpperGridCount10 >= 4
                if isValidGridLevel(startLevel20 - 4, array.size(longLevelsArray))
                    float sellLevel14 = array.get(longLevelsArray, startLevel20 - 4)
                    if checkPriceLimit(sellLevel14, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel14)
                            alert('{"name": "💥SAT Emri 🔴 ' + str.tostring(sellLevel14) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel14) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent4 := true
                            array.set(gridHasActiveSellOrder, startLevel20 - 4, true)
                            array.set(gridShowSellOrder, startLevel20 - 4, true)
                            totalSellOrders := totalSellOrders + 1
                            lastOrderTime2Grid :=startLevel20 - 4

            if userUpperGridCount10 >= 5
                if isValidGridLevel(startLevel20 - 5, array.size(longLevelsArray))
                    float sellLevel15 = array.get(longLevelsArray, startLevel20 - 5)
                    if checkPriceLimit(sellLevel15, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel15)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel15) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel15) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent4 := true
                            array.set(gridHasActiveSellOrder, startLevel20 - 5, true)
                            array.set(gridShowSellOrder, startLevel20 - 5, true)
                            totalSellOrders := totalSellOrders + 1
                            lastOrderTime2Grid :=startLevel20 - 5

        
        if isOrderTime60() and initialOrdersSent1 and initialOrdersSent2 and initialOrdersSent3 and initialOrdersSent4 and not initialOrdersSent5 and array.size(longLevelsArray) > 0 and lastOrderTime2Grid != -1
            float lotPerGrid = fix_cl_per_level           
            int startLevel44 = lastOrderTime2Grid  
            if userUpperGridCount10 >= 6
                if isValidGridLevel(startLevel44 - 1, array.size(longLevelsArray))
                    float sellLevel16 = array.get(longLevelsArray, startLevel44 - 1)
                    if checkPriceLimit(sellLevel16, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel16)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel16) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel16) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent5 := true
                            array.set(gridHasActiveSellOrder, startLevel44 - 1, true)
                            array.set(gridShowSellOrder, startLevel44 - 1, true)
                            totalSellOrders := totalSellOrders + 1

            if userUpperGridCount10 >= 7
                if isValidGridLevel(startLevel44 - 2, array.size(longLevelsArray))
                    float sellLevel17 = array.get(longLevelsArray, startLevel44 - 2)
                    if checkPriceLimit(sellLevel17, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel17)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel17) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel17) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent5 := true
                            array.set(gridHasActiveSellOrder, startLevel44 - 2, true)
                            array.set(gridShowSellOrder, startLevel44 - 2, true)
                            totalSellOrders := totalSellOrders + 1

            if userUpperGridCount10 >= 8
                if isValidGridLevel(startLevel44 - 3, array.size(longLevelsArray))
                    float sellLevel18 = array.get(longLevelsArray, startLevel44 - 3)
                    if checkPriceLimit(sellLevel18, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel18)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel18) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel18) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent5 := true
                            array.set(gridHasActiveSellOrder, startLevel44 - 3, true)
                            array.set(gridShowSellOrder, startLevel44 - 3, true)
                            totalSellOrders := totalSellOrders + 1

            if userUpperGridCount10 >= 9
                if isValidGridLevel(startLevel44 - 4, array.size(longLevelsArray))
                    float sellLevel19 = array.get(longLevelsArray, startLevel44 - 4)
                    if checkPriceLimit(sellLevel19, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel19)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel19) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel19) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent5 := true
                            array.set(gridHasActiveSellOrder, startLevel44 - 4, true)
                            array.set(gridShowSellOrder, startLevel44 - 4, true)
                            totalSellOrders := totalSellOrders + 1

            if userUpperGridCount10 >= 10
                if isValidGridLevel(startLevel44 - 5, array.size(longLevelsArray))
                    float sellLevel20 = array.get(longLevelsArray, startLevel44 - 5)
                    if checkPriceLimit(sellLevel20, bottomLevel, topLevel)
                        if not pozisyonVarMi(sellLevel20)
                            alert('{"name": "💥 SAT Emri 🔴 ' + str.tostring(sellLevel20) + ' fiyatından gönderildi",\"symbol\": \"' + syminfo.ticker + '\", \"orderSide\": \"sell\", \"orderType\": \"lmt\", ' +'\"price\": \"' + str.tostring(sellLevel20) + '\", \"quantity\": \"' + str.tostring(lotPerGrid) +'\", \"timeInForce\": \"day\", \"apiKey\": \"' + apikey + '\",\"token\":\"' + token + '\"}')
                            initialOrdersSent5 := true
                            array.set(gridHasActiveSellOrder, startLevel44 - 5, true)
                            array.set(gridShowSellOrder, startLevel44 - 5, true)
                            totalSellOrders := totalSellOrders + 1


        
        if array.size(longLevelsArray) > 0
            maxIndex = array.size(longLevelsArray) - 1
    
            for i = 0 to maxIndex
                if arrayIndexValid(i, gridHasActiveSellOrder) and arrayIndexValidFloat(i, longLevelsArray)
                    exitLevel33 = array.get(longLevelsArray, i)

                    
                    if array.get(gridHasActiveSellOrder, i)
                        if high > exitLevel33
                            var currentGridIndex = getCurrentGridIndex(high, longLevelsArray)
                            var previousGridIndex = getCurrentGridIndex(exitLevel33, longLevelsArray)
                            var gridDifference = currentGridIndex - previousGridIndex                      
                            array.set(gridHasActiveSellOrder, i, false)
                            array.set(gridShowSellOrder, i, false)                           
                            if isValidGridLevel(i + 1, array.size(longLevelsArray)) and not array.get(gridHasActiveBuyOrder, i + 1) and not emirVarMi(array.get(longLevelsArray, i + 1)) and gridDifference < 1
                                float buyLevelzz = array.get(longLevelsArray, i + 1)
                                alert('{"name": "💥 ' + str.tostring(exitLevel33) + ' SATIŞ Gerçekleşti ve 🔴 ' + str.tostring(buyLevelzz) + ' bu fiyata al emri gönderildi 🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' + '"price": "' + str.tostring(buyLevelzz) + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')
                                array.set(gridHasActiveBuyOrder, i + 1, true)  
                                array.set(gridShowBuyOrder, i + 1, true)     
                                totalBuyOrders := totalBuyOrders + 1 

        if array.size(longLevelsArray) > 0
            maxIndex = array.size(longLevelsArray) - 1
            
            for i = 0 to maxIndex
                if arrayIndexValid(i, gridHasActiveBuyOrder) and 
                   arrayIndexValid(i, gridHasPosition) and 
                   arrayIndexValidFloat(i, longLevelsArray)

                    tradeLevel = array.get(longLevelsArray, i)
                    var lastTradeTime = array.new_int(array.size(longLevelsArray), 0)
                    
                    // İlk kontrol: Gerçekten bu grid seviyesinde aktif bir AL emri var mı?
                    if array.get(gridHasActiveBuyOrder, i) and not array.get(gridHasPosition, i)
                        // İkinci kontrol: Fiyat bu grid seviyesinin altına düştü mü?
                        if low < tradeLevel 
                            
                            // Büyük düşüşleri kontrol etmek için grid farklarını hesaplama
                            var currentGridIndex = getCurrentGridIndex(low, longLevelsArray)
                            var previousGridIndex = getCurrentGridIndex(tradeLevel, longLevelsArray)
                            var gridDifference = previousGridIndex - currentGridIndex
                            
                            var currentTime = time
                            var timeElapsed = currentTime - array.get(lastTradeTime, i)
            
                            // Önemli: Burada pozisyonun olmadığı, zaman aralığının uygun olduğu VE
                            // grid seviyesinde AL emrinin aktif olduğunu kontrol ediyoruz
                            if not pozisyonVarMi(tradeLevel) and timeElapsed >= 1 and array.get(gridHasActiveBuyOrder, i)
                                array.set(lastTradeTime, i, currentTime)
                                
                                // Pozisyon yoksa açalım
                                if not array.get(gridHasPosition, i)
                                    array.set(gridHasPosition, i, true)
                                    array.set(gridHasActiveBuyOrder, i, false)
                                    array.set(gridShowBuyOrder, i, false)
                                        
                                    // Pozisyon açıldığında ilgili SAT/AL emirlerini oluşturalım
                                    if array.get(gridHasPosition, i)
                                            
                                        float satgonder = na
                                        float gonder1 = na
                                        float gonder2 = na
                                        float gonder3 = na

                                        // Sat emri fiyatını hesaplama (bir üst grid)
                                        if i > 0 and i - 1 < array.size(longLevelsArray)
                                            satgonder := array.get(longLevelsArray, i - 1)

                                        // Alt gridler için al emri fiyatlarını hesaplama
                                        if i + 1 < array.size(longLevelsArray)
                                            gonder1 := array.get(longLevelsArray, i + 1)

                                        if i + 2 < array.size(longLevelsArray)
                                            gonder2 := array.get(longLevelsArray, i + 2)

                                        if i + 3 < array.size(longLevelsArray)
                                            gonder3 := array.get(longLevelsArray, i + 3)

                                        // Sat emirlerini gönderme
                                        if not na(satgonder) and i > 0 and isValidGridLevel(i - 1, array.size(longLevelsArray))
                                            if not array.get(gridHasActiveSellOrder, i - 1) and not emirVarMi(satgonder)
                                                alert('{"name": "🔥 ' + str.tostring(tradeLevel) + ' Fiyatından Pozisyona Girildi 🔵 ve ' + str.tostring(satgonder) + ' Fiyatına SAT Emri Gönderildi 🔴", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "lmt", ' + '"price": "' + str.tostring(satgonder) + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')
                                                array.set(gridHasActiveSellOrder, i - 1, true)
                                                array.set(gridShowSellOrder, i - 1, true)
                                                array.set(gridHasActiveBuyOrder, i, false)
                                                array.set(gridShowBuyOrder, i, false)
                                                totalSellOrders := totalSellOrders + 1
                                                totalOpenTrades := totalOpenTrades + 1

                                        // Alt grid seviyelerine al emirleri gönderme
                                        if not na(gonder1) and isValidGridLevel(i + 1, array.size(longLevelsArray))
                                            if not array.get(gridHasActiveBuyOrder, i + 1) and not emirVarMi(gonder1)
                                                alert('{"name": "🔥 ' + str.tostring(gonder1) + '🔵🟢 Pozisyon Sonrası AL Emri Gönderildi ", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder1) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                                array.set(gridHasActiveBuyOrder, i + 1, true)
                                                array.set(gridShowBuyOrder, i + 1, true)
                                                totalBuyOrders := totalBuyOrders + 1

                                        if not na(gonder2) and isValidGridLevel(i + 2, array.size(longLevelsArray))
                                            if not array.get(gridHasActiveBuyOrder, i + 2) and not emirVarMi(gonder2)
                                                alert('{"name": "🔥 ' + str.tostring(gonder2) + '🔵🟢 Pozisyon Sonrası AL Emri Gönderildi", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder2) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                                array.set(gridHasActiveBuyOrder, i + 2, true)
                                                array.set(gridShowBuyOrder, i + 2, true)
                                                totalBuyOrders := totalBuyOrders + 1

                                        if not na(gonder3) and isValidGridLevel(i + 3, array.size(longLevelsArray))
                                            if not array.get(gridHasActiveBuyOrder, i + 3) and not emirVarMi(gonder3)
                                                alert('{"name": "🔥 ' + str.tostring(gonder3) + '🔵🟢 Pozisyon Sonrası AL Emri Gönderildi", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder3) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                                array.set(gridHasActiveBuyOrder, i + 3, true)
                                                array.set(gridShowBuyOrder, i + 3, true)
                                                totalBuyOrders := totalBuyOrders + 1
                                        

                   
                    if array.get(gridHasPosition, i) and i > 0
                        exitLevel22 = array.get(longLevelsArray, i - 1)
                        exitLevel33 = array.get(longLevelsArray, i)
                        if high > exitLevel22 
                            totalClosedTrades := totalClosedTrades + 1

                            array.set(gridHasPosition, i, false)
                            array.set(gridHasActiveSellOrder, i - 1, false)
                            array.set(gridShowSellOrder,i - 1, false)
                            
                                                          
                            if not emirVarMi(array.get(longLevelsArray, i)) and high < exitLevel33
                                array.set(gridHasActiveBuyOrder, i, true)
                                array.set(gridShowBuyOrder, i, true)
                                totalBuyOrders := totalBuyOrders + 1
                                
                                alert('{"name": "' + str.tostring(exitLevel22) + '🟠 ✅ Pozisyon Kapatıldı  ' + str.tostring(array.get(longLevelsArray, i)) + ' 🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", "price": "' + str.tostring(array.get(longLevelsArray, i)) + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 


if window() and not priceHitsLimits() and islem_yapilabilir  
    exchange_style = (grid_calculation == 'SABİT GRİD')

    
    

    if mode == "Yatay" or mode == "Uzun" and  alim_yontemi == "mktbest"
        for i = 0 to array.size(longLevelsArray) - 1
            level = roundToMinMove(array.get(longLevelsArray, i))
            level_str = str.tostring(level)

            entry_level_comment = "Long" + str.tostring(i+1)
            exit_level_comment  = "Long Tp" + str.tostring(i+1)
            condition = entry_condition == 'Malsız Başla'  ? close > level : true

            if condition   and not levelHasOpenTrade(entry_level_comment) 

                tp_level = float(na)
                if i > 1
                    nextLevel = array.get(longLevelsArray, i-1)
                    nextNextLevel = array.get(longLevelsArray, i -2)
                    tp_level := exchange_style ? nextLevel : nextNextLevel                  
                else if i == 1
                    highestLongLevel = array.get(longLevelsArray, i - 1)
                    tp_level := exchange_style ? highestLongLevel  : (highestLongLevel + referencePrice) / 2
                else if i == 0 and mode == "Yatay"
                    tp_level := exchange_style ? referencePrice : (referencePrice + array.get(shortLevelsArray, 0)) / 2
                else if i == 0 and mode == "Uzun"
                    highestLongLevel = array.get(longLevelsArray, i)
                    last_dff  = referencePrice - (highestLongLevel + referencePrice) / 2
                    tp_level := exchange_style ? referencePrice : referencePrice + last_dff
                if not na(tp_level) 
                    qty = calculateLotSize(lotStrategy, fix_cl_per_level, i, level, referencePrice)
                   
                    
                    float commission = qty * level * (komisyon / 100) 
                    sell_qty_long =  qty
                    float exit_commission = sell_qty_long * tp_level * (komisyon / 100) 
                    float total_commission = commission + exit_commission

                   
                    string pnlText = "Son Fiyat: " + str.tostring(close, "#.##") + " TL\n" 
                    if strategy.closedtrades == 0
                        pnlText += "Tamamlanan Islemler K/Z: ₺0.00\n" + "Acik Islemler K/Z: ₺" + str.tostring(strategy.openprofit, "#.##") + "\n" + "Toplam Komisyon: ₺" + str.tostring(total_commission, "#.##") + "\n" + "Toplam K/Z: ₺" + str.tostring(strategy.openprofit - total_commission, "#.##")
                    else
                        float total = strategy.netprofit + strategy.openprofit - total_commission
                        pnlText += "Tamamlanan Islemler K/Z: ₺" + str.tostring(strategy.netprofit, "#.##") + "\n" + "Acik Islemler K/Z: ₺" + str.tostring(strategy.openprofit, "#.##") + "\n" + "Toplam Komisyon: ₺" + str.tostring(total_commission, "#.##") + "\n" + "Toplam K/Z: ₺" + str.tostring(total, "#.##")
  
                    longEntryTime := time
                    
                    strategy.entry(id="Buy@" + level_str, direction = strategy.long, qty = qty, comment=entry_level_comment , limit=level, alert_message = '{"name": "' + alarm_ismi1 + ' Grid-' + str.tostring(array.size(longLevelsArray) - i) + ' Fiyat: ' + str.tostring(level, "#.##") + ' 🚀 [LONG] Emir Gönderildi | ' + pnlText + '", "symbol": "' + "{{ticker}}" + '", "orderSide": "buy", "orderType": "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri) + '", "quantity": "' + str.tostring(qty) + '", "timeInForce": "day", "apiKey": "' + str.tostring(apikey) + '", "timenow":"{{timenow}}"}')
                    strategy.exit(id=("TP@" + level_str), from_entry = ("Buy@" + level_str), comment=exit_level_comment , limit=tp_level, qty=sell_qty_long, alert_message = '{"name": "' + alarm_ismi2 + ' Grid-' + str.tostring(array.size(longLevelsArray) - i) + ' Fiyat: ' + str.tostring(tp_level, "#.##") + ' 🚀 [LONG-EXIT] Emir Gönderildi | ' + pnlText + ' Biriktirilen Lot: ' + str.tostring(biriktirilmis_lot) + '", "symbol": "' + "{{ticker}}" + '", "orderSide": "sell", "orderType": "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri) + '", "quantity": "' + str.tostring(sell_qty_long) + '", "timeInForce": "day", "apiKey": "' + str.tostring(apikey) + '", "timenow":"{{timenow}}"}')
                               

    if mode == "Yatay" or mode == "Kısa" and  alim_yontemi == "mktbest" 
        for i = 0 to array.size(shortLevelsArray) - 1

            level = roundToMinMove(array.get(shortLevelsArray, i))
            level_str = str.tostring(level)
            entry_level_comment = "Short" + str.tostring(i+1)
            exit_level_comment  = "Short Tp" + str.tostring(i+1)
            condition = entry_condition == 'Malsız Başla' ? close < level : true

            if condition and not levelHasOpenTrade(entry_level_comment)
               
                tp_level = float(na)
                if i > 1 
                    prevLevel = array.get(shortLevelsArray, i - 1)
                    prevPrevLevel = array.get(shortLevelsArray, i - 2)
                    tp_level := exchange_style ? prevLevel : (prevLevel + prevPrevLevel) / 2
                else if i == 1 
                    lowestShortLevel = array.get(shortLevelsArray, i - 1)
                    tp_level := exchange_style ? lowestShortLevel : (lowestShortLevel + referencePrice) / 2
                
                else if i == 0 and mode == "Yatay"
                    tp_level := exchange_style ? referencePrice : (referencePrice + array.get(longLevelsArray, 0)) / 2
                else if i == 0 and mode == "Kısa"
                    lowestShortLevel = array.get(shortLevelsArray, i)
                    last_dff  = (lowestShortLevel + referencePrice) / 2 - referencePrice
                    tp_level := exchange_style ? referencePrice : referencePrice - last_dff

                if not na(tp_level) 
                    
                    qty = calculateLotSize(lotStrategy, fix_cl_per_level, i, level, referencePrice)
                    shortEntryTime := time

                    
                    float commission = qty * level * (komisyon / 100) 
                    float exit_commission = qty * tp_level * (komisyon / 100) 
                    float total_commission = commission + exit_commission

                    
                    string karZararText = ""
                    if strategy.closedtrades == 0
                        karZararText := "Tamamlanan: ₺0.00\n" + 
                                 "Acik: ₺" + str.tostring(strategy.openprofit, "#.##") + "\n" + 
                                 "Toplam Komisyon: ₺" + str.tostring(total_commission, "#.##") + "\n" + 
                                 "Toplam: ₺" + str.tostring(strategy.openprofit - total_commission, "#.##")
                    else 
                        float overallPnL = strategy.netprofit + strategy.openprofit - total_commission
                        karZararText := "Tamamlanan: ₺" + str.tostring(strategy.netprofit, "#.##") + "\n" + 
                                 "Acik: ₺" + str.tostring(strategy.openprofit, "#.##") + "\n" + 
                                 "Toplam Komisyon: ₺" + str.tostring(total_commission, "#.##") + "\n" + 
                                 "Toplam: ₺" + str.tostring(overallPnL, "#.##")

                    
                    strategy.entry(id = ("Sell@" + level_str), direction = strategy.short, qty = qty, comment=entry_level_comment , limit=level, alert_message = '{"name": "' + alarm_ismi5 + ' Grid-' + str.tostring(i + 1) + ' Fiyat: ' + str.tostring(level, "#.##") + ' 🚀 [SHORT] Emir Gönderildi | ' + karZararText + '", "symbol": "' + "{{ticker}}" + '", "orderSide": "sell", "orderType": "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri) + '", "quantity": "' + str.tostring(qty) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                    strategy.exit(id = ("TP@" + level_str), from_entry = ("Sell@" + level_str), comment = exit_level_comment , limit=tp_level, alert_message = '{"name": "' + alarm_ismi6 + ' Grid-' + str.tostring(i + 1) + ' Fiyat: ' + str.tostring(tp_level, "#.##") + ' 🚀 [SHORT-EXIT] Emir Gönderildi | ' + karZararText + '", "symbol": "' + "{{ticker}}" + '", "orderSide": "buy", "orderType": "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri) + '", "quantity": "' + str.tostring(qty) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 

else
    if not window() and close_at_end_time  and  alim_yontemi == "mktbest" 
        
        if strategy.position_size != 0
            strategy.cancel_all()
            if mode == "Uzun" and strategy.position_size > 0
                strategy.close_all(comment = 'Ayarlanan Süre Doldu ve Tüm İşlemler Kapatıldı ' + '(' + str.tostring(mode) + ' MOD)',immediately=true,alert_message='{"name": "' + alarm_ismi7 + ' Süre Doldu. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔻 [LONG-SÜRE] Emir Gönderildi ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
            else if mode == "Yatay"
                if strategy.position_size > 0
                    strategy.close_all(comment = 'Ayarlanan Süre Doldu ve Tüm İşlemler Kapatıldı ' + '(' + str.tostring(mode) + ' MOD)',immediately=true,alert_message='{"name": "' + alarm_ismi8 + ' Süre Doldu. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔻 [YATAY-LONG-SÜRE] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                if strategy.position_size < 0
                    strategy.close_all(comment = 'Ayarlanan Süre Doldu ve Tüm İşlemler Kapatıldı ' + '(' + str.tostring(mode) + ' MOD)',immediately=true,alert_message='{"name": "' + alarm_ismi8 + ' Süre Doldu. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔺 [YATAY-SHORT-SÜRE] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "buy", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
            else if mode == "Kısa" and strategy.position_size < 0
                strategy.close_all(comment = 'Ayarlanan Süre Doldu ve Tüm İşlemler Kapatıldı ' + '(' + str.tostring(mode) + ' MOD)',immediately=true,alert_message='{"name": "' + alarm_ismi9 + ' Süre Doldu. Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔺 [SHORT-SÜRE] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "buy", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
    





bar_before_last = last_bar_time - timeframe.in_seconds(timeframe.period)*1000


format_date(timestamp) =>
    
    date_str = str.tostring(dayofmonth(timestamp)) + "-" + str.tostring(month(timestamp)) + "-" + str.tostring(year(timestamp))
    
    hour_str = str.tostring(hour(timestamp))
    minute_str = str.tostring(minute(timestamp))
    
    minute_str := minute(timestamp) < 10 ? "0" + minute_str : minute_str
    
    date_str + "\n" + hour_str + ":" + minute_str

start_date_formatted = format_date(start)
finish_date_formatted = format_date(finish)



closeAllPositionsLong() =>
    strategy.cancel_all()
    strategy.close_all(comment = 'Kar/Zarar Seviyesi Ulaştı ve Tüm Long İşlemler Kapatıldı', immediately = true, alert_message='{"name": "Kar/Zarar Kapatma ⚠️ Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔻 [LONG-KZ] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 

closeAllPositionsShort() =>
    strategy.cancel_all()
    strategy.close_all(comment = 'Kar/Zarar Seviyesi Ulaştı ve Tüm Short İşlemler Kapatıldı', immediately = true, alert_message='{"name": "Kar/Zarar Kapatma ⚠️ Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔺 [SHORT-KZ] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "buy", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 

closeAllPositionsYatay() =>
    strategy.cancel_all()
    if (strategy.position_size > 0)
        strategy.close_all(comment = 'Kar/Zarar Seviyesi Ulaştı ve Tüm Yatay Long İşlemler Kapatıldı', immediately = true, alert_message='{"name": "Kar/Zarar Kapatma ⚠️ Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔻 [YATAY-LONG-KZ] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "sell", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
    else if (strategy.position_size < 0)
        strategy.close_all(comment = 'Kar/Zarar Seviyesi Ulaştı ve Tüm Yatay Short İşlemler Kapatıldı', immediately = true, alert_message='{"name": "Kar/Zarar Kapatma ⚠️ Fiyat: ' + str.tostring(sembol_degeri, "#.##") + ' 🔺 [YATAY-SHORT-KZ] Emir Gönderildi  ", "symbol": "' + "{{ticker}}"  + '", "orderSide": "buy", "orderType":  "' + str.tostring(alim_yontemi) + '", "price": "' + str.tostring(sembol_degeri, "#.##") + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 





uzun_grid = input.color(title="Uzun Grid Rengi", defval=color.rgb(151, 161, 159), group="Grid Renk Ayarları")
kisa_grid = input.color(title="Kisa Grid Rengi", defval=color.rgb(179, 190, 19), group="Grid Renk Ayarları")
uzun_grid_cizgi = input.color(title="Uzun Grid Çizgi Rengi", defval=color.rgb(6, 7, 7), group="Grid Renk Ayarları")
kisa_grid_cizgi = input.color(title="Kisa Grid Çizgi Rengi", defval=color.rgb(6, 7, 7), group="Grid Renk Ayarları")

if window()

    var int total_grids = gridLevels + 1  
    var int middle_grid = math.ceil(total_grids / 2)  

  
    if mode == "Yatay"
        line.new(x1=startBarTime, y1=referencePrice, x2=finishBarTime, y2=referencePrice, xloc=xloc.bar_time, width=1, color=#1120e7, style=line.style_solid)
        formatted_referencePrice = str.tostring(referencePrice, "#.##")
        label.new(x=startBarTime, y=referencePrice, xloc=xloc.bar_time, text="🔄 Grid-Dönüş Bölgesi: " + formatted_referencePrice + " TL", style=label.style_label_right, color=#1120e7, textcolor=color.white, size=size.small)
        label.new(x=finishBarTime, y=referencePrice, xloc=xloc.bar_time, text="🔄 Grid-Dönüş Bölgesi: " + formatted_referencePrice + " TL", style=label.style_label_left, color=#1120e7, textcolor=color.white, size=size.small)

    
    if mode == "Yatay" or mode == "Uzun"
        
        var bool has_any_orders = false
        if alim_yontemi == "lmt"
            for i = 0 to array.size(longLevelsArray) - 1
                if array.size(gridHasActiveBuyOrder) > i and array.size(gridHasActiveSellOrder) > i
                    if array.get(gridHasActiveBuyOrder, i) or array.get(gridHasActiveSellOrder, i) or array.get(gridHasPosition, i)
                        has_any_orders := true
                        break

        for i = 0 to array.size(longLevelsArray) - 1
            level = roundToMinMove(array.get(longLevelsArray, i))
            formatted_level = str.tostring(level, "#.##")
            
            
            string base_label_text = "GRİD " + str.tostring(i + 1) + "\n" + 
                                   formatted_level + " TL"

            
            string position_label_text = "GRİD " + str.tostring(i + 1) + "\n" + formatted_level + " TL\n" 
                                       

            if  alim_yontemi == "mktbest"
                
                line.new(x1=startBarTime, y1=level, x2=finishBarTime, y2=level, xloc=xloc.bar_time, width=1, color=uzun_grid_cizgi, style=line.style_dotted)
                label.new(x=startBarTime, y=level, xloc=xloc.bar_time, text=base_label_text, style=label.style_label_center, color=uzun_grid, size=size.small, textcolor=#0c0c0c, textalign=text.align_left)
                label.new(x=finishBarTime, y=level, xloc=xloc.bar_time, text=base_label_text, style=label.style_label_center, color=uzun_grid, size=size.small, textcolor=#0c0c0c, textalign=text.align_left)

            else if alim_yontemi == "lmt"
               
                line.new(x1=startBarTime, y1=level, x2=finishBarTime, y2=level, xloc=xloc.bar_time, width=1, color=uzun_grid_cizgi, style=line.style_dotted)  
                label.new(x=startBarTime, y=level, xloc=xloc.bar_time, text=base_label_text, style=label.style_label_center, color=uzun_grid, size=size.small, textcolor=#0c0c0c, textalign=text.align_center)
                label.new(x=finishBarTime, y=level, xloc=xloc.bar_time, text=base_label_text, style=label.style_label_center, color=uzun_grid, size=size.small, textcolor=#0c0c0c, textalign=text.align_center)
                


        if (mode == "Yatay" or mode == "Kısa") 
            for i = 0 to array.size(shortLevelsArray) - 1
                style_decision = (i == array.size(shortLevelsArray) - 1) ? line.style_dotted : line.style_dashed
                level = roundToMinMove(array.get(shortLevelsArray, i))  
                level_str = str.tostring(level)

                decimals_to_show = "0." + symbol_decimal_str(symbol_min_move())
                label_color2 = kisa_grid
                label_color200 = kisa_grid_cizgi

                formatted_level1 = str.tostring(level, "#.##") 
                grid_text1 = "🔻  "
                
                string base_label_text1 = "GRİD " + str.tostring(i + 1) + "\n" + formatted_level1 +  " TL"

                line.new(x1=startBarTime, y1=level, x2=finishBarTime, y2=level, xloc=xloc.bar_time, width=1, color=label_color200, style=line.style_dotted)
                label.new(x=finishBarTime, y=level, xloc=xloc.bar_time, text=base_label_text1, style=label.style_label_center, color=label_color2, size=size.small, textcolor=#0c0c0c, textalign=text.align_center)
                label.new(x=startBarTime, y=level, xloc=xloc.bar_time, text=base_label_text1, style=label.style_label_center, color=label_color2, size=size.small, textcolor=#0c0c0c, textalign=text.align_center)

                if mode == "Kısa" and i == 0 and (grid_calculation != 'SABİT GRİD') 
                    new_trigger_line = ((3 * referencePrice - level) / 2)
                    line.new(x1=startBarTime, y1=new_trigger_line, x2=finishBarTime, y2=new_trigger_line, xloc=xloc.bar_time, width=1, color=label_color200, style=line.style_dotted)
                    label.new(x=finishBarTime, y=new_trigger_line, xloc=xloc.bar_time, text=str.tostring(new_trigger_line, decimals_to_show + grid_text1), style=label.style_label_center, color=color.rgb(255, 153, 0, 77), size=size.small, textcolor=#0c0c0c, textalign=text.align_right)
                    label.new(x=startBarTime, y=new_trigger_line, xloc=xloc.bar_time, text=str.tostring(i, "GRİD" + grid_text1), style=label.style_label_center, color=color.rgb(255, 153, 0, 77), size=size.small, textcolor=#0c0c0c, textalign=text.align_right)

        
        if entry_condition == "Mal ile Başla"
            label_color2000 = kisa_grid_cizgi
            line.new(x1=startBarTime, y1=referencePrice, x2=finishBarTime, y2=referencePrice, xloc=xloc.bar_time, width=1, color=label_color2000, style=line.style_dotted)
            label.new(x=finishBarTime, y=referencePrice, xloc=xloc.bar_time, text="MAL ALARAK BAŞLADIĞINDA SON SATIŞ YERİ==>" + str.tostring(referencePrice), style=label.style_label_center, color=#be0461, textcolor=#0c0c0c, size=size.small, textalign=text.align_right)
            label.new(x=startBarTime, y=referencePrice, xloc=xloc.bar_time, text="MAL ALARAK BAŞLADIĞINDA SON SATIŞ YERİ==>" + str.tostring(referencePrice), style=label.style_label_center, color=#be0461, textcolor=#0c0c0c, size=size.small, textalign=text.align_right)

        
        if enable_tp_sl 
            if mode == "Yatay"
                line.new(x1=startBarTime, y1=upperLimit, x2=finishBarTime, y2=upperLimit, xloc=xloc.bar_time, width=3, color=#dd0808fb, style=line.style_solid)
                line.new(x1=startBarTime, y1=lowerLimit, x2=finishBarTime, y2=lowerLimit, xloc=xloc.bar_time, width=3, color=#dd0808fb, style=line.style_solid)
                label.new(x=finishBarTime, y=upperLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI: " + str.tostring(upperLimit, "#.##") + " TL  (" + stop_mode + ")", style=label.style_label_left, color=#dd0808fb, textcolor=color.rgb(252, 252, 252), size=size.small)
                label.new(x=finishBarTime, y=lowerLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI: " + str.tostring(lowerLimit, "#.##") + " TL  (" + stop_mode + ")", style=label.style_label_left, color=#dd0808fb, textcolor=color.rgb(255, 255, 255), size=size.small)
            else if mode == "Uzun"
                line.new(x1=startBarTime, y1=upperLimit, x2=finishBarTime, y2=upperLimit, xloc=xloc.bar_time, width=1, color=color.teal, style=line.style_dashed)
                line.new(x1=startBarTime, y1=lowerLimit, x2=finishBarTime, y2=lowerLimit, xloc=xloc.bar_time, width=1, color=color.teal, style=line.style_dashed)
                label.new(x=finishBarTime, y=upperLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI  " + str.tostring(upperLimit, "#.##") + " TL", style=label.style_label_left, color=color.teal, textcolor=#0c0c0c, size=size.small)
                label.new(x=startBarTime, y=upperLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI  " + str.tostring(upperLimit, "#.##") + " TL", style=label.style_label_right, color=color.teal, textcolor=#0c0c0c, size=size.small)
                label.new(x=finishBarTime, y=lowerLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI  " + str.tostring(lowerLimit, "#.##") + " TL", style=label.style_label_left, color=#be0461, textcolor=#0c0c0c, size=size.small)
                label.new(x=startBarTime, y=lowerLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI  " + str.tostring(lowerLimit, "#.##") + " TL", style=label.style_label_right, color=#be0461, textcolor=#0c0c0c, size=size.small)
            else if mode == "Kısa"
                line.new(x1=startBarTime, y1=upperLimit, x2=finishBarTime, y2=upperLimit, xloc=xloc.bar_time, width=2, color=color.red, style=line.style_solid)
                line.new(x1=startBarTime, y1=lowerLimit, x2=finishBarTime, y2=lowerLimit, xloc=xloc.bar_time, width=2, color=color.lime, style=line.style_solid)
                label.new(x=finishBarTime, y=upperLimit, xloc=xloc.bar_time, text="ROBOT STOP FİYATI", style=label.style_label_left, color=color.red, textcolor=#0c0c0c, size=size.small)
                label.new(x=finishBarTime, y=lowerLimit, xloc=xloc.bar_time, text="KAR AL ROBOT STOP FİYATI", style=label.style_label_left, color=color.lime, textcolor=color.black, size=size.small)













hasOpenPosition(price, isLong) =>
    result = false
    for tradeId = 0 to strategy.opentrades - 1
        trade_price = strategy.opentrades.entry_price(tradeId)
        trade_size = strategy.opentrades.size(tradeId)
        if math.abs(trade_price - price) < 0.01  
            if (isLong and trade_size > 0) or (not isLong and trade_size < 0)
                result := true
                break
    result



calcGridIntervals(arr) =>
    if array.size(arr) < 2
        0.0
    else
        total_percentage = 0.0
        count = 0
        for i = 0 to array.size(arr) - 2
            current_level = array.get(arr, i)
            next_level = array.get(arr, i + 1)
            if not na(current_level) and not na(next_level) and current_level != 0
                percentage = math.abs((next_level - current_level) / current_level * 100)
                total_percentage += percentage
                count += 1
        count > 0 ? total_percentage / count : 0.0









tablo_baslik_rengi = input.color(title="Tablo Başlık Rengi", defval=color.rgb(54, 58, 69), group="Tablo Renk Ayarları")
tablo_yazi_rengi = input.color(title="Tablo Yazı Rengi", defval=color.rgb(12, 12, 12), group="Tablo Renk Ayarları")
tablo_arkaplan = input.color(title="Tablo Arkaplan", defval=#ffffff, group="Tablo Renk Ayarları")
tablo_arkaplan_yazi = input.color(title="Tablo Arkaplan Yazı Rengi", defval=color.rgb(255, 252, 252), group="Tablo Renk Ayarları")


var float dunkuKapanis = na
var int sonGun = na


tablo_boyutu = input.string(title="📊 Tablo Boyutu", defval="Normal", options=["Normal", "Small", "Tiny"], group = "///////////---TABLO AYARLARI---///////////")

atr = ta.atr(14)
natr = (atr / close) * 100

if showTable
    
   
    var currentSize = size.normal
    if tablo_boyutu == "Small"
        currentSize := size.small
    else if tablo_boyutu == "Tiny"
        currentSize := size.tiny
 
   
    var table infoTable = table.new(position.top_right, 20, 2, bgcolor=tablo_arkaplan)
 
    
    table.cell(infoTable, 0, 0, "Sembol"+"\n"+"Bilgisi", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 1, 0, "Açık"+"\n"+"İşlemler", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 2, 0, "Kapalı İşlemler"+ "\n"+ "Toplam İşlemler", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 3, 0, "Son Fiyat"+"\n"+"Kar-Zarar", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 4, 0, "Kar/Zarar"+ "\n"+" Hedefleri", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 5, 0, "Başlangıç"+"\n"+" Bitiş", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 6, 0, "Zamanda Kapama"+"\n"+"Şart Durumu", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 7, 0, "Durum", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 8, 0, "Grid Arası"+"\n"+"Mesafe", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)

    string symbolText = syminfo.ticker + "\n" + syminfo.description + "\n" + timeframe.period + "\n" +"Min. Fiyat Adımı: " + str.tostring(syminfo.minmove/100) + "\n" +"İşlem: " + mode + "\n" +"Atr TL : " + str.tostring(atr, "#.##") + "\n" +"NAtr % : " + str.tostring(natr, "#.##")
    table.cell(infoTable, 0, 1, symbolText, text_color=tablo_yazi_rengi, text_size=currentSize)
 
    
    string positionText = str.tostring(strategy.opentrades) + " İşlem"
    if strategy.opentrades > 0
        positionText += "\n"
        if strategy.position_size > 0
            positionText += "Long: " + str.tostring(strategy.position_size, "#.##") + "\n"
        else if strategy.position_size < 0
            positionText += "Short: " + str.tostring(math.abs(strategy.position_size), "#.##") + "\n"
     
        positionText += "Aktif:\n"
        float level = na
     
        for tradeId = 0 to strategy.opentrades - 1
            string comment = strategy.opentrades.entry_comment(tradeId)
            float entryPrice = strategy.opentrades.entry_price(tradeId)
         
            if str.startswith(comment, "Long")
                string gridNumberStr = str.substring(comment, 4)
                int gridNumber = int(str.tonumber(gridNumberStr))
                if gridNumber > 0 and gridNumber <= array.size(longLevelsArray)
                    int arrayIndex = gridNumber - 1
                    level := roundToMinMove(array.get(longLevelsArray, arrayIndex))
                    entryPrice := level
            else if str.startswith(comment, "Short")
                string gridNumberStr = str.substring(comment, 5)
                int gridNumber = int(str.tonumber(gridNumberStr))
                if gridNumber > 0 and gridNumber <= array.size(shortLevelsArray)
                    int arrayIndex = gridNumber - 1
                    level := roundToMinMove(array.get(shortLevelsArray, arrayIndex))
                    entryPrice := level
         
            positionText += comment + " -> " + str.tostring(entryPrice, "#.##") + " TL"
            if tradeId < strategy.opentrades - 1
                positionText += "\n"
 
    table.cell(infoTable, 1, 1, positionText, text_color=tablo_yazi_rengi, text_size=currentSize)

    
    string closedTradesText = str.tostring(strategy.closedtrades) + " İşlem"
    int totalTrades = strategy.opentrades + strategy.closedtrades
    string totalTradesText = str.tostring(totalTrades) + " İşlem"
    table.cell(infoTable, 2, 1, closedTradesText + "\n" + totalTradesText, text_color=tablo_yazi_rengi, text_size=currentSize)
  
   
    string pnlText = "Son Fiyat: " + str.tostring(close, "#.##") + " TL\n"
  
    float total_commission = getTotalCommission()

    pnlText += "Tamamlanan Islemler K/Z: ₺" + str.tostring(strategy.netprofit, "#.##") + "\n" + 
          "Acik Islemler K/Z: ₺" + str.tostring(strategy.openprofit, "#.##") + "\n" + 
          "Toplam Komisyon: ₺" + str.tostring(total_commission, "#.##") + "\n" + 
          "Toplam K/Z: ₺" + str.tostring(strategy.netprofit + strategy.openprofit - total_commission, "#.##")
  
    table.cell(infoTable, 3, 1, pnlText, text_color=tablo_yazi_rengi, text_size=currentSize)
 
    string karZararText = enable_profit_loss_close ? "✅ Aktif\nKar: ₺" + str.tostring(profit_target) + "\nZarar: ₺" + str.tostring(loss_limit) :"❌ Pasif"
    table.cell(infoTable, 4, 1, karZararText, text_color=tablo_yazi_rengi, text_size=currentSize)
 
    string dateText = "Başlangıç:\n" + start_date_formatted + "\n\nBitiş:\n" + finish_date_formatted
    table.cell(infoTable, 5, 1, dateText, text_color=tablo_yazi_rengi, text_size=currentSize)
 
    string zamanKapamaText = close_at_end_time ? "✅ Aktif" : "❌ Pasif"
    table.cell(infoTable, 6, 1, zamanKapamaText, text_color=tablo_yazi_rengi, text_size=currentSize)
 
    string durumText = ""
    if hedefe_ulasildi
        durumText := "Tekrar\nİşlem Açmaz\nHedefe Ulaştı\nTebrik Ederim\n\n🎯"
    else if not window() and close_at_end_time
        durumText := "Tekrar\nİşlem Açmaz\nHedef Saatine Ulaştı\nTebrik Ederim\n\n🎯"
    else
        durumText := "İşlem\nDevam\nEdiyor\n\n🪂"
    table.cell(infoTable, 7, 1, durumText, text_color=tablo_yazi_rengi, text_size=currentSize)

    // Grid intervals
    var float longGridInterval = 0.0
    var float shortGridInterval = 0.0
 
    if mode == "Uzun" or mode == "Yatay"
        longGridInterval := calcGridIntervals(longLevelsArray)
    if mode == "Kısa" or mode == "Yatay"
        shortGridInterval := calcGridIntervals(shortLevelsArray)
 
    string intervalText = ""
    if mode == "Uzun"
        intervalText := "Long Gridler:\n%" + str.tostring(longGridInterval, "#.##")
    else if mode == "Kısa"
        intervalText := "Short Gridler:\n%" + str.tostring(shortGridInterval, "#.##")
    else if mode == "Yatay"
        intervalText := "Long 🔺: %" + str.tostring(longGridInterval, "#.##") + "\n\nShort 🔻: %" + str.tostring(shortGridInterval, "#.##")
 
    table.cell(infoTable, 8, 1, intervalText, text_color=tablo_yazi_rengi, text_size=currentSize)

   

    table.cell(infoTable, 9, 0, "Lot Stratejisi", text_color=tablo_arkaplan_yazi, bgcolor=tablo_baslik_rengi, text_size=currentSize)
    table.cell(infoTable, 9, 1, lotStrategy, text_color=tablo_yazi_rengi, text_size=currentSize)
    




float totalPnL = strategy.netprofit  
float openPnL = strategy.openprofit  
float total_commission = getTotalCommission()
float overallPnL = totalPnL + openPnL - total_commission  



if enable_profit_loss_close and ((overallPnL <= loss_limit) or (overallPnL >= profit_target))
    if mode == "Uzun" 
        closeAllPositionsLong()
        pnl := 0.0
        islem_yapilabilir := false 
        hedefe_ulasildi := true
    else if mode == "Kısa"
        closeAllPositionsShort()
        pnl := 0.0
        islem_yapilabilir := false
        hedefe_ulasildi := true
    else if mode == "Yatay"
        closeAllPositionsYatay()
        pnl := 0.0
        islem_yapilabilir := false
        hedefe_ulasildi := true




    







var int last_report_time = 0
var report_interval = waitPeriods * timeframe.multiplier * 60  


var int start_time = time
var int bar_count = 0
var bool first_run = true


stop_durumu = enable_tp_sl ? "✅ Aktif" : "❌ Pasif"
kz_durumu = enable_profit_loss_close ? "✅ Aktif" : "❌ Pasif"
zaman_durumu = close_at_end_time ? "✅ Aktif" : "❌ Pasif"



calcRuntime() =>
    if window()
        float total_minutes = (time - start_time) / (1000 * 60)
        int hours = math.floor(total_minutes / 60)
        int mins = math.floor(total_minutes % 60)
        [hours, mins]
    [0, 0]


getOpenTradesInfo() =>
    string openTradesInfo = ""
    if strategy.opentrades > 0
        openTradesInfo := "\n📌 Açık İşlemler:\n"
        for tradeId = 0 to strategy.opentrades - 1
            comment = strategy.opentrades.entry_comment(tradeId)
            price = strategy.opentrades.entry_price(tradeId)
            openTradesInfo += "- " + comment + ": " + str.tostring(price, "#.##") + " TL\n"
    openTradesInfo

if barstate.isconfirmed and periodicReportEnabled 
    if first_run and window()
        start_time := time
        first_run := false
    if window()
        bar_count := bar_count + 1
    if (time - last_report_time >= report_interval * 1000)
        last_report_time := time
        [runtime_hours, runtime_mins] = calcRuntime()
        
        float kapanan_islemler = strategy.closedtrades
        float kapanan_tutar = strategy.netprofit
        float acik_islemler = strategy.opentrades
        float acik_tutar = strategy.openprofit
        float total_commission = getTotalCommission()
        float kar_zarar = strategy.netprofit + strategy.openprofit
        float max_kazanc = nz(strategy.max_runup, 0.0)
        float max_kayip = nz(strategy.max_drawdown, 0.0)
        float total100 = strategy.closedtrades == 0 ? strategy.openprofit - total_commission : strategy.netprofit + strategy.openprofit - total_commission

        if report_aktif_pasif
            string aktif_pasif_txt = '{\nSembol: ' + syminfo.ticker + '\nPeriyot: ' + timeframe.period + '\nStop Durumu: ' + stop_durumu + '\nKar/Zarar Durumu: ' + kz_durumu +  '\nZaman Kapatma: ' + zaman_durumu + '\nGrid Modu: ' + mode + '\nLot Stratejisi: ' + lotStrategy + '\n⏰ ' + str.tostring(waitPeriods) + ' periyod sonra tekrar rapor alacaksınız.}'
            alert(aktif_pasif_txt)

        if report_detayli
            string detayli_txt = '{\n🏢 ' + syminfo.ticker + '\n✔️ Kapanan İşlemler: ' + str.tostring(kapanan_islemler, "#") + ' adet / ' + (kapanan_islemler == 0 ? '0.00' : str.tostring(strategy.netprofit, "#.##")) + ' TL' + '\n⚡️ Açık İşlemler: ' + str.tostring(acik_islemler, "#") + ' adet / ' + str.tostring(acik_tutar, "#.##") + ' TL' + '\n💰 Toplam Komisyon: ' + str.tostring(total_commission, "#.##") + ' TL' + '\n💵 Toplam K/Z: ₺' + str.tostring(total100, "#.##") + ' TL' + '\n⏰ ' + str.tostring(waitPeriods) + ' periyod sonra tekrar rapor alacaksınız.}'
            alert(detayli_txt)

        if report_islem
            string islem_txt = '{\n🏢 ' + syminfo.ticker + '\n⚡️ Açık İşlemler: ' + str.tostring(acik_islemler, "#") + ' adet / ' + str.tostring(acik_tutar, "#.##") + ' TL' + getOpenTradesInfo() + '\n💵 Toplam K/Z: ₺' + str.tostring(total100, "#.##") + ' TL' + '\n⏰ ' + str.tostring(waitPeriods) + ' periyod sonra tekrar rapor alacaksınız.}'
            alert(islem_txt)




var currentYear = year(timenow)
var currentMonth = month(timenow)
var currentDay = dayofmonth(timenow)


var sifir_saat = input.int(title="🕐 Sıfırlama Saati", defval=17, minval=0, maxval=23, group="⏰ ZAMAN AYARLARI")
var sifir_dakika = input.int(title="🕐 Sıfırlama Dakikası", defval=58, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")
var sifir_saniye = input.int(title="🕐 Sıfırlama Saniyesi", defval=0, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")

var kayit_saat = input.int(title="🕐 Kayıt Saati", defval=17, minval=0, maxval=23, group="⏰ ZAMAN AYARLARI")
var kayit_dakika = input.int(title="🕐 Kayıt Dakikası", defval=59, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")
var kayit_saniye = input.int(title="🕐 Kayıt Saniyesi", defval=0, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")

var al_emir_saat = input.int(title="🕐 AL Emir Saati", defval=10, minval=0, maxval=23, group="⏰ ZAMAN AYARLARI")
var al_emir_dakika = input.int(title="🕐 AL Emir Dakikası", defval=3, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")
var al_emir_saniye = input.int(title="🕐 AL Emir Saniyesi", defval=0, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")

var sat_emir1_saat = input.int(title="🕐 1.SAT Emir Saati", defval=10, minval=0, maxval=23, group="⏰ ZAMAN AYARLARI")
var sat_emir1_dakika = input.int(title="🕐 1.SAT Emir Dakikası", defval=0, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")
var sat_emir1_saniye = input.int(title="🕐 1.SAT Emir Saniyesi", defval=0, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")

var sat_emir2_saat = input.int(title="🕐 2.SAT Emir Saati", defval=10, minval=0, maxval=23, group="⏰ ZAMAN AYARLARI")
var sat_emir2_dakika = input.int(title="🕐 2.SAT Emir Dakikası", defval=3, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")
var sat_emir2_saniye = input.int(title="🕐 2.SAT Emir Saniyesi", defval=0, minval=0, maxval=59, group="⏰ ZAMAN AYARLARI")

var sifir = timestamp(currentYear, currentMonth, currentDay, sifir_saat, sifir_dakika, sifir_saniye)           
var firstFinish101 = timestamp(currentYear, currentMonth, currentDay, kayit_saat, kayit_dakika, kayit_saniye)   
var secondFinish100 = timestamp(currentYear, currentMonth, currentDay, sat_emir1_saat, sat_emir1_dakika, sat_emir1_saniye)
var thirdFinish10 = timestamp(currentYear, currentMonth, currentDay, sat_emir2_saat, sat_emir2_dakika, sat_emir2_saniye) 
var qq = timestamp(currentYear, currentMonth, currentDay, al_emir_saat, al_emir_dakika, al_emir_saniye) 
    

isqq() =>   //al emirleri
    btcHour = hour(time)
    btcMinute = minute(time)
    targetHour = hour(qq)
    targetMinute = minute(qq)
    btcHour == targetHour and btcMinute == targetMinute


issifirTime() =>   //sıfırlama
    btcHour = hour(time)
    btcMinute = minute(time)
    targetHour = hour(sifir)
    targetMinute = minute(sifir)
    btcHour == targetHour and btcMinute == targetMinute


isSaveTime() =>  //kayıt
    btcHour = hour(time)
    btcMinute = minute(time)
    targetHour = hour(firstFinish101)
    targetMinute = minute(firstFinish101)
    btcHour == targetHour and btcMinute == targetMinute


isFirstSendTime() =>   //1.sat
    btcHour = hour(time)
    btcMinute = minute(time)
    targetHour = hour(secondFinish100)
    targetMinute = minute(secondFinish100)
    btcHour == targetHour and btcMinute == targetMinute


isSecondSendTime() =>  //2.sat
    btcHour = hour(time)
    btcMinute = minute(time)
    targetHour = hour(thirdFinish10)
    targetMinute = minute(thirdFinish10)
    btcHour == targetHour and btcMinute == targetMinute


findGridsBetween(float startPrice, float endPrice, array<float> gridLevels) =>
    int[] levels = array.new_int()
    
    if na(gridLevels) or array.size(gridLevels) == 0 or 
       na(gridHasActiveBuyOrder) or array.size(gridHasActiveBuyOrder) == 0 or
       na(gridHasPosition) or array.size(gridHasPosition) == 0
        levels  // Return empty array
    else
        if startPrice > endPrice  // Fiyat düşmüş
            for i = 0 to array.size(gridLevels) - 1
                float level = array.get(gridLevels, i)
                if not na(level) and 
                   arrayIndexValid(i, gridHasActiveBuyOrder) and 
                   arrayIndexValid(i, gridHasPosition) and
                   level < startPrice and 
                   level > endPrice and 
                   array.get(gridHasActiveBuyOrder, i) and 
                   not array.get(gridHasPosition, i)
                    array.push(levels, i)
        
        else if startPrice < endPrice  // Fiyat yükselmiş
            for i = 0 to array.size(gridLevels) - 2
                float level = array.get(gridLevels, i)
                if not na(level) and 
                   arrayIndexValid(i, gridHasActiveSellOrder) and 
                   arrayIndexValid(i + 1, gridHasPosition) and
                   level > startPrice and 
                   level < endPrice and 
                   array.get(gridHasActiveSellOrder, i) and 
                   array.get(gridHasPosition, i + 1)
                    array.push(levels, i)
                            
        levels







var float[] savedSellOrders = array.new_float(0)
var bool ordersSaved = false
var bool[] firstBatchSent = array.new_bool(10, false)  
var bool[] secondBatchSent = array.new_bool(10, false) 
var bool[] buyOrdersSent = array.new_bool(2, false)    

var bool canSendOrders = false  
var float[] savedOrders = array.new_float(0)  


if isSaveTime() and not ordersSaved and array.size(longLevelsArray) > 0 and alim_yontemi == "lmt"
    array.clear(savedSellOrders)
    
    // Aktif SAT emirlerini kaydet
    for i = 0 to array.size(longLevelsArray) - 1
        if array.get(gridHasActiveSellOrder, i)
            float sellLevel = array.get(longLevelsArray, i)
            if array.size(savedSellOrders) < 20  
                array.push(savedSellOrders, sellLevel)
    
    alert('{"name": "⚡️ Gün Sonu Bildirimi", "message": "Aktif SAT emirleri kaydedildi. Yarın sabah saat 10:00\'da otomatik olarak yeniden gönderilecektir. İyi akşamlar dilerim. 🌙"}')
    canSendOrders := true 
    ordersSaved := true
    
    // TÜM grid durumlarını tam olarak sıfırla (en önemli değişiklik burada)
    for i = 0 to array.size(gridHasActiveBuyOrder) - 1
        array.set(gridHasActiveBuyOrder, i, false)
        array.set(gridShowBuyOrder, i, false)
        
    for i = 0 to array.size(gridHasActiveSellOrder) - 1
        // SAT emirlerini false yap ama kaydettiğimiz bilgileri unutma
        array.set(gridHasActiveSellOrder, i, false)
        array.set(gridShowSellOrder, i, false)
        
    for i = 0 to array.size(gridHasPosition) - 1
        array.set(gridHasPosition, i, false)
            
if isFirstSendTime() and ordersSaved and alim_yontemi == "lmt" and canSendOrders
  
    if array.size(savedSellOrders) >= 1 and not array.get(firstBatchSent, 0)
        float sellLevel1 = array.get(savedSellOrders, 0)
        alert('{"name": "' + str.tostring(sellLevel1) + ' 🔴 1.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel1) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 0, true)

   
    if array.size(savedSellOrders) >= 2 and not array.get(firstBatchSent, 1)
        float sellLevel2 = array.get(savedSellOrders, 1)
        alert('{"name": "' + str.tostring(sellLevel2) + ' 🔴 2.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel2) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 1, true)

    
    if array.size(savedSellOrders) >= 3 and not array.get(firstBatchSent, 2)
        float sellLevel3 = array.get(savedSellOrders, 2)
        alert('{"name": "' + str.tostring(sellLevel3) + ' 🔴 3.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel3) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 2, true)

   
    if array.size(savedSellOrders) >= 4 and not array.get(firstBatchSent, 3)
        float sellLevel4 = array.get(savedSellOrders, 3)
        alert('{"name": "' + str.tostring(sellLevel4) + ' 🔴 4.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel4) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 3, true)

    
    if array.size(savedSellOrders) >= 5 and not array.get(firstBatchSent, 4)
        float sellLevel5 = array.get(savedSellOrders, 4)
        alert('{"name": "' + str.tostring(sellLevel5) + ' 🔴 5.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel5) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 4, true)

    
    if array.size(savedSellOrders) >= 6 and not array.get(firstBatchSent, 5)
        float sellLevel6 = array.get(savedSellOrders, 5)
        alert('{"name": "' + str.tostring(sellLevel6) + ' 🔴 6.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel6) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 5, true)

    
    if array.size(savedSellOrders) >= 7 and not array.get(firstBatchSent, 6)
        float sellLevel7 = array.get(savedSellOrders, 6)
        alert('{"name": "' + str.tostring(sellLevel7) + ' 🔴 7.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel7) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 6, true)

    
    if array.size(savedSellOrders) >= 8 and not array.get(firstBatchSent, 7)
        float sellLevel8 = array.get(savedSellOrders, 7)
        alert('{"name": "' + str.tostring(sellLevel8) + ' 🔴 8.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel8) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 7, true)

    
    if array.size(savedSellOrders) >= 9 and not array.get(firstBatchSent, 8)
        float sellLevel9 = array.get(savedSellOrders, 8)
        alert('{"name": "' + str.tostring(sellLevel9) + ' 🔴 9.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
              '", "orderSide": "sell", "orderType": "lmt", ' +
              '"price": "' + str.tostring(sellLevel9) + 
              '", "quantity": "' + str.tostring(fix_cl_per_level) +
              '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 8, true)

    if array.get(firstBatchSent, 8) 
        alert('{"name": "⚡️ Bilgilendirme", "message": "İlk grup SAT emirleri başarıyla gönderildi. İkinci grup emirler 3 dakika sonra gönderilecektir."}')



if isSecondSendTime() and ordersSaved and alim_yontemi == "lmt" and array.size(savedSellOrders) > 10 and canSendOrders

    
    if array.size(savedSellOrders) >= 10 and not array.get(firstBatchSent, 9)
        float sellLevel10 = array.get(savedSellOrders, 9)
        alert('{"name": "' + str.tostring(sellLevel10) + ' 🔴 10.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "lmt", ' +'"price": "' + str.tostring(sellLevel10) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(firstBatchSent, 9, true)

    

    
    if array.size(savedSellOrders) >= 11 and not array.get(secondBatchSent, 0)
        float sellLevel11 = array.get(savedSellOrders, 10)
        alert('{"name": "' + str.tostring(sellLevel11) + ' 🔴 11.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel11) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 0, true)

    
    if array.size(savedSellOrders) >= 12 and not array.get(secondBatchSent, 1)
        float sellLevel12 = array.get(savedSellOrders, 11)
        alert('{"name": "' + str.tostring(sellLevel12) + ' 🔴 12.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel12) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 1, true)

    
    if array.size(savedSellOrders) >= 13 and not array.get(secondBatchSent, 2)
        float sellLevel13 = array.get(savedSellOrders, 12)
        alert('{"name": "' + str.tostring(sellLevel13) + ' 🔴 13.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel13) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 2, true)

    
    if array.size(savedSellOrders) >= 14 and not array.get(secondBatchSent, 3)
        float sellLevel14 = array.get(savedSellOrders, 13)
        alert('{"name": "' + str.tostring(sellLevel14) + ' 🔴 14.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel14) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 3, true)

   
    if array.size(savedSellOrders) >= 15 and not array.get(secondBatchSent, 4)
        float sellLevel15 = array.get(savedSellOrders, 14)
        alert('{"name": "' + str.tostring(sellLevel15) + ' 🔴 15.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel15) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 4, true)

    
    if array.size(savedSellOrders) >= 16 and not array.get(secondBatchSent, 5)
        float sellLevel16 = array.get(savedSellOrders, 15)
        alert('{"name": "' + str.tostring(sellLevel16) + ' 🔴 16.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel16) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 5, true)

   
    if array.size(savedSellOrders) >= 17 and not array.get(secondBatchSent, 6)
        float sellLevel17 = array.get(savedSellOrders, 16)
        alert('{"name": "' + str.tostring(sellLevel17) + ' 🔴 17.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel17) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 6, true)

    
    if array.size(savedSellOrders) >= 18 and not array.get(secondBatchSent, 7)
        float sellLevel18 = array.get(savedSellOrders, 17)
        alert('{"name": "' + str.tostring(sellLevel18) + ' 🔴 18.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel18) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 7, true)

    
    if array.size(savedSellOrders) >= 19 and not array.get(secondBatchSent, 8)
        float sellLevel19 = array.get(savedSellOrders, 18)
        alert('{"name": "' + str.tostring(sellLevel19) + ' 🔴 19.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel19) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 8, true)

    
    if array.size(savedSellOrders) >= 20 and not array.get(secondBatchSent, 9)
        float sellLevel20 = array.get(savedSellOrders, 19)
        alert('{"name": "' + str.tostring(sellLevel20) + ' 🔴 20.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + 
             '", "orderSide": "sell", "orderType": "lmt", ' +
             '"price": "' + str.tostring(sellLevel20) + 
             '", "quantity": "' + str.tostring(fix_cl_per_level) +
             '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
        array.set(secondBatchSent, 9, true)

    if array.get(secondBatchSent, 9) 
        alert('{"name": "⚡️ Bilgilendirme", "message": "İkinci grup SAT emirleri başarıyla gönderildi. Tüm işlemler tamamlandı."}')


if isqq() and array.size(longLevelsArray) > 0 and alim_yontemi == "lmt" and canSendOrders
    int currentGridIndex = getCurrentGridIndex(close, longLevelsArray)
   
    if currentGridIndex != -1
        if isValidGridLevel(currentGridIndex + 1, array.size(longLevelsArray)) and not array.get(buyOrdersSent, 0)
            float buyLevel1 = array.get(longLevelsArray, currentGridIndex + 1)
            alert('{"name": "' + str.tostring(buyLevel1) + ' 🟢 1.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(buyLevel1) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
            array.set(buyOrdersSent, 0, true)
            array.set(gridHasActiveBuyOrder, currentGridIndex + 1, true)
            array.set(gridShowBuyOrder, currentGridIndex + 1, true)

        if isValidGridLevel(currentGridIndex + 2, array.size(longLevelsArray)) and not array.get(buyOrdersSent, 1)
            float buyLevel2 = array.get(longLevelsArray, currentGridIndex + 2)
            alert('{"name": "' + str.tostring(buyLevel2) + ' 🟢 2.Kayıt Edilen Emir", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(buyLevel2) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
            array.set(buyOrdersSent, 1, true)
            array.set(gridHasActiveBuyOrder, currentGridIndex + 2, true)
            array.set(gridShowBuyOrder, currentGridIndex + 2, true)
            
        if array.get(buyOrdersSent, 0) and array.get(buyOrdersSent, 1)
            ordersSaved := false  // Kayıt durumunu sıfırla
            canSendOrders := false  // Gün içi normal moda dön
    
            for i = 0 to array.size(buyOrdersSent) - 1
                array.set(buyOrdersSent, i, false)
            for i = 0 to array.size(firstBatchSent) - 1
                array.set(firstBatchSent, i, false)
            for i = 0 to array.size(secondBatchSent) - 1
                array.set(secondBatchSent, i, false)
        
            alert('{"name": "⚡️ AL Emirleri Tamamlandı", "message": "Tüm kaydedilen AL emirleri başarıyla gönderildi. Sistem normal çalışma moduna geçti."}')
            

// Fiyat düşüşüne göre AL emirleri için gridleri bulma
findBuyGridsBetween(float startPrice, float endPrice, array<float> gridLevels) =>
    int[] levels = array.new_int()
    for i = 0 to array.size(gridLevels) - 1
        float level = array.get(gridLevels, i)
        if level < startPrice and level >= endPrice and array.get(gridHasActiveBuyOrder, i) and not array.get(gridHasPosition, i)
            array.push(levels, i)
    levels

// Fiyat yükselişine göre SAT emirleri için gridleri bulma
findSellGridsBetween(float startPrice, float endPrice, array<float> gridLevels) =>
    int[] levels = array.new_int()
    for i = 0 to array.size(gridLevels) - 1
        float level = array.get(gridLevels, i)
        if level > startPrice and level <= endPrice and array.get(gridHasPosition, i) and i > 0
            array.push(levels, i)
    levels
// Ana işlem bloğu
if array.size(longLevelsArray) > 0 and (not ordersSaved or (ordersSaved and array.get(buyOrdersSent, 0) and array.get(buyOrdersSent, 1)))
    maxIndex = array.size(longLevelsArray) - 1
    
    // Ani fiyat hareketlerini ele almak için eklenen kod
    float previousClose = close[1]
    float currentLow = low
    float currentHigh = high
    var bool aniHareketOldu = false
    
    // Fiyat düşmüşse ve aktif AL emirleri varsa
    if currentLow < previousClose
        var int[] crossedLevels = findGridsBetween(previousClose, currentLow, longLevelsArray)
        
        if array.size(crossedLevels) > 0
            aniHareketOldu := true
            for j = 0 to array.size(crossedLevels) - 1
                int i = array.get(crossedLevels, j)
                if i <= maxIndex and arrayIndexValid(i, gridHasActiveBuyOrder) and 
                   arrayIndexValid(i, gridHasPosition) and 
                   arrayIndexValidFloat(i, longLevelsArray)
                   
                    tradeLevel = array.get(longLevelsArray, i)
                    var lastTradeTime = array.new_int(array.size(longLevelsArray), 0)
                    
                    // İlk kontrol: Gerçekten bu grid seviyesinde aktif bir AL emri var mı?
                    if array.get(gridHasActiveBuyOrder, i) and not array.get(gridHasPosition, i)
                        var currentTime = time
                        var timeElapsed = currentTime - array.get(lastTradeTime, i)
                        
                        // Pozisyon yoksa açalım
                        if not pozisyonVarMi(tradeLevel) and timeElapsed >= 1
                            array.set(lastTradeTime, i, currentTime)
                            
                            if not array.get(gridHasPosition, i)
                                array.set(gridHasPosition, i, true)
                                array.set(gridHasActiveBuyOrder, i, false)
                                array.set(gridShowBuyOrder, i, false)
                                
                                // Pozisyon açıldığında ilgili SAT/AL emirlerini oluşturalım
                                if array.get(gridHasPosition, i)
                                    float satgonder = na
                                    float gonder1 = na
                                    float gonder2 = na
                                    float gonder3 = na

                                    // Sat emri fiyatını hesaplama (bir üst grid)
                                    if i > 0 and i - 1 < array.size(longLevelsArray)
                                        satgonder := array.get(longLevelsArray, i - 1)

                                    // Alt gridler için al emri fiyatlarını hesaplama
                                    if i + 1 < array.size(longLevelsArray)
                                        gonder1 := array.get(longLevelsArray, i + 1)

                                    if i + 2 < array.size(longLevelsArray)
                                        gonder2 := array.get(longLevelsArray, i + 2)

                                    if i + 3 < array.size(longLevelsArray)
                                        gonder3 := array.get(longLevelsArray, i + 3)

                                    // Sat emirlerini gönderme
                                    if not na(satgonder) and i > 0 and isValidGridLevel(i - 1, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveSellOrder, i - 1) and not emirVarMi(satgonder)
                                            alert('{"name": "' + str.tostring(tradeLevel) + ' 🔵⚡ İşlemde >> ' + str.tostring(satgonder) + ' 🔴⏳ Emir", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "lmt", ' +'"price": "' + str.tostring(satgonder) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveSellOrder, i - 1, true)
                                            array.set(gridShowSellOrder, i - 1, true)
                                            array.set(gridHasActiveBuyOrder, i, false)
                                            array.set(gridShowBuyOrder, i, false)
                                            totalSellOrders := totalSellOrders + 1
                                            totalOpenTrades := totalOpenTrades + 1

                                    // Alt grid seviyelerine al emirleri gönderme
                                    if not na(gonder1) and isValidGridLevel(i + 1, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveBuyOrder, i + 1) and not emirVarMi(gonder1)
                                            alert('{"name": "' + str.tostring(gonder1) + '🔵🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder1) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveBuyOrder, i + 1, true)
                                            array.set(gridShowBuyOrder, i + 1, true)
                                            totalBuyOrders := totalBuyOrders + 1

                                    if not na(gonder2) and isValidGridLevel(i + 2, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveBuyOrder, i + 2) and not emirVarMi(gonder2)
                                            alert('{"name": "' + str.tostring(gonder2) + '🔵🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder2) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveBuyOrder, i + 2, true)
                                            array.set(gridShowBuyOrder, i + 2, true)
                                            totalBuyOrders := totalBuyOrders + 1

                                    if not na(gonder3) and isValidGridLevel(i + 3, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveBuyOrder, i + 3) and not emirVarMi(gonder3)
                                            alert('{"name": "' + str.tostring(gonder3) + '🔵🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder3) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveBuyOrder, i + 3, true)
                                            array.set(gridShowBuyOrder, i + 3, true)
                                            totalBuyOrders := totalBuyOrders + 1
    
    // İşlem kapatma kısmı için de benzer bir mantık eklenebilir
    if currentHigh > previousClose
        var int[] crossedSellLevels = findGridsBetween(previousClose, currentHigh, longLevelsArray)
        
        if array.size(crossedSellLevels) > 0
            aniHareketOldu := true
            for j = 0 to array.size(crossedSellLevels) - 1
                int i = array.get(crossedSellLevels, j)
                if i <= maxIndex and arrayIndexValid(i, gridHasPosition) and arrayIndexValidFloat(i, longLevelsArray)
                    
                    if array.get(gridHasPosition, i) and i > 0
                        exitLevel22 = array.get(longLevelsArray, i - 1)
                        exitLevel33 = array.get(longLevelsArray, i)
                        if high > exitLevel22 
                            totalClosedTrades := totalClosedTrades + 1

                            array.set(gridHasPosition, i, false)
                            array.set(gridHasActiveSellOrder, i - 1, false)
                            array.set(gridShowSellOrder,i - 1, false)
                            
                                                          
                            if not emirVarMi(array.get(longLevelsArray, i)) and high < exitLevel33
                                array.set(gridHasActiveBuyOrder, i, true)
                                array.set(gridShowBuyOrder, i, true)
                                totalBuyOrders := totalBuyOrders + 1
                                
                                alert('{"name": "' + str.tostring(exitLevel22) + '🟠⚡ İşlem Kapandı >> ' + str.tostring(array.get(longLevelsArray, i)) + ' 🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", "price": "' + str.tostring(array.get(longLevelsArray, i)) + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')
    
    // Eğer ani hareket tespit edilmediyse, normal işlem açma/kapama mantığı çalışır
    if not aniHareketOldu
        for i = 0 to maxIndex
            if arrayIndexValid(i, gridHasActiveBuyOrder) and 
               arrayIndexValid(i, gridHasPosition) and 
               arrayIndexValidFloat(i, longLevelsArray)

                tradeLevel = array.get(longLevelsArray, i)
                var lastTradeTime = array.new_int(array.size(longLevelsArray), 0)
                
                // İlk kontrol: Gerçekten bu grid seviyesinde aktif bir AL emri var mı?
                if array.get(gridHasActiveBuyOrder, i) and not array.get(gridHasPosition, i)
                    // İkinci kontrol: Fiyat bu grid seviyesinin altına düştü mü?
                    if low < tradeLevel 
                        
                        // Büyük düşüşleri kontrol etmek için grid farklarını hesaplama
                        var currentGridIndex = getCurrentGridIndex(low, longLevelsArray)
                        var previousGridIndex = getCurrentGridIndex(tradeLevel, longLevelsArray)
                        var gridDifference = previousGridIndex - currentGridIndex
                        
                        var currentTime = time
                        var timeElapsed = currentTime - array.get(lastTradeTime, i)
            
                        // Önemli: Burada pozisyonun olmadığı, zaman aralığının uygun olduğu VE
                        // grid seviyesinde AL emrinin aktif olduğunu kontrol ediyoruz
                        if not pozisyonVarMi(tradeLevel) and timeElapsed >= 1 and array.get(gridHasActiveBuyOrder, i)
                            array.set(lastTradeTime, i, currentTime)
                            
                            // Pozisyon yoksa açalım
                            if not array.get(gridHasPosition, i)
                                array.set(gridHasPosition, i, true)
                                array.set(gridHasActiveBuyOrder, i, false)
                                array.set(gridShowBuyOrder, i, false)
                                    
                                // Pozisyon açıldığında ilgili SAT/AL emirlerini oluşturalım
                                if array.get(gridHasPosition, i)
                                        
                                    float satgonder = na
                                    float gonder1 = na
                                    float gonder2 = na
                                    float gonder3 = na

                                    // Sat emri fiyatını hesaplama (bir üst grid)
                                    if i > 0 and i - 1 < array.size(longLevelsArray)
                                        satgonder := array.get(longLevelsArray, i - 1)

                                    // Alt gridler için al emri fiyatlarını hesaplama
                                    if i + 1 < array.size(longLevelsArray)
                                        gonder1 := array.get(longLevelsArray, i + 1)

                                    if i + 2 < array.size(longLevelsArray)
                                        gonder2 := array.get(longLevelsArray, i + 2)

                                    if i + 3 < array.size(longLevelsArray)
                                        gonder3 := array.get(longLevelsArray, i + 3)

                                    // Sat emirlerini gönderme
                                    if not na(satgonder) and i > 0 and isValidGridLevel(i - 1, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveSellOrder, i - 1) and not emirVarMi(satgonder)
                                            alert('{"name": "' + str.tostring(tradeLevel) + ' 🔵⚡ İşlemde >> ' + str.tostring(satgonder) + ' 🔴⏳ Emir", "symbol": "' + syminfo.ticker + '", "orderSide": "sell", "orderType": "lmt", ' +'"price": "' + str.tostring(satgonder) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveSellOrder, i - 1, true)
                                            array.set(gridShowSellOrder, i - 1, true)
                                            array.set(gridHasActiveBuyOrder, i, false)
                                            array.set(gridShowBuyOrder, i, false)
                                            totalSellOrders := totalSellOrders + 1
                                            totalOpenTrades := totalOpenTrades + 1

                                    // Alt grid seviyelerine al emirleri gönderme
                                    if not na(gonder1) and isValidGridLevel(i + 1, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveBuyOrder, i + 1) and not emirVarMi(gonder1)
                                            alert('{"name": "' + str.tostring(gonder1) + '🔵🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder1) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveBuyOrder, i + 1, true)
                                            array.set(gridShowBuyOrder, i + 1, true)
                                            totalBuyOrders := totalBuyOrders + 1

                                    if not na(gonder2) and isValidGridLevel(i + 2, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveBuyOrder, i + 2) and not emirVarMi(gonder2)
                                            alert('{"name": "' + str.tostring(gonder2) + '🔵🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder2) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveBuyOrder, i + 2, true)
                                            array.set(gridShowBuyOrder, i + 2, true)
                                            totalBuyOrders := totalBuyOrders + 1

                                    if not na(gonder3) and isValidGridLevel(i + 3, array.size(longLevelsArray))
                                        if not array.get(gridHasActiveBuyOrder, i + 3) and not emirVarMi(gonder3)
                                            alert('{"name": "' + str.tostring(gonder3) + '🔵🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", ' +'"price": "' + str.tostring(gonder3) + '", "quantity": "' + str.tostring(fix_cl_per_level) +'", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}') 
                                            array.set(gridHasActiveBuyOrder, i + 3, true)
                                            array.set(gridShowBuyOrder, i + 3, true)
                                            totalBuyOrders := totalBuyOrders + 1

                // İşlem kapama kısmı için normal mantık
                if array.get(gridHasPosition, i) and i > 0
                    exitLevel22 = array.get(longLevelsArray, i - 1)
                    exitLevel33 = array.get(longLevelsArray, i)
                    if high > exitLevel22 
                        totalClosedTrades := totalClosedTrades + 1

                        array.set(gridHasPosition, i, false)
                        array.set(gridHasActiveSellOrder, i - 1, false)
                        array.set(gridShowSellOrder,i - 1, false)
                        
                                                      
                        if not emirVarMi(array.get(longLevelsArray, i)) and high < exitLevel33
                            array.set(gridHasActiveBuyOrder, i, true)
                            array.set(gridShowBuyOrder, i, true)
                            totalBuyOrders := totalBuyOrders + 1
                            
                            alert('{"name": "' + str.tostring(exitLevel22) + '🟠⚡ İşlem Kapandı >> ' + str.tostring(array.get(longLevelsArray, i)) + ' 🟢", "symbol": "' + syminfo.ticker + '", "orderSide": "buy", "orderType": "lmt", "price": "' + str.tostring(array.get(longLevelsArray, i)) + '", "quantity": "' + str.tostring(fix_cl_per_level) + '", "timeInForce": "day", "apiKey": "' + apikey + '","token":"' + token + '"}')




getTotalActiveBuyOrders() =>
    int count = 0
    if array.size(gridHasActiveBuyOrder) > 0
        for i = 0 to array.size(gridHasActiveBuyOrder) - 1
            if array.get(gridHasActiveBuyOrder, i)
                count += 1
    count

getTotalActiveSellOrders() =>
    int count = 0
    if array.size(gridHasActiveSellOrder) > 0
        for i = 0 to array.size(gridHasActiveSellOrder) - 1
            if array.get(gridHasActiveSellOrder, i)
                count += 1
    count

getTotalActivePositions() =>
    int count = 0
    if array.size(gridHasPosition) > 0
        for i = 0 to array.size(gridHasPosition) - 1
            if array.get(gridHasPosition, i)
                count += 1
    count

var showTradeTable = input.bool(false, "📊 İşlem Tablosunu Göster", group="Tablo Ayarları")

// Tablo renk ayarları
var color TABLE_BG_COLOR = color.new(color.rgb(28, 28, 28), 0)
var color HEADER_BG_COLOR = color.rgb(38, 46, 56)
var color TEXT_COLOR = color.white
var color POSITIVE_COLOR = color.rgb(0, 255, 0)
var color NEGATIVE_COLOR = color.rgb(255, 0, 0)


var label[] buyLabels = array.new_label()
var label[] sellLabels = array.new_label()


color orderTime1Color = color.red         
color orderTime2Color = color.orange       
color orderTime3Color = color.yellow       
color orderTime4Color = color.lime         


plotBuyOrders() =>
    if window() and showTradeTable and array.size(gridHasActiveBuyOrder) > 0
        for i = 0 to array.size(gridHasActiveBuyOrder) - 1
            if array.get(gridHasActiveBuyOrder, i) and array.size(longLevelsArray) > i
                float level = array.get(longLevelsArray, i)
                lbl = label.new(bar_index, level, "AL", color=color.green, style=label.style_label_up, size=size.tiny)
                array.push(buyLabels, lbl)  

plotSellOrders() =>
    if window() and showTradeTable and array.size(gridHasActiveSellOrder) > 0
        for i = 0 to array.size(gridHasActiveSellOrder) - 1
            if array.get(gridHasActiveSellOrder, i) and array.size(longLevelsArray) > i
                float level = array.get(longLevelsArray, i)
                color labelColor = color.red 

               
                if i >= 0 and i <= 3  
                    labelColor := orderTime1Color
                else if i >= 4 and i <= 9  
                    labelColor := orderTime2Color
                else if i >= 10 and i <= 14  
                    labelColor := orderTime3Color
                else if i >= 15 and i <= 19  
                    labelColor := orderTime4Color

                lbl = label.new(bar_index, level, "SAT", color=labelColor, style=label.style_label_down, size=size.tiny)
                array.push(sellLabels, lbl)  

if isqq() 
    if array.size(buyLabels) > 0
        for i = 0 to array.size(buyLabels) - 1
            label.delete(array.get(buyLabels, i))
        array.clear(buyLabels)  
    if array.size(sellLabels) > 0
        for i = 0 to array.size(sellLabels) - 1
            label.delete(array.get(sellLabels, i))
        array.clear(sellLabels)  
var label[] positionLabels = array.new_label()

plotActivePositions() =>
    if window() and showTradeTable and array.size(gridHasPosition) > 0
        for i = 0 to array.size(gridHasPosition) - 1
            if array.get(gridHasPosition, i) and array.size(longLevelsArray) > i
                float level = array.get(longLevelsArray, i)
                label.new(bar_index, level, "POZ", color=color.blue, style=label.style_label_right, size=size.tiny)
plotBuyOrders()
plotSellOrders()
plotActivePositions()

if barstate.islast and tabloGoster1
    // Color Palette
    color darkBgColor = color.new(color.rgb(18, 18, 18), 0)
    color headerBgColor = color.rgb(30, 40, 50)
    color subHeaderBgColor = color.rgb(40, 50, 60)
    color textColor = color.white
    color primaryHighlightColor = color.rgb(65, 105, 225)
    color positiveColor = color.rgb(0, 200, 100)
    color negativeColor = color.rgb(220, 50, 50)
    color neutralColor = color.rgb(180, 180, 180)
    
    // Create Table
    var table masterTable = table.new(position.top_right, 5, 30, bgcolor=darkBgColor, border_width=1)
    
    // Header
    table.cell(masterTable, 0, 0, "🔍 LMT Stratejisi Detay Raporu", bgcolor=headerBgColor, text_color=textColor, text_size=size.small)
    table.cell(masterTable, 1, 0, "", bgcolor=headerBgColor)
    table.cell(masterTable, 2, 0, "", bgcolor=headerBgColor)
    table.cell(masterTable, 3, 0, "", bgcolor=headerBgColor)
    table.cell(masterTable, 4, 0, "", bgcolor=headerBgColor)
    
    // Trading Parameters Section
    table.cell(masterTable, 0, 1, "📊 Strateji Parametreleri", bgcolor=subHeaderBgColor, text_color=textColor, text_size=size.small)
    table.cell(masterTable, 1, 1, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 2, 1, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 3, 1, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 4, 1, "", bgcolor=subHeaderBgColor)
    
    table.cell(masterTable, 0, 2, "İşlem Modu", text_color=textColor)
    table.cell(masterTable, 1, 2, mode, text_color=primaryHighlightColor)
    
    table.cell(masterTable, 0, 3, "Lot Stratejisi", text_color=textColor)
    table.cell(masterTable, 1, 3, lotStrategy, text_color=primaryHighlightColor)
    
    table.cell(masterTable, 2, 2, "Grid Hesaplama", text_color=textColor)
    table.cell(masterTable, 3, 2, grid_calculation, text_color=primaryHighlightColor)
    
    table.cell(masterTable, 2, 3, "Referans Fiyat", text_color=textColor)
    table.cell(masterTable, 3, 3, str.tostring(referencePrice, "#.##") + " TL", text_color=neutralColor,tooltip="Stratejinin hesaplandığı referans fiyat")
    
    // Grid Information Section
    table.cell(masterTable, 0, 4, "🏁 Grid Bilgileri", bgcolor=subHeaderBgColor, text_color=textColor, text_size=size.small)
    table.cell(masterTable, 1, 4, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 2, 4, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 3, 4, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 4, 4, "", bgcolor=subHeaderBgColor)
    
    table.cell(masterTable, 0, 5, "Toplam Grid Sayısı", text_color=textColor)
    table.cell(masterTable, 1, 5, str.tostring(gridLevels), text_color=primaryHighlightColor)
    
    table.cell(masterTable, 2, 5, "Grid Aralığı (%)", text_color=textColor)
    float longGridInterval = calcGridIntervals(longLevelsArray)
    table.cell(masterTable, 3, 5, str.tostring(longGridInterval, "#.##"), text_color=longGridInterval > 0 ? positiveColor : negativeColor)
    
    table.cell(masterTable, 0, 6, "10:00 Açılış Fiyatı", text_color=textColor)
    table.cell(masterTable, 1, 6, str.tostring(openingPrice, "#.##") + " TL", text_color=neutralColor,tooltip="Alt Limit: " + str.tostring(openingPrice * 0.90, "#.##") + " TL\nÜst Limit: " + str.tostring(openingPrice * 1.10, "#.##") + " TL")
    
    table.cell(masterTable, 2, 6, "Grid Aralığı (±%10)", text_color=textColor)
    table.cell(masterTable, 3, 6, str.tostring(gridsInPriceRange), text_color=primaryHighlightColor, tooltip=priceRangeGridStatus)
    
    table.cell(masterTable, 0, 7, "En Yüksek Grid", text_color=textColor)
    table.cell(masterTable, 1, 7, na(highestGridInRange) ? "-" : str.tostring(highestGridInRange, "#.##") + " TL", text_color=positiveColor)
    
    table.cell(masterTable, 2, 7, "En Düşük Grid", text_color=textColor)
    table.cell(masterTable, 3, 7, na(lowestGridInRange) ? "-" : str.tostring(lowestGridInRange, "#.##") + " TL", text_color=negativeColor)
    
    // Order Information Section
    table.cell(masterTable, 0, 8, "📈 Emir Bilgileri", bgcolor=subHeaderBgColor, text_color=textColor, text_size=size.small)
    table.cell(masterTable, 1, 8, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 2, 8, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 3, 8, "", bgcolor=subHeaderBgColor)
    table.cell(masterTable, 4, 8, "", bgcolor=subHeaderBgColor)
    
    table.cell(masterTable, 0, 9, "Toplam SAT Emirleri", text_color=textColor)
    table.cell(masterTable, 1, 9, str.tostring(totalSellOrderCount), text_color=primaryHighlightColor, tooltip=totalSellOrderStatus)
    
    table.cell(masterTable, 2, 9, "Aktif İşlemler", text_color=textColor)
    int remainingUpperGridOrders = userUpperGridCount + userUpperGridCount10 - totalClosedTrades
    remainingUpperGridOrders := math.max(remainingUpperGridOrders, 0)
    int totalActivePositions = remainingUpperGridOrders + getTotalActivePositions()
    table.cell(masterTable, 3, 9, str.tostring(totalActivePositions), text_color=totalActivePositions > 0 ? positiveColor : negativeColor)

    table.cell(masterTable, 0, 10, "Kapanan İşlemler", text_color=textColor)
    table.cell(masterTable, 1, 10, str.tostring(totalClosedTrades), text_color=primaryHighlightColor)
Editor is loading...
Leave a Comment