Bot Ayarları


(Config.php)



// Binance API anahtarları
define('API_KEY', 'API'); // Gerçek API anahtarınızla değiştirin
define('API_SECRET', 'SCRET'); // Gerçek API secret anahtarınızla değiştirin

// Trading ayarları
define('INVESTMENT_AMOUNT', 10); // USD İşlem miktarı 
define('LEVERAGE', 10); // kaldıraç x10
define('STOP_LOSS_PERCENT', 1); // %1 zarar oranı
define('TAKE_PROFIT_PERCENT', 3); // %3 kar oranı

// Teknik indikatör ayarları
define('EMA_FAST', 5); //değiştirmeyin
define('EMA_SLOW', 20); //değiştirmeyin
define('MACD_FAST', 12);//değiştirmeyin 
define('MACD_SLOW', 26);//değiştirmeyin 
define('ADX_PERIOD', 14);//değiştirmeyin 
define('TIMEFRAME', '5m');//değiştirmeyin 

// Trading Configuration
define('REFRESH_INTERVAL', 10); // seconds değiştirmeyin

// Technical Indicators Configuration
define('VWAP_PERIOD', 20); //değiştirmeyin 
define('MACD_SIGNAL', 9); //değiştirmeyin 
define('ADX_THRESHOLD', 22); //değiştirmeyin
Formül;

Price > VWAP && EMA5 > EMA20 && MACD > 0 && ADX > 22

Price < VWAP && EMA5 < EMA20 && MACD < 0 && ADX > 22

Nasıl çalışır?
Config Dosyasında apikey ve scretkey bilgilerinizi girin
işlem büyüklüğünü ve kaldıraç oranını bütçenize göre düzenleyin ve kaydedin
diğer ayarları değiştirmeyin çok makul bir stratejiniz ve zaman aralığınız yoksa.

tüm dosyaları local yada linux sunucunuza yükleyin
işlem çiftini girin başlat butonunu tıklayın.

Ne iş yapar bu bot;

verdiğiniz işlem çiftinin 5 dakikalık verilerini wws yani websocked ile binance futures apiden anlık olarak alır.
config dosyasına göre değerlendirir
formülasyon %100 eşleşirse otomatik pozisyon açar.
aynı pozisyon açıksa yeni pozisyon açmaz.


sorumluluk reddi;

bu kendini geliştirmek isteyen webmasterler için eiğitici bir yazılımdır, yatırım tavsiyesi yada kazanç garantili bir yazılım değildir.
kullanıcılar futures işlemlerin titizlikle değerlendirilmesi gerektiğini aksi halde büyük zararlar açılabileceğini bilmelidir.
öneri olarak test aşamasında her zaman küçük miktar ve küçük kaldıraç kullanılmalıdır.
Tüm sorumluluk script/ yazılımı kullanan kişiye aittir.

index.php //değiştirmeyin
<?php
require_once 'config.php';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Binance Futures Bot</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { max-width: 800px; margin: 0 auto; }
        .form-group { margin-bottom: 15px; }
        input[type="text"] { width: 100%; padding: 8px; }
        button { padding: 10px 15px; background: #007bff; color: white; border: none; cursor: pointer; }
        .error { color: red; margin-bottom: 10px; }
        .success { color: green; margin-bottom: 10px; }
        .info { color: blue; margin-bottom: 10px; }
        .warning { color: orange; margin-bottom: 10px; }
        #status { margin-top: 20px; padding: 10px; border: 1px solid #ddd; }
        #indicators { margin-top: 20px; }
        .indicator { margin-bottom: 5px; padding: 5px; border: 1px solid #ddd; border-radius: 4px; }
        .test-button {
            margin-right: 10px;
            background: #28a745;
        }
        .condition-true {
            background-color: #d4edda;
        }
        .condition-false {
            background-color: #f8d7da;
        }
        #log {
            height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-top: 20px;
            background-color: #f8f9fa;
            font-family: monospace;
        }
        .connection-status {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .connection-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .connected {
            background-color: #28a745;
        }
        .connecting {
            background-color: #ffc107;
        }
        .disconnected {
            background-color: #dc3545;
        }
        .stats-container {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            font-size: 12px;
            color: #666;
        }
        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .stat-value {
            font-weight: bold;
            font-size: 14px;
        }
        .config-info {
            margin-top: 20px;
            padding: 10px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .config-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        .config-label {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Binance Futures Bot</h2>
        <div id="messages"></div>
        <form id="tradingForm">
            <div class="form-group">
                <label for="symbol">İşlem Çifti (örn: BNBUSDT):</label>
                <input type="text" id="symbol" name="symbol" required>
            </div>
            <button type="submit">Başlat</button>
        </form>
        
        <div class="connection-status">
            <span id="connectionIndicator" class="connection-indicator disconnected"></span>
            <span id="connectionText">Bağlantı Yok</span>
        </div>
        
        <div id="status">
            <div class="info">Durum: <span id="currentStatus">Beklemede</span></div>
            <div class="info">Son Güncelleme: <span id="lastUpdate">-</span></div>
        </div>
        
        <div class="stats-container">
            <div class="stat-item">
                <span>Alınan Mesajlar</span>
                <span id="statsMessages" class="stat-value">0</span>
            </div>
            <div class="stat-item">
                <span>Yeniden Bağlanmalar</span>
                <span id="statsReconnects" class="stat-value">0</span>
            </div>
            <div class="stat-item">
                <span>Çalışma Süresi</span>
                <span id="statsUptime" class="stat-value">00:00:00</span>
            </div>
            <div class="stat-item">
                <span>Ping (ms)</span>
                <span id="statsPing" class="stat-value">-</span>
            </div>
        </div>
        
        <div class="config-info">
            <h3>Bot Ayarları</h3>
            <div class="config-item">
                <span class="config-label">Yatırım Miktarı:</span>
                <span><?php echo INVESTMENT_AMOUNT; ?> USD</span>
            </div>
            <div class="config-item">
                <span class="config-label">Kaldıraç:</span>
                <span><?php echo LEVERAGE; ?>x</span>
            </div>
            <div class="config-item">
                <span class="config-label">Stop Loss:</span>
                <span>%<?php echo STOP_LOSS_PERCENT; ?></span>
            </div>
            <div class="config-item">
                <span class="config-label">Take Profit:</span>
                <span>%<?php echo TAKE_PROFIT_PERCENT; ?></span>
            </div>
            <div class="config-item">
                <span class="config-label">Zaman Dilimi:</span>
                <span><?php echo TIMEFRAME; ?></span>
            </div>
            <div class="config-item">
                <span class="config-label">ADX Eşiği:</span>
                <span><?php echo ADX_THRESHOLD; ?></span>
            </div>
        </div>
        
        <div id="indicators">
            <div class="indicator">Fiyat: <span id="price">-</span></div>
            <div class="indicator">VWAP: <span id="vwap">-</span></div>
            <div class="indicator">EMA<?php echo EMA_FAST; ?>: <span id="ema_fast">-</span></div>
            <div class="indicator">EMA<?php echo EMA_SLOW; ?>: <span id="ema_slow">-</span></div>
            <div class="indicator">MACD: <span id="macd">-</span></div>
            <div class="indicator">ADX: <span id="adx">-</span></div>
            <div class="indicator">Fiyat > VWAP: <span id="price_vwap">-</span></div>
            <div class="indicator">EMA<?php echo EMA_FAST; ?> > EMA<?php echo EMA_SLOW; ?>: <span id="ema_compare">-</span></div>
            <div class="indicator">MACD > 0: <span id="macd_positive">-</span></div>
            <div class="indicator">ADX > <?php echo ADX_THRESHOLD; ?>: <span id="adx_threshold">-</span></div>
        </div>
        <div style="margin-top: 20px;">
            <button id="testLong" class="test-button">Test LONG</button>
            <button id="testShort" class="test-button">Test SHORT</button>
        </div>
        <div id="log">
            <div>Log mesajları burada görünecek...</div>
        </div>
    </div>

    <script>
        // ==================== CONFIG DEĞERLERİ ====================
        // PHP'den JavaScript'e config değerlerini aktar
        const CONFIG = {
            INVESTMENT_AMOUNT: <?php echo INVESTMENT_AMOUNT; ?>,
            LEVERAGE: <?php echo LEVERAGE; ?>,
            STOP_LOSS_PERCENT: <?php echo STOP_LOSS_PERCENT; ?>,
            TAKE_PROFIT_PERCENT: <?php echo TAKE_PROFIT_PERCENT; ?>,
            EMA_FAST: <?php echo EMA_FAST; ?>,
            EMA_SLOW: <?php echo EMA_SLOW; ?>,
            MACD_FAST: <?php echo MACD_FAST; ?>,
            MACD_SLOW: <?php echo MACD_SLOW; ?>,
            MACD_SIGNAL: <?php echo MACD_SIGNAL; ?>,
            ADX_PERIOD: <?php echo ADX_PERIOD; ?>,
            ADX_THRESHOLD: <?php echo ADX_THRESHOLD; ?>,
            VWAP_PERIOD: <?php echo VWAP_PERIOD; ?>,
            TIMEFRAME: "<?php echo TIMEFRAME; ?>",
            REFRESH_INTERVAL: <?php echo REFRESH_INTERVAL; ?>
        };
        
        // ==================== GLOBAL DEĞİŞKENLER ====================
        // WebSocket bağlantı yönetimi için değişkenler
        let ws = null;
        let wsReconnectInterval = null;
        let pingInterval = null;
        let lastPingTime = 0;
        let reconnectAttempts = 0;
        let isReconnecting = false;
        let lastConnectionAttempt = 0;
        
        const MAX_RECONNECT_ATTEMPTS = 5;
        const RECONNECT_DELAY = 5000; // 5 saniye
        const MIN_RECONNECT_INTERVAL = 10000; // En az 10 saniye aralıkla yeniden bağlanma
        const MAX_LOG_ENTRIES = 100; // Maksimum log girişi sayısı
        
        // Veri değişkenleri
        let klines = [];
        let indicators = {
            vwap: 0,
            ema_fast: 0,
            ema_slow: 0,
            macd: 0,
            adx: 0,
            current_price: 0
        };
        let isOrderPending = false;
        
        // Bağlantı istatistikleri
        let connectionStats = {
            messagesReceived: 0,
            reconnects: 0,
            lastMessageTime: 0,
            uptime: 0,
            connectionStartTime: 0,
            lastPingLatency: 0
        };

        // ==================== YARDIMCI FONKSİYONLAR ====================
        // Log fonksiyonu
        function log(message, type = 'info') {
            const logElement = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const logItem = document.createElement('div');
            logItem.className = type;
            logItem.textContent = `[${timestamp}] ${message}`;
            
            // Log sayısını sınırla
            while (logElement.children.length >= MAX_LOG_ENTRIES) {
                logElement.removeChild(logElement.firstChild);
            }
            
            logElement.appendChild(logItem);
            logElement.scrollTop = logElement.scrollHeight;
            
            // Sadece önemli mesajları konsola yazdır
            if (type === 'error' || type === 'warning' || type === 'success') {
                console.log(`[${type}] ${message}`);
            }
        }
        
        // Bağlantı durumunu güncelle
        function updateConnectionStatus(status) {
            const indicator = document.getElementById('connectionIndicator');
            const text = document.getElementById('connectionText');
            
            indicator.className = 'connection-indicator ' + status;
            
            switch(status) {
                case 'connected':
                    text.textContent = 'Bağlı';
                    break;
                case 'connecting':
                    text.textContent = 'Bağlanıyor...';
                    break;
                case 'disconnected':
                    text.textContent = 'Bağlantı Yok';
                    break;
            }
        }
        
        // Zaman formatı
        function formatTime(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            
            return [
                hours.toString().padStart(2, '0'),
                minutes.toString().padStart(2, '0'),
                secs.toString().padStart(2, '0')
            ].join(':');
        }
        
        // İstatistikleri güncelle
        function updateStats() {
            document.getElementById('statsMessages').textContent = connectionStats.messagesReceived;
            document.getElementById('statsReconnects').textContent = connectionStats.reconnects;
            document.getElementById('statsUptime').textContent = formatTime(connectionStats.uptime);
            document.getElementById('statsPing').textContent = connectionStats.lastPingLatency || '-';
        }

        // Fiyat hassasiyetini belirle
        function getPricePrecision(price) {
            if (price < 0.0001) return 8;
            if (price < 0.001) return 7;
            if (price < 0.01) return 6;
            if (price < 0.1) return 5;
            if (price < 1) return 4;
            if (price < 10) return 3;
            if (price < 100) return 2;
            if (price < 1000) return 1;
            return 0;
        }

        // ==================== VERİ İŞLEME FONKSİYONLARI ====================
        // İlk verileri yükle
        function loadInitialData(symbol) {
            log(`${symbol} için ilk verileri yükleniyor...`);
            
            // Config'den zaman dilimini al
            const timeframe = CONFIG.TIMEFRAME;
            
            fetch(`https://fapi.binance.com/fapi/v1/klines?symbol=${symbol}&interval=${timeframe}&limit=100`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP hata! Durum: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    klines = data;
                    log(`İlk veriler yüklendi: ${klines.length} kline`, 'success');
                    updateIndicators();
                })
                .catch(error => {
                    log(`İlk veri yükleme hatası: ${error.message}`, 'error');
                    document.getElementById('currentStatus').textContent = 'Veri yükleme hatası!';
                });
        }
        
        // VWAP hesapla
        function calculateVWAP(klines) {
            // Config'den VWAP periyodunu al
            const period = CONFIG.VWAP_PERIOD;
            
            // Son 'period' kadar kline'ı al
            const recentKlines = klines.slice(-period);
            
            let sumPriceVolume = 0;
            let sumVolume = 0;
            
            recentKlines.forEach(kline => {
                const price = (parseFloat(kline[2]) + parseFloat(kline[3]) + parseFloat(kline[4])) / 3;
                const volume = parseFloat(kline[5]);
                sumPriceVolume += price * volume;
                sumVolume += volume;
            });
            
            return sumPriceVolume / sumVolume;
        }

        // EMA hesapla
        function calculateEMA(klines, period) {
            const prices = klines.map(k => parseFloat(k[4]));
            const multiplier = 2 / (period + 1);
            let ema = prices[0];
            
            for (let i = 1; i < prices.length; i++) {
                ema = (prices[i] - ema) * multiplier + ema;
            }
            
            return ema;
        }

        // MACD hesapla
        function calculateMACD(klines) {
            // Config'den MACD değerlerini al
            const fastPeriod = CONFIG.MACD_FAST;
            const slowPeriod = CONFIG.MACD_SLOW;
            const signalPeriod = CONFIG.MACD_SIGNAL;
            
            const emaFast = calculateEMA(klines, fastPeriod);
            const emaSlow = calculateEMA(klines, slowPeriod);
            
            // MACD Line = EMA(FAST) - EMA(SLOW)
            const macdLine = emaFast - emaSlow;
            
            // Basitleştirilmiş hesaplama - gerçek MACD Signal Line için daha karmaşık hesaplama gerekir
            // Burada sadece MACD Line değerini döndürüyoruz
            return macdLine;
        }

        // ADX hesapla
        function calculateADX(klines) {
            // Config'den ADX periyodunu al
            const period = CONFIG.ADX_PERIOD;
            
            const highs = klines.map(k => parseFloat(k[2]));
            const lows = klines.map(k => parseFloat(k[3]));
            const closes = klines.map(k => parseFloat(k[4]));
            
            let tr = [];
            for (let i = 1; i < klines.length; i++) {
                tr.push(Math.max(
                    highs[i] - lows[i],
                    Math.abs(highs[i] - closes[i-1]),
                    Math.abs(lows[i] - closes[i-1])
                ));
            }
            
            // Son 'period' kadar TR değerini al ve ortalamasını hesapla
            return tr.slice(-period).reduce((a, b) => a + b, 0) / period;
        }

        // İndikatörleri güncelle
        function updateIndicators() {
            if (klines.length === 0) {
                log('Kline verisi yok, indikatörler hesaplanamıyor', 'error');
                return;
            }
            
            indicators.vwap = calculateVWAP(klines);
            indicators.ema_fast = calculateEMA(klines, CONFIG.EMA_FAST);
            indicators.ema_slow = calculateEMA(klines, CONFIG.EMA_SLOW);
            indicators.macd = calculateMACD(klines);
            indicators.adx = calculateADX(klines);
            indicators.current_price = parseFloat(klines[klines.length - 1][4]);

            // Hassasiyet bilgilerini al
            const pricePrecision = getPricePrecision(indicators.current_price);

            // UI güncelle
            document.getElementById('price').textContent = indicators.current_price.toFixed(pricePrecision);
            document.getElementById('vwap').textContent = indicators.vwap.toFixed(pricePrecision);
            document.getElementById('ema_fast').textContent = indicators.ema_fast.toFixed(pricePrecision);
            document.getElementById('ema_slow').textContent = indicators.ema_slow.toFixed(pricePrecision);
            document.getElementById('macd').textContent = indicators.macd.toFixed(pricePrecision);
            document.getElementById('adx').textContent = indicators.adx.toFixed(2);
            document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString();

            // Koşul göstergelerini güncelle
            const priceVwap = indicators.current_price > indicators.vwap;
            const emaCompare = indicators.ema_fast > indicators.ema_slow;
            const macdPositive = indicators.macd > 0;
            const adxThreshold = indicators.adx > CONFIG.ADX_THRESHOLD;

            document.getElementById('price_vwap').textContent = priceVwap ? 'Evet' : 'Hayır';
            document.getElementById('ema_compare').textContent = emaCompare ? 'Evet' : 'Hayır';
            document.getElementById('macd_positive').textContent = macdPositive ? 'Evet' : 'Hayır';
            document.getElementById('adx_threshold').textContent = adxThreshold ? 'Evet' : 'Hayır';

            // Koşul renklerini güncelle
            document.getElementById('price_vwap').parentElement.className = 
                'indicator ' + (priceVwap ? 'condition-true' : 'condition-false');
            document.getElementById('ema_compare').parentElement.className = 
                'indicator ' + (emaCompare ? 'condition-true' : 'condition-false');
            document.getElementById('macd_positive').parentElement.className = 
                'indicator ' + (macdPositive ? 'condition-true' : 'condition-false');
            document.getElementById('adx_threshold').parentElement.className = 
                'indicator ' + (adxThreshold ? 'condition-true' : 'condition-false');

            // Koşulları kontrol et
            checkConditions();
        }

        // ==================== WEBSOCKET YÖNETİMİ ====================
        // WebSocket bağlantısını kur
        function connectWebSocket(symbol) {
            // Önceki yeniden bağlanma zamanlayıcısını temizle
            if (wsReconnectInterval) {
                clearTimeout(wsReconnectInterval);
                wsReconnectInterval = null;
            }
            
            // Önceki ping zamanlayıcısını temizle
            if (pingInterval) {
                clearInterval(pingInterval);
                pingInterval = null;
            }
            
            // Önceki WebSocket bağlantısını kapat
            if (ws) {
                ws.close();
                ws = null;
            }
            
            reconnectAttempts = 0;
            updateConnectionStatus('connecting');
            
            try {
                log(`${symbol} için WebSocket bağlantısı kuruluyor...`);
                
                // Config'den zaman dilimini al
                const timeframe = CONFIG.TIMEFRAME;
                
                // Birleşik akış kullanımı
                ws = new WebSocket('wss://fstream.binance.com/stream');
                
                ws.onopen = function() {
                    reconnectAttempts = 0; // Başarılı bağlantıda sıfırla
                    isReconnecting = false;
                    log('WebSocket bağlantısı açıldı', 'success');
                    updateConnectionStatus('connected');
                    document.getElementById('currentStatus').textContent = 'Bağlantı kuruldu';
                    
                    // Bağlantı istatistiklerini başlat
                    connectionStats.connectionStartTime = Date.now();
                    
                    // Abone olma isteği gönder
                    const subscribeMsg = {
                        method: "SUBSCRIBE",
                        params: [`${symbol.toLowerCase()}@kline_${timeframe}`],
                        id: 1
                    };
                    
                    ws.send(JSON.stringify(subscribeMsg));
                    log(`${symbol} kline verilerine abone olundu (${timeframe})`, 'info');
                    
                    // Ping/Pong mekanizmasını başlat
                    startPingPong();
                };
                
                ws.onmessage = function(event) {
                    try {
                        connectionStats.messagesReceived++;
                        connectionStats.lastMessageTime = Date.now();
                        
                        const response = JSON.parse(event.data);
                        
                        // Abonelik yanıtını kontrol et
                        if (response.id === 1) {
                            if (response.result === null) {
                                log('Abonelik başarılı', 'success');
                            } else {
                                log('Abonelik hatası: ' + JSON.stringify(response), 'error');
                            }
                            return;
                        }
                        
                        // Pong yanıtını kontrol et
                        if (response.result !== undefined && response.id) {
                            connectionStats.lastPingLatency = Date.now() - lastPingTime;
                            // Ping/Pong mesajlarını loglamayı azalt
                            if (connectionStats.messagesReceived % 10 === 0) {
                                log(`Pong alındı. Gecikme: ${connectionStats.lastPingLatency}ms`, 'info');
                            }
                            return;
                        }
                        
                        // Normal veri akışı
                        if (response.data && response.data.k) {
                            const kline = response.data.k;
                            
                            // Mum kapandıysa (isFinal=true) veya yeni bir mum ise
                            if (kline.x || klines.length === 0) {
                                // Yeni kline verisi
                                if (klines.length >= 100) {
                                    klines.shift();
                                }
                                
                                const newKline = [
                                    kline.t, // Açılış zamanı
                                    kline.o, // Açılış fiyatı
                                    kline.h, // En yüksek fiyat
                                    kline.l, // En düşük fiyat
                                    kline.c, // Kapanış fiyatı
                                    kline.v  // Hacim
                                ];
                                
                                klines.push(newKline);
                                updateIndicators();
                                log(`Yeni mum: ${new Date(kline.t).toLocaleTimeString()} - Kapanış: ${kline.c}`, 'info');
                            } else {
                                // Mevcut mumun güncellenmesi - her güncellemeyi loglamayı azalt
                                const lastIndex = klines.length - 1;
                                if (lastIndex >= 0) {
                                    klines[lastIndex][2] = Math.max(parseFloat(klines[lastIndex][2]), parseFloat(kline.h)); // Yüksek
                                    klines[lastIndex][3] = Math.min(parseFloat(klines[lastIndex][3]), parseFloat(kline.l)); // Düşük
                                    klines[lastIndex][4] = kline.c; // Kapanış
                                    klines[lastIndex][5] = kline.v; // Hacim
                                    
                                    // Sadece belirli aralıklarla güncelleme logla
                                    if (connectionStats.messagesReceived % 20 === 0) {
                                        updateIndicators();
                                    } else {
                                        // Sadece fiyatı güncelle, tüm indikatörleri hesaplama
                                        indicators.current_price = parseFloat(kline.c);
                                        document.getElementById('price').textContent = indicators.current_price.toFixed(getPricePrecision(indicators.current_price));
                                    }
                                }
                            }
                        }
                    } catch (error) {
                        log('Veri işleme hatası: ' + error.message, 'error');
                    }
                };
                
                ws.onerror = function(error) {
                    log('WebSocket hatası: ' + (error.message || JSON.stringify(error)), 'error');
                    updateConnectionStatus('disconnected');
                    document.getElementById('currentStatus').textContent = 'Bağlantı hatası!';
                    
                    // Hata durumunda yeniden bağlanma işlemini başlat
                    scheduleReconnect(symbol);
                };
                
                ws.onclose = function(event) {
                    // Kod 1000 (normal kapanma) veya 1001 (sayfa kapatıldı) ise normal kapanma
                    const isNormalClosure = event.code === 1000 || event.code === 1001;
                    
                    if (!isNormalClosure) {
                        log(`WebSocket bağlantısı beklenmedik şekilde kapandı. Kod: ${event.code}`, 'warning');
                    } else {
                        log(`WebSocket bağlantısı normal şekilde kapandı. Kod: ${event.code}`, 'info');
                    }
                    
                    updateConnectionStatus('disconnected');
                    document.getElementById('currentStatus').textContent = 'Bağlantı kapandı!';
                    
                    // Ping zamanlayıcısını temizle
                    if (pingInterval) {
                        clearInterval(pingInterval);
                        pingInterval = null;
                    }
                    
                    // Normal kapanma değilse yeniden bağlan
                    if (!isNormalClosure) {
                        scheduleReconnect(symbol);
                    }
                };
            } catch (error) {
                log('WebSocket oluşturma hatası: ' + error.message, 'error');
                updateConnectionStatus('disconnected');
                document.getElementById('currentStatus').textContent = 'Bağlantı hatası!';
                
                // Hata durumunda yeniden bağlanma işlemini başlat
                scheduleReconnect(symbol);
            }
        }
        
        // Ping/Pong mekanizması (birleşik akış için)
        function startPingPong() {
            pingInterval = setInterval(() => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    lastPingTime = Date.now();
                    ws.send(JSON.stringify({ 
                        method: "ping",
                        id: Date.now()
                    }));
                    
                    // Ping mesajlarını loglamayı azalt
                    if (connectionStats.messagesReceived % 10 === 0) {
                        log('Ping gönderildi', 'info');
                    }
                }
            }, 30000); // 30 saniye
        }
        
        // Yeniden bağlanma işlemini zamanla
        function scheduleReconnect(symbol) {
            // Çok sık yeniden bağlanma denemelerini engelle
            const now = Date.now();
            if (now - lastConnectionAttempt < MIN_RECONNECT_INTERVAL) {
                log(`Çok sık yeniden bağlanma denemesi, bekleniyor...`, 'warning');
                return;
            }
            
            lastConnectionAttempt = now;
            
            if (isReconnecting) {
                log('Zaten yeniden bağlanma işlemi devam ediyor', 'info');
                return;
            }
            
            if (wsReconnectInterval) {
                clearTimeout(wsReconnectInterval);
                wsReconnectInterval = null;
            }
            
            reconnectAttempts++;
            connectionStats.reconnects++;
            isReconnecting = true;
            
            if (reconnectAttempts <= MAX_RECONNECT_ATTEMPTS) {
                const delay = RECONNECT_DELAY * Math.pow(1.5, reconnectAttempts - 1); // Üstel geri çekilme
                log(`Yeniden bağlanma denemesi ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS}, ${delay/1000} saniye sonra...`, 'info');
                
                wsReconnectInterval = setTimeout(() => {
                    log(`Yeniden bağlanılıyor... Deneme: ${reconnectAttempts}`, 'info');
                    isReconnecting = false;
                    connectWebSocket(symbol);
                }, delay);
            } else {
                log(`Maksimum yeniden bağlanma denemesi (${MAX_RECONNECT_ATTEMPTS}) aşıldı. Lütfen sayfayı yenileyin.`, 'error');
                document.getElementById('currentStatus').textContent = 'Bağlantı başarısız!';
                isReconnecting = false;
            }
        }

        // ==================== EMİR İŞLEMLERİ ====================
        // Emir gönderme fonksiyonu
        function sendOrder(symbol, direction, price, quantity, stopLoss, takeProfit) {
            isOrderPending = true;
            document.getElementById('currentStatus').textContent = `${direction} Emri Gönderiliyor...`;
            
            const params = new URLSearchParams({
                symbol: symbol,
                direction: direction,
                price: price,
                quantity: quantity,
                stop_loss: stopLoss,
                take_profit: takeProfit
            });

            // Fetch API ile istek göndermeden önce kontrol
            log(`Gönderilecek parametreler: ${JSON.stringify(Object.fromEntries(params))}`);
            
            return fetch('mainnet.php?' + params.toString(), {
                method: 'GET',
                headers: {
                    'Cache-Control': 'no-cache'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP hata! Durum: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // Config değerlerini kontrol et ve logla
                if (data.config_values) {
                    log(`Config değerleri: Yatırım: ${data.config_values.investment_amount}$, Kaldıraç: ${data.config_values.leverage}x, SL: %${data.config_values.stop_loss_percent}, TP: %${data.config_values.take_profit_percent}`, 'info');
                }
                return data;
            });
        }

        // İşlem koşullarını kontrol et
        function checkConditions() {
            if (isOrderPending) {
                log('Emir bekleniyor, yeni emir gönderilmiyor');
                return;
            }

            const symbol = document.getElementById('symbol').value;
            if (!symbol) {
                return;
            }
            
            // Hassasiyet bilgilerini al
            const pricePrecision = getPricePrecision(indicators.current_price);
            const quantityPrecision = 2; // Varsayılan miktar hassasiyeti
            
            // Config'den ADX eşiğini al
            const adxThreshold = CONFIG.ADX_THRESHOLD;
            
            // Long koşulları
            if (indicators.current_price > indicators.vwap &&
                indicators.ema_fast > indicators.ema_slow &&
                indicators.macd > 0 &&
                indicators.adx > adxThreshold) {
                
                log('LONG koşulları sağlandı, emir gönderiliyor...');
                
                const price = indicators.current_price;
                
                // Config'den yatırım miktarını al
                const investmentAmount = CONFIG.INVESTMENT_AMOUNT;
                
                // Miktar = Yatırım Miktarı / Fiyat (kaldıraç hesaba katılmaz)
                const quantity = (investmentAmount / price).toFixed(quantityPrecision);
                
                log(`Hesaplanan miktar: ${quantity} (${investmentAmount}$ / ${price})`);
                
                // Stop Loss ve Take Profit değerleri mainnet.php tarafında hesaplanacak
                // Burada sadece tahmini değerler gönderiyoruz
                const stopLoss = (price * (1 - CONFIG.STOP_LOSS_PERCENT / 100)).toFixed(pricePrecision);
                const takeProfit = (price * (1 + CONFIG.TAKE_PROFIT_PERCENT / 100)).toFixed(pricePrecision);
                
                sendOrder(symbol, 'LONG', price.toFixed(pricePrecision), quantity, stopLoss, takeProfit)
                    .then(data => {
                        log('LONG emir detayları: ' + JSON.stringify(data), 'success');
                        if (data.error) {
                            document.getElementById('currentStatus').textContent = 'Hata: ' + data.error;
                            log('Emir hatası: ' + data.error, 'error');
                        } else {
                            document.getElementById('currentStatus').textContent = 'LONG Pozisyon Açıldı';
                            log('LONG pozisyon başarıyla açıldı', 'success');
                        }
                        isOrderPending = false;
                    })
                    .catch(error => {
                        console.error('Hata:', error);
                        document.getElementById('currentStatus').textContent = 'Hata: ' + error.message;
                        log('Emir gönderme hatası: ' + error.message, 'error');
                        isOrderPending = false;
                    });
            }
            // Short koşulları
            else if (indicators.current_price < indicators.vwap &&
                     indicators.ema_fast < indicators.ema_slow &&
                     indicators.macd < 0 &&
                     indicators.adx > adxThreshold) {
                
                log('SHORT koşulları sağlandı, emir gönderiliyor...');
                
                const price = indicators.current_price;
                
                // Config'den yatırım miktarını al
                const investmentAmount = CONFIG.INVESTMENT_AMOUNT;
                
                // Miktar = Yatırım Miktarı / Fiyat (kaldıraç hesaba katılmaz)
                const quantity = (investmentAmount / price).toFixed(quantityPrecision);
                
                log(`Hesaplanan miktar: ${quantity} (${investmentAmount}$ / ${price})`);
                
                // Stop Loss ve Take Profit değerleri mainnet.php tarafında hesaplanacak
                // Burada sadece tahmini değerler gönderiyoruz
                const stopLoss = (price * (1 + CONFIG.STOP_LOSS_PERCENT / 100)).toFixed(pricePrecision);
                const takeProfit = (price * (1 - CONFIG.TAKE_PROFIT_PERCENT / 100)).toFixed(pricePrecision);
                
                sendOrder(symbol, 'SHORT', price.toFixed(pricePrecision), quantity, stopLoss, takeProfit)
                    .then(data => {
                        log('SHORT emir detayları: ' + JSON.stringify(data), 'success');
                        if (data.error) {
                            document.getElementById('currentStatus').textContent = 'Hata: ' + data.error;
                            log('Emir hatası: ' + data.error, 'error');
                        } else {
                            document.getElementById('currentStatus').textContent = 'SHORT Pozisyon Açıldı';
                            log('SHORT pozisyon başarıyla açıldı', 'success');
                        }
                        isOrderPending = false;
                    })
                    .catch(error => {
                        console.error('Hata:', error);
                        document.getElementById('currentStatus').textContent = 'Hata: ' + error.message;
                        log('Emir gönderme hatası: ' + error.message, 'error');
                        isOrderPending = false;
                    });
            } else {
                document.getElementById('currentStatus').textContent = 'Koşullar Uygun Değil';
            }
        }

        // ==================== OLAY DİNLEYİCİLERİ ====================
        // Form gönderimi
        document.getElementById('tradingForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const symbol = document.getElementById('symbol').value.toUpperCase();
            
            if (!symbol) {
                alert('Lütfen bir sembol girin');
                return;
            }

            // Mevcut WebSocket bağlantısını kapat
            if (ws) {
                ws.close();
                klines = []; // Verileri temizle
            }

            document.getElementById('currentStatus').textContent = 'Bağlanıyor...';
            document.getElementById('messages').innerHTML = `<div class="info">Sembol: ${symbol} için bağlantı kuruluyor...</div>`;
            log(`${symbol} için işlem başlatılıyor...`);
            
            // Önce ilk verileri yükle
            loadInitialData(symbol);
            
            // Sonra WebSocket bağlantısı kur
            setTimeout(() => {
                connectWebSocket(symbol);
            }, 1000); // İlk verilerin yüklenmesi için kısa bir gecikme
        });

        // Test LONG butonu
        document.getElementById('testLong').addEventListener('click', function() {
            if (isOrderPending) {
                log('Emir bekleniyor, yeni emir gönderilmiyor', 'warning');
                return;
            }

            const symbol = document.getElementById('symbol').value.toUpperCase();
            if (!symbol) {
                alert('Lütfen bir sembol girin');
                return;
            }
            
            if (klines.length === 0) {
                alert('Veri yükleniyor, lütfen bekleyin');
                return;
            }
            
            log('Test LONG emri hazırlanıyor...');
            
            const pricePrecision = getPricePrecision(indicators.current_price);
            const quantityPrecision = 2;
            
            const price = indicators.current_price;
            
            // Config'den yatırım miktarını al
            const investmentAmount = CONFIG.INVESTMENT_AMOUNT;
            
            // Miktar = Yatırım Miktarı / Fiyat
            const quantity = (investmentAmount / price).toFixed(quantityPrecision);
            
            log(`Hesaplanan miktar: ${quantity} (${investmentAmount}$ / ${price})`);
            
            // Stop Loss ve Take Profit değerleri mainnet.php tarafında hesaplanacak
            // Burada sadece tahmini değerler gönderiyoruz
            const stopLoss = (price * (1 - CONFIG.STOP_LOSS_PERCENT / 100)).toFixed(pricePrecision);
            const takeProfit = (price * (1 + CONFIG.TAKE_PROFIT_PERCENT / 100)).toFixed(pricePrecision);
            
            sendOrder(symbol, 'LONG', price.toFixed(pricePrecision), quantity, stopLoss, takeProfit)
                .then(data => {
                    log('Test LONG emir detayları: ' + JSON.stringify(data), 'success');
                    if (data.error) {
                        document.getElementById('currentStatus').textContent = 'Hata: ' + data.error;
                        log('Emir hatası: ' + data.error, 'error');
                    } else {
                        document.getElementById('currentStatus').textContent = 'Test LONG Pozisyon Açıldı';
                        log('Test LONG pozisyon başarıyla açıldı', 'success');
                    }
                    isOrderPending = false;
                })
                .catch(error => {
                    console.error('Hata:', error);
                    document.getElementById('currentStatus').textContent = 'Hata: ' + error.message;
                    log('Emir gönderme hatası: ' + error.message, 'error');
                    isOrderPending = false;
                });
        });

        // Test SHORT butonu
        document.getElementById('testShort').addEventListener('click', function() {
            if (isOrderPending) {
                log('Emir bekleniyor, yeni emir gönderilmiyor', 'warning');
                return;
            }

            const symbol = document.getElementById('symbol').value.toUpperCase();
            if (!symbol) {
                alert('Lütfen bir sembol girin');
                return;
            }
            
            if (klines.length === 0) {
                alert('Veri yükleniyor, lütfen bekleyin');
                return;
            }
            
            log('Test SHORT emri hazırlanıyor...');
            
            const pricePrecision = getPricePrecision(indicators.current_price);
            const quantityPrecision = 2;
            
            const price = indicators.current_price;
            
            // Config'den yatırım miktarını al
            const investmentAmount = CONFIG.INVESTMENT_AMOUNT;
            
            // Miktar = Yatırım Miktarı / Fiyat
            const quantity = (investmentAmount / price).toFixed(quantityPrecision);
            
            log(`Hesaplanan miktar: ${quantity} (${investmentAmount}$ / ${price})`);
            
            // Stop Loss ve Take Profit değerleri mainnet.php tarafında hesaplanacak
            // Burada sadece tahmini değerler gönderiyoruz
            const stopLoss = (price * (1 + CONFIG.STOP_LOSS_PERCENT / 100)).toFixed(pricePrecision);
            const takeProfit = (price * (1 - CONFIG.TAKE_PROFIT_PERCENT / 100)).toFixed(pricePrecision);
            
            sendOrder(symbol, 'SHORT', price.toFixed(pricePrecision), quantity, stopLoss, takeProfit)
                .then(data => {
                    log('Test SHORT emir detayları: ' + JSON.stringify(data), 'success');
                    if (data.error) {
                        document.getElementById('currentStatus').textContent = 'Hata: ' + data.error;
                        log('Emir hatası: ' + data.error, 'error');
                    } else {
                        document.getElementById('currentStatus').textContent = 'Test SHORT Pozisyon Açıldı';
                        log('Test SHORT pozisyon başarıyla açıldı', 'success');
                    }
                    isOrderPending = false;
                })
                .catch(error => {
                    console.error('Hata:', error);
                    document.getElementById('currentStatus').textContent = 'Hata: ' + error.message;
                    log('Emir gönderme hatası: ' + error.message, 'error');
                    isOrderPending = false;
                });
        });
        
        // İstatistikleri periyodik olarak güncelle
        setInterval(() => {
            if (connectionStats.connectionStartTime > 0) {
                connectionStats.uptime = Math.floor((Date.now() - connectionStats.connectionStartTime) / 1000);
                updateStats();
            }
        }, 1000);
        
        // Config değerlerini başlangıçta logla
        log(`Bot ayarları yüklendi: Yatırım: ${CONFIG.INVESTMENT_AMOUNT}$, Kaldıraç: ${CONFIG.LEVERAGE}x, SL: %${CONFIG.STOP_LOSS_PERCENT}, TP: %${CONFIG.TAKE_PROFIT_PERCENT}`, 'info');
        log(`Teknik indikatör ayarları: EMA Hızlı: ${CONFIG.EMA_FAST}, EMA Yavaş: ${CONFIG.EMA_SLOW}, ADX Eşiği: ${CONFIG.ADX_THRESHOLD}`, 'info');
    </script>
</body>
</html>

mainnet.php //değiştirmeyin

<?php
require_once 'config.php';

// Gelen parametreleri al
$symbol = $_GET['symbol'] ?? '';
$direction = $_GET['direction'] ?? '';
$price = $_GET['price'] ?? 0;
$quantity = $_GET['quantity'] ?? 0;
$stop_loss = $_GET['stop_loss'] ?? 0;
$take_profit = $_GET['take_profit'] ?? 0;

// Parametreleri doğrula
if (empty($symbol) || empty($direction) || $price <= 0 || $quantity <= 0) {
    die(json_encode(['error' => 'Geçersiz parametreler']));
}

// Config'den değerleri al
$max_investment = INVESTMENT_AMOUNT; // Config'den al
$leverage = LEVERAGE; // Config'den kaldıraç değerini al
$stop_loss_percent = STOP_LOSS_PERCENT; // Config'den stop loss yüzdesini al
$take_profit_percent = TAKE_PROFIT_PERCENT; // Config'den take profit yüzdesini al

// Maksimum işlem miktarı kontrolü
$max_quantity = $max_investment / $price;

if ($quantity > $max_quantity * 1.1) { // %10 tolerans
    die(json_encode([
        'error' => 'İşlem miktarı çok yüksek',
        'details' => [
            'requested_quantity' => $quantity,
            'max_allowed' => $max_quantity,
            'price' => $price,
            'config_investment' => $max_investment,
            'config_leverage' => $leverage
        ]
    ]));
}

// API anahtarlarını kontrol et
if (API_KEY === 'YOUR_API_KEY' || API_SECRET === 'YOUR_API_SECRET') {
    die(json_encode(['error' => 'API anahtarları ayarlanmamış. Lütfen config.php dosyasını düzenleyin.']));
}

// Binance Futures API endpoint
$base_url = 'https://fapi.binance.com';

// Sembol bilgilerini al ve hassasiyetleri belirle
try {
    $exchange_info = getExchangeInfo($base_url);
    $symbol_info = findSymbolInfo($exchange_info, $symbol);
    
    if (!$symbol_info) {
        die(json_encode(['error' => 'Sembol bulunamadı: ' . $symbol]));
    }
    
    $precisions = getPrecisions($symbol_info);
    $price_precision = $precisions['price_precision'];
    $quantity_precision = $precisions['quantity_precision'];
    
    // Değerleri hassasiyete göre formatla
    $formatted_price = number_format($price, $price_precision, '.', '');
    $formatted_quantity = number_format($quantity, $quantity_precision, '.', '');
    $formatted_stop_loss = number_format($stop_loss, $price_precision, '.', '');
    $formatted_take_profit = number_format($take_profit, $price_precision, '.', '');
    
} catch (Exception $e) {
    die(json_encode(['error' => 'Sembol bilgileri alınamadı: ' . $e->getMessage()]));
}

// Mevcut piyasa fiyatını al
try {
    $current_price = getCurrentPrice($base_url, $symbol);
} catch (Exception $e) {
    die(json_encode(['error' => 'Mevcut fiyat alınamadı: ' . $e->getMessage()]));
}

// Take Profit ve Stop Loss fiyatlarını config değerlerine göre hesapla
if ($direction === 'LONG') {
    // LONG için Stop Loss, mevcut fiyattan STOP_LOSS_PERCENT kadar düşük
    $calculated_stop_loss = $current_price * (1 - $stop_loss_percent / 100);
    $formatted_stop_loss = number_format($calculated_stop_loss, $price_precision, '.', '');
    
    // LONG için Take Profit, mevcut fiyattan TAKE_PROFIT_PERCENT kadar yüksek
    $calculated_take_profit = $current_price * (1 + $take_profit_percent / 100);
    $formatted_take_profit = number_format($calculated_take_profit, $price_precision, '.', '');
} else { // SHORT
    // SHORT için Stop Loss, mevcut fiyattan STOP_LOSS_PERCENT kadar yüksek
    $calculated_stop_loss = $current_price * (1 + $stop_loss_percent / 100);
    $formatted_stop_loss = number_format($calculated_stop_loss, $price_precision, '.', '');
    
    // SHORT için Take Profit, mevcut fiyattan TAKE_PROFIT_PERCENT kadar düşük
    $calculated_take_profit = $current_price * (1 - $take_profit_percent / 100);
    $formatted_take_profit = number_format($calculated_take_profit, $price_precision, '.', '');
}

// Kaldıraç ayarla
try {
    setLeverage($base_url, $symbol, $leverage);
} catch (Exception $e) {
    // Kaldıraç ayarlama hatası kritik değil, devam et ama hata bilgisini kaydet
    $leverage_error = $e->getMessage();
}

// Mevcut pozisyonları kontrol et
try {
    $positions = getPositions($base_url, $symbol);
    
    foreach ($positions as $position) {
        if ($position['symbol'] === $symbol && floatval($position['positionAmt']) !== 0.0) {
            die(json_encode([
                'error' => 'Zaten açık pozisyon var',
                'position' => $position
            ]));
        }
    }
} catch (Exception $e) {
    die(json_encode(['error' => 'Pozisyon bilgileri alınamadı: ' . $e->getMessage()]));
}

// Ana emri gönder
try {
    $order_result = placeMainOrder($base_url, $symbol, $direction, $formatted_price, $formatted_quantity);
} catch (Exception $e) {
    die(json_encode(['error' => 'Ana emir gönderilemedi: ' . $e->getMessage()]));
}

// Stop Loss emri gönder
try {
    $sl_response = placeStopLossOrder($base_url, $symbol, $direction, $formatted_quantity, $formatted_stop_loss);
} catch (Exception $e) {
    // Stop Loss hatası kritik değil, devam et ama hata bilgisini kaydet
    $sl_error = $e->getMessage();
    $sl_response = ['error' => $sl_error];
}

// Take Profit emri gönder
try {
    $tp_response = placeTakeProfitOrder($base_url, $symbol, $direction, $formatted_quantity, $formatted_take_profit);
} catch (Exception $e) {
    // Take Profit hatası kritik değil, devam et ama hata bilgisini kaydet
    $tp_error = $e->getMessage();
    $tp_response = ['error' => $tp_error];
}

// Sonuçları döndür
echo json_encode([
    'main_order' => $order_result,
    'stop_loss' => $sl_response,
    'take_profit' => $tp_response,
    'config_values' => [
        'investment_amount' => INVESTMENT_AMOUNT,
        'leverage' => LEVERAGE,
        'stop_loss_percent' => STOP_LOSS_PERCENT,
        'take_profit_percent' => TAKE_PROFIT_PERCENT
    ],
    'price_info' => [
        'current_market_price' => $current_price,
        'order_price' => $formatted_price,
        'calculated_stop_loss' => $calculated_stop_loss,
        'calculated_take_profit' => $calculated_take_profit,
        'adjusted_stop_loss' => $formatted_stop_loss,
        'adjusted_take_profit' => $formatted_take_profit
    ],
    'quantity_info' => [
        'max_quantity' => $max_quantity,
        'actual_quantity' => $formatted_quantity
    ]
]);

// ==================== YARDIMCI FONKSİYONLAR ====================

// Kaldıraç ayarla
function setLeverage($base_url, $symbol, $leverage) {
    $timestamp = round(microtime(true) * 1000);
    $params = [
        'symbol' => $symbol,
        'leverage' => $leverage,
        'timestamp' => $timestamp
    ];
    
    $query_string = http_build_query($params);
    $signature = hash_hmac('sha256', $query_string, API_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url . '/fapi/v1/leverage?' . $query_string . '&signature=' . $signature);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-MBX-APIKEY: ' . API_KEY
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        throw new Exception('CURL hatası: ' . $curl_error);
    }
    
    if ($http_code !== 200) {
        throw new Exception('HTTP Kodu: ' . $http_code . ', Yanıt: ' . $response);
    }
    
    return json_decode($response, true);
}

// Mevcut fiyatı al
function getCurrentPrice($base_url, $symbol) {
    $ticker_url = $base_url . '/fapi/v1/ticker/price?symbol=' . $symbol;
    $ticker_response = file_get_contents($ticker_url);
    
    if ($ticker_response === false) {
        throw new Exception('Fiyat bilgisi alınamadı');
    }
    
    $ticker_data = json_decode($ticker_response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Fiyat verisi JSON formatında değil: ' . $ticker_response);
    }
    
    return floatval($ticker_data['price']);
}

// Exchange bilgilerini al
function getExchangeInfo($base_url) {
    $exchange_info_url = $base_url . '/fapi/v1/exchangeInfo';
    $exchange_info_response = file_get_contents($exchange_info_url);
    
    if ($exchange_info_response === false) {
        throw new Exception('Exchange bilgileri alınamadı');
    }
    
    $exchange_info = json_decode($exchange_info_response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Exchange bilgileri JSON formatında değil: ' . $exchange_info_response);
    }
    
    return $exchange_info;
}

// Sembol bilgilerini bul
function findSymbolInfo($exchange_info, $symbol) {
    foreach ($exchange_info['symbols'] as $s) {
        if ($s['symbol'] === $symbol) {
            return $s;
        }
    }
    return null;
}

// Fiyat ve miktar hassasiyetlerini al
function getPrecisions($symbol_info) {
    $price_precision = 0;
    $quantity_precision = 0;
    
    foreach ($symbol_info['filters'] as $filter) {
        if ($filter['filterType'] === 'PRICE_FILTER') {
            $tick_size = $filter['tickSize'];
            $price_precision = strlen(substr(strrchr($tick_size, "1"), 1));
        }
        if ($filter['filterType'] === 'LOT_SIZE') {
            $step_size = $filter['stepSize'];
            $quantity_precision = strlen(substr(strrchr($step_size, "1"), 1));
        }
    }
    
    return [
        'price_precision' => $price_precision,
        'quantity_precision' => $quantity_precision
    ];
}

// Pozisyonları al
function getPositions($base_url, $symbol) {
    $timestamp = round(microtime(true) * 1000);
    $position_params = [
        'symbol' => $symbol,
        'timestamp' => $timestamp
    ];
    
    $position_query = http_build_query($position_params);
    $position_signature = hash_hmac('sha256', $position_query, API_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url . '/fapi/v2/positionRisk?' . $position_query . '&signature=' . $position_signature);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-MBX-APIKEY: ' . API_KEY
    ]);
    
    $position_response = curl_exec($ch);
    $position_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        throw new Exception('CURL hatası: ' . $curl_error);
    }
    
    if ($position_http_code !== 200) {
        throw new Exception('HTTP Kodu: ' . $position_http_code . ', Yanıt: ' . $position_response);
    }
    
    $positions = json_decode($position_response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Pozisyon verisi JSON formatında değil: ' . $position_response);
    }
    
    return $positions;
}

// Ana emri gönder
function placeMainOrder($base_url, $symbol, $direction, $price, $quantity) {
    $timestamp = round(microtime(true) * 1000);
    $params = [
        'symbol' => $symbol,
        'side' => $direction === 'LONG' ? 'BUY' : 'SELL',
        'type' => 'LIMIT',
        'timeInForce' => 'GTC',
        'quantity' => $quantity,
        'price' => $price,
        'timestamp' => $timestamp
    ];
    
    $query_string = http_build_query($params);
    $signature = hash_hmac('sha256', $query_string, API_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url . '/fapi/v1/order?' . $query_string . '&signature=' . $signature);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-MBX-APIKEY: ' . API_KEY
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        throw new Exception('CURL hatası: ' . $curl_error);
    }
    
    if ($http_code !== 200) {
        throw new Exception('HTTP Kodu: ' . $http_code . ', Yanıt: ' . $response);
    }
    
    $order_result = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Emir yanıtı JSON formatında değil: ' . $response);
    }
    
    return $order_result;
}

// Stop Loss emri gönder
function placeStopLossOrder($base_url, $symbol, $direction, $quantity, $stop_price) {
    $timestamp = round(microtime(true) * 1000);
    $params = [
        'symbol' => $symbol,
        'side' => $direction === 'LONG' ? 'SELL' : 'BUY',
        'type' => 'STOP_MARKET',
        'quantity' => $quantity,
        'stopPrice' => $stop_price,
        'closePosition' => 'true',
        'timestamp' => $timestamp
    ];
    
    $query_string = http_build_query($params);
    $signature = hash_hmac('sha256', $query_string, API_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url . '/fapi/v1/order?' . $query_string . '&signature=' . $signature);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-MBX-APIKEY: ' . API_KEY
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        throw new Exception('CURL hatası: ' . $curl_error);
    }
    
    if ($http_code !== 200) {
        throw new Exception('HTTP Kodu: ' . $http_code . ', Yanıt: ' . $response);
    }
    
    return json_decode($response, true);
}

// Take Profit emri gönder
function placeTakeProfitOrder($base_url, $symbol, $direction, $quantity, $take_profit_price) {
    $timestamp = round(microtime(true) * 1000);
    $params = [
        'symbol' => $symbol,
        'side' => $direction === 'LONG' ? 'SELL' : 'BUY',
        'type' => 'TAKE_PROFIT_MARKET',
        'quantity' => $quantity,
        'stopPrice' => $take_profit_price,
        'closePosition' => 'true',
        'timestamp' => $timestamp
    ];
    
    $query_string = http_build_query($params);
    $signature = hash_hmac('sha256', $query_string, API_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url . '/fapi/v1/order?' . $query_string . '&signature=' . $signature);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-MBX-APIKEY: ' . API_KEY
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        throw new Exception('CURL hatası: ' . $curl_error);
    }
    
    if ($http_code !== 200) {
        throw new Exception('HTTP Kodu: ' . $http_code . ', Yanıt: ' . $response);
    }
    
    return json_decode($response, true);
}
?>
Taslak ve formül için cgpt
Tasarım ve ana yapı için claude
hata düzeltmeleri için v0'a
derleme toparlama çalıştırma ve emek için bana teşekkürler


Başarılar.