• 22-04-2025, 11:42:06
    #1

    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.
    • amiral79
    • erhancopper
    • erdem0523
    amiral79, erhancopper ve erdem0523 bunu beğendi.
    3 kişi bunu beğendi.
  • 23-04-2025, 09:58:16
    #2
    güzel gibi duruyor kripto paraya uzağım ancak işlem anladığım kadarı ile yükselecek bir durumda yada düşecek biurumda kendi kendine işlemmi açıyor hocam ?
  • 23-04-2025, 10:12:34
    #3
    Furkanavci adlı üyeden alıntı: mesajı görüntüle
    güzel gibi duruyor kripto paraya uzağım ancak işlem anladığım kadarı ile yükselecek bir durumda yada düşecek biurumda kendi kendine işlemmi açıyor hocam ?
    evet ama geliştirilmesi gerekiyor, adx hesaplaması hatalı bu halde, konu ilgi görmeyince güncellemedim,
    şuan çok daha ileri seviyede 10/8 başarı oranında ve tek yönlü çalıştırmaya başladım.
    long yanıltıyor short is king mantığına büründüm.

    4 işlem açtım yakalandı şuan birisi )

  • 24-04-2025, 17:38:55
    #4
    Elinize sağlık hocam geliştirmek için böyle bir şey arıyordum bende
  • 26-04-2025, 14:09:41
    #5
    Ellerine sağlık hocam güncellenmiş hali mevcut mu ?
  • 27-04-2025, 09:01:37
    #6
    Swaid adlı üyeden alıntı: mesajı görüntüle
    Elinize sağlık hocam geliştirmek için böyle bir şey arıyordum bende
    adx hatasını çözerseniz oldukça başarılı.

    berkaysaatci adlı üyeden alıntı: mesajı görüntüle
    Ellerine sağlık hocam güncellenmiş hali mevcut mu ?
    mevcut fakat, paylaşabileceğim hali budur.

    manuel ve tek coin için başka bir bot daha vereyim test edilmedi(sinyal olmadığı için)

    index.php

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Binance Futures Trading Bot</title>
        <!-- Bootstrap CSS -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
        <!-- Font Awesome -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <!-- Chart.js -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.min.css" rel="stylesheet">
        <style>
            body {
                padding-top: 20px;
                background-color: #f5f5f5;
            }
            .card {
                border-radius: 10px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                margin-bottom: 20px;
            }
            .card-header {
                background-color: #f8f9fa;
                border-bottom: 1px solid #e3e6f0;
                font-weight: bold;
            }
            .indicator {
                display: inline-block;
                width: 12px;
                height: 12px;
                border-radius: 50%;
                margin-right: 5px;
            }
            .indicator-green {
                background-color: #28a745;
            }
            .indicator-red {
                background-color: #dc3545;
            }
            .indicator-yellow {
                background-color: #ffc107;
            }
            .table td, .table th {
                vertical-align: middle;
            }
            .signal-buy {
                color: #28a745;
                font-weight: bold;
            }
            .signal-sell {
                color: #dc3545;
                font-weight: bold;
            }
            .signal-neutral {
                color: #6c757d;
            }
            #tradingChart {
                height: 300px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row mb-4">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center">
                        <h1>Binance Futures Trading Bot</h1>
                        <div>
                            <span id="botStatus" class="badge bg-danger">Stopped</span>
                            <button id="toggleBot" class="btn btn-success ms-2">Start Bot</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <!-- Market Overview -->
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span>Market Overview</span>
                            <div>
                                <select id="symbolSelect" class="form-select form-select-sm d-inline-block" style="width: auto;">
                                    <option value="BTCUSDT">BTCUSDT</option>
                                    <option value="ETHUSDT">ETHUSDT</option>
                                    <option value="BNBUSDT">BNBUSDT</option>
                                    <option value="SOLUSDT">SOLUSDT</option>
                                </select>
                                <select id="intervalSelect" class="form-select form-select-sm d-inline-block ms-2" style="width: auto;">
                                    <option value="1m">1m</option>
                                    <option value="5m">5m</option>
                                    <option value="15m">15m</option>
                                    <option value="1h" selected>1h</option>
                                    <option value="4h">4h</option>
                                    <option value="1d">1d</option>
                                </select>
                            </div>
                        </div>
                        <div class="card-body">
                            <canvas id="tradingChart"></canvas>
                        </div>
                    </div>
                    
                    <!-- Technical Indicators -->
                    <div class="card">
                        <div class="card-header">
                            Technical Indicators
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table table-sm">
                                        <tbody>
                                            <tr>
                                                <td>EMA(50)</td>
                                                <td id="ema50">--</td>
                                                <td id="ema50Status"></td>
                                            </tr>
                                            <tr>
                                                <td>EMA(200)</td>
                                                <td id="ema200">--</td>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td>ADX</td>
                                                <td id="adx">--</td>
                                                <td id="adxStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>MACD</td>
                                                <td id="macd">--</td>
                                                <td id="macdStatus"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table table-sm">
                                        <tbody>
                                            <tr>
                                                <td>VWAP</td>
                                                <td id="vwap">--</td>
                                                <td id="vwapStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>Pivot Level</td>
                                                <td id="pivotLevel">--</td>
                                                <td id="pivotStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>ATR</td>
                                                <td id="atr">--</td>
                                                <td id="atrStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>Price Pattern</td>
                                                <td id="pricePattern">--</td>
                                                <td id="patternStatus"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="alert mt-3 text-center" id="signalAlert">
                                <strong id="signalText">Waiting for signal...</strong>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Account Overview -->
                <div class="col-md-4">
                    <!-- Bot Settings -->
                    <div class="card">
                        <div class="card-header">
                            Bot Settings
                        </div>
                        <div class="card-body">
                            <form id="settingsForm">
                                <div class="mb-3">
                                    <label class="form-label">Trading Pair</label>
                                    <select id="tradingPair" class="form-select">
                                        <option value="BTCUSDT">BTCUSDT</option>
                                        <option value="ETHUSDT">ETHUSDT</option>
                                        <option value="BNBUSDT">BNBUSDT</option>
                                        <option value="SOLUSDT">SOLUSDT</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Interval</label>
                                    <select id="tradingInterval" class="form-select">
                                        <option value="1m">1 Minute</option>
                                        <option value="5m">5 Minutes</option>
                                        <option value="15m">15 Minutes</option>
                                        <option value="1h" selected>1 Hour</option>
                                        <option value="4h">4 Hours</option>
                                        <option value="1d">1 Day</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Trade Amount (USDT)</label>
                                    <input type="number" id="tradeAmount" class="form-control" value="100">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">ATR Threshold</label>
                                    <input type="number" id="atrThreshold" class="form-control" value="50">
                                </div>
                                <button type="submit" class="btn btn-primary">Save Settings</button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Account Balance -->
                    <div class="card">
                        <div class="card-header">
                            Account Balance
                        </div>
                        <div class="card-body">
                            <table class="table table-sm">
                                <tbody id="balanceTable">
                                    <tr>
                                        <td>USDT</td>
                                        <td class="text-end">0.00</td>
                                    </tr>
                                    <tr>
                                        <td>BTC</td>
                                        <td class="text-end">0.00</td>
                                    </tr>
                                </tbody>
                            </table>
                            <button id="refreshBalance" class="btn btn-sm btn-outline-secondary">Refresh</button>
                        </div>
                    </div>
                    
                    <!-- Open Positions -->
                    <div class="card">
                        <div class="card-header">
                            Open Positions
                        </div>
                        <div class="card-body">
                            <table class="table table-sm" id="positionsTable">
                                <thead>
                                    <tr>
                                        <th>Symbol</th>
                                        <th>Size</th>
                                        <th>PnL</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="3" class="text-center">No open positions</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Recent Trades -->
                    <div class="card">
                        <div class="card-header">
                            Recent Trades
                        </div>
                        <div class="card-body">
                            <table class="table table-sm" id="tradesTable">
                                <thead>
                                    <tr>
                                        <th>Symbol</th>
                                        <th>Side</th>
                                        <th>Price</th>
                                        <th>Time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="4" class="text-center">No recent trades</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- jQuery -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
        <!-- Bootstrap JS -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
        <!-- Chart.js -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
        
        <script>
        $(document).ready(function() {
            // Global variables
            let chart;
            let botRunning = false;
            let intervalId;
            const API_URL = 'api.php'; // Backend PHP endpoint
            
            // Initialize
            initializeChart();
            updateMarketData();
            checkBotStatus();
            
            // Event handlers
            $('#toggleBot').on('click', toggleBot);
            $('#symbolSelect, #intervalSelect').on('change', updateMarketData);
            $('#refreshBalance').on('click', loadAccountBalance);
            $('#settingsForm').on('submit', saveSettings);
            
            // Initialize Chart
            function initializeChart() {
                const ctx = document.getElementById('tradingChart').getContext('2d');
                chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Price',
                            data: [],
                            borderColor: 'rgb(75, 192, 192)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false
                            }
                        }
                    }
                });
            }
            
            // Load and update market data
            function updateMarketData() {
                const symbol = $('#symbolSelect').val();
                const interval = $('#intervalSelect').val();
                
                $.ajax({
                    url: `${API_URL}?action=analyze&symbol=${symbol}&interval=${interval}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updateChart(response.analysis);
                            updateIndicators(response.analysis);
                            updateSignal(response.signal);
                        } else {
                            showError('Failed to fetch market data');
                        }
                    },
                    error: function() {
                        showError('Failed to connect to API');
                    }
                });
            }
            
            // Update chart with new data
            function updateChart(analysis) {
                // For a real implementation, you would format the actual market data
                // This is a placeholder that would be replaced with real data
                const timestamps = Array.from({length: 50}, (_, i) => new Date(Date.now() - i * 3600000).toLocaleTimeString());
                const prices = Array.from({length: 50}, (_, i) => 40000 + Math.random() * 2000);
                
                chart.data.labels = timestamps.reverse();
                chart.data.datasets[0].data = prices.reverse();
                chart.update();
            }
            
            // Update technical indicators display
            function updateIndicators(analysis) {
                // Update EMA values
                $('#ema50').text(analysis.ema50.toFixed(2));
                $('#ema200').text(analysis.ema200.toFixed(2));
                
                // Update ADX
                $('#adx').text(analysis.adx.toFixed(2));
                
                // Update MACD
                $('#macd').text(analysis.macd.toFixed(6));
                
                // Update VWAP
                $('#vwap').text(analysis.vwap.toFixed(2));
                
                // Update Pivot
                $('#pivotLevel').text(analysis.pivotLevel.toFixed(2));
                
                // Update ATR
                $('#atr').text(analysis.atr.toFixed(2));
                
                // Update Price Pattern
                let patternText = '';
                if (analysis.higherHighs && analysis.higherLows) {
                    patternText = 'Uptrend';
                    $('#patternStatus').html('<span class="indicator indicator-green"></span>');
                } else if (analysis.lowerHighs && analysis.lowerLows) {
                    patternText = 'Downtrend';
                    $('#patternStatus').html('<span class="indicator indicator-red"></span>');
                } else {
                    patternText = 'Sideways';
                    $('#patternStatus').html('<span class="indicator indicator-yellow"></span>');
                }
                $('#pricePattern').text(patternText);
                
                // Update indicator status
                $('#ema50Status').html(analysis.ema50 > analysis.ema200 ? 
                    '<span class="indicator indicator-green"></span>' : 
                    '<span class="indicator indicator-red"></span>');
                    
                $('#adxStatus').html(analysis.adx > 25 ? 
                    '<span class="indicator indicator-green"></span>' : 
                    '<span class="indicator indicator-red"></span>');
                    
                $('#macdStatus').html(analysis.macd > analysis.macdSignal ? 
                    '<span class="indicator indicator-green"></span>' : 
                    '<span class="indicator indicator-red"></span>');
                    
                $('#vwapStatus').html(analysis.close > analysis.vwap ? 
                    '<span class="indicator indicator-green"></span>' : 
                    '<span class="indicator indicator-red"></span>');
                    
                $('#pivotStatus').html(analysis.close > analysis.pivotLevel ? 
                    '<span class="indicator indicator-green"></span>' : 
                    '<span class="indicator indicator-red"></span>');
                    
                $('#atrStatus').html(analysis.atr > $('#atrThreshold').val() ? 
                    '<span class="indicator indicator-green"></span>' : 
                    '<span class="indicator indicator-red"></span>');
            }
            
            // Update signal display
            function updateSignal(signal) {
                let alertClass = 'alert-secondary';
                let signalClass = 'signal-neutral';
                
                if (signal === 'BUY') {
                    alertClass = 'alert-success';
                    signalClass = 'signal-buy';
                } else if (signal === 'SELL') {
                    alertClass = 'alert-danger';
                    signalClass = 'signal-sell';
                }
                
                $('#signalAlert').removeClass('alert-success alert-danger alert-secondary').addClass(alertClass);
                $('#signalText').removeClass('signal-buy signal-sell signal-neutral').addClass(signalClass).text(`Signal: ${signal}`);
            }
            
            // Toggle bot status
            function toggleBot() {
                const action = botRunning ? 'stop' : 'start';
                
                $.ajax({
                    url: `${API_URL}?action=${action}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            botRunning = action === 'start';
                            updateBotStatusUI();
                            
                            if (botRunning) {
                                // Start automatic data refresh
                                intervalId = setInterval(refreshData, 30000); // Refresh every 30 seconds
                            } else {
                                // Stop automatic refresh
                                clearInterval(intervalId);
                            }
                        } else {
                            showError(`Failed to ${action} bot`);
                        }
                    },
                    error: function() {
                        showError('Failed to connect to API');
                    }
                });
            }
            
            // Check bot status on page load
            function checkBotStatus() {
                $.ajax({
                    url: `${API_URL}?action=status`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            botRunning = response.running;
                            updateBotStatusUI();
                            
                            if (botRunning) {
                                // Start automatic data refresh
                                intervalId = setInterval(refreshData, 30000); // Refresh every 30 seconds
                            }
                        }
                    }
                });
                
                // Load initial data
                loadAccountBalance();
                loadOpenPositions();
                loadTradeHistory();
            }
            
            // Update bot status UI
            function updateBotStatusUI() {
                if (botRunning) {
                    $('#botStatus').removeClass('bg-danger').addClass('bg-success').text('Running');
                    $('#toggleBot').removeClass('btn-success').addClass('btn-danger').text('Stop Bot');
                } else {
                    $('#botStatus').removeClass('bg-success').addClass('bg-danger').text('Stopped');
                    $('#toggleBot').removeClass('btn-danger').addClass('btn-success').text('Start Bot');
                }
            }
            
            // Refresh all data
            function refreshData() {
                updateMarketData();
                loadAccountBalance();
                loadOpenPositions();
                loadTradeHistory();
            }
            
            // Load account balance
            function loadAccountBalance() {
                $.ajax({
                    url: `${API_URL}?action=balance`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updateBalanceTable(response.balance);
                        }
                    }
                });
            }
            
            // Update balance table
            function updateBalanceTable(balances) {
                let tableHtml = '';
                
                for (const asset in balances) {
                    tableHtml += `
                    <tr>
                        <td>${asset}</td>
                        <td class="text-end">${balances[asset].available.toFixed(asset === 'USDT' ? 2 : 8)}</td>
                    </tr>
                    `;
                }
                
                $('#balanceTable').html(tableHtml);
            }
            
            // Load open positions
            function loadOpenPositions() {
                $.ajax({
                    url: `${API_URL}?action=positions`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updatePositionsTable(response.positions);
                        }
                    }
                });
            }
            
            // Update positions table
            function updatePositionsTable(positions) {
                let tableHtml = '';
                
                if (positions.length === 0) {
                    tableHtml = '<tr><td colspan="3" class="text-center">No open positions</td></tr>';
                } else {
                    positions.forEach(function(position) {
                        const pnlClass = position.unRealizedProfit >= 0 ? 'text-success' : 'text-danger';
                        
                        tableHtml += `
                        <tr>
                            <td>${position.symbol}</td>
                            <td>${position.positionAmt}</td>
                            <td class="${pnlClass}">${position.unRealizedProfit.toFixed(2)}</td>
                        </tr>
                        `;
                    });
                }
                
                $('#positionsTable tbody').html(tableHtml);
            }
            
            // Load trade history
            function loadTradeHistory() {
                $.ajax({
                    url: `${API_URL}?action=history`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updateTradesTable(response.history);
                        }
                    }
                });
            }
            
            // Update trades table
            function updateTradesTable(trades) {
                let tableHtml = '';
                
                if (trades.length === 0) {
                    tableHtml = '<tr><td colspan="4" class="text-center">No recent trades</td></tr>';
                } else {
                    trades.forEach(function(trade) {
                        const side = trade.isBuyer ? 'BUY' : 'SELL';
                        const sideClass = trade.isBuyer ? 'text-success' : 'text-danger';
                        const time = new Date(trade.time).toLocaleString();
                        
                        tableHtml += `
                        <tr>
                            <td>${trade.symbol}</td>
                            <td class="${sideClass}">${side}</td>
                            <td>${parseFloat(trade.price).toFixed(2)}</td>
                            <td>${time}</td>
                        </tr>
                        `;
                    });
                }
                
                $('#tradesTable tbody').html(tableHtml);
            }
            
            // Save bot settings
            function saveSettings(e) {
                e.preventDefault();
                
                const settings = {
                    symbol: $('#tradingPair').val(),
                    interval: $('#tradingInterval').val(),
                    tradeAmount: parseFloat($('#tradeAmount').val()),
                    atrThreshold: parseFloat($('#atrThreshold').val())
                };
                
                $.ajax({
                    url: `${API_URL}?action=settings`,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(settings),
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            showSuccess('Settings saved successfully');
                            
                            // Update chart symbol and interval if needed
                            if ($('#symbolSelect').val() !== settings.symbol) {
                                $('#symbolSelect').val(settings.symbol);
                            }
                            
                            if ($('#intervalSelect').val() !== settings.interval) {
                                $('#intervalSelect').val(settings.interval);
                            }
                            
                            updateMarketData();
                        } else {
                            showError('Failed to save settings');
                        }
                    },
                    error: function() {
                        showError('Failed to connect to API');
                    }
                });
            }
            
            // Show error message
            function showError(message) {
                alert(`Error: ${message}`);
            }
            
            // Show success message
            function showSuccess(message) {
                alert(`Success: ${message}`);
            }
        });
        </script>
    </body>
    </html>
    api.php

    <?php
    // Binance Futures Trading Bot - Backend Implementation
    // This script handles the connection to Binance API and executes trading logic
    
    // Configuration
    define('API_KEY', 'YOUR_BINANCE_API_KEY');
    define('API_SECRET', 'YOUR_BINANCE_API_SECRET');
    define('SYMBOL', 'BTCUSDT'); // Default trading pair
    define('INTERVAL', '4h');    // Default timeframe
    define('QUANTITY', 0.001);   // Default trading quantity
    define('ATR_THRESHOLD', 50); // Default ATR threshold
    
    // Error reporting
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // Request handling
    header('Content-Type: application/json');
    session_start();
    
    // Router
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    
    switch ($action) {
        case 'start':
            startBot();
            break;
        case 'stop':
            stopBot();
            break;
        case 'status':
            getBotStatus();
            break;
        case 'settings':
            updateSettings();
            break;
        case 'balance':
            getAccountBalance();
            break;
        case 'positions':
            getOpenPositions();
            break;
        case 'history':
            getTradeHistory();
            break;
        case 'analyze':
            analyzeMarket();
            break;
        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    }
    
    function startBot() {
        // Set status in session
        $_SESSION['bot_running'] = true;
        $_SESSION['bot_start_time'] = time();
        
        echo json_encode([
            'status' => 'success',
            'message' => 'Bot started successfully',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
    function stopBot() {
        // Set status in session
        $_SESSION['bot_running'] = false;
        
        echo json_encode([
            'status' => 'success',
            'message' => 'Bot stopped successfully',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
    function getBotStatus() {
        $running = isset($_SESSION['bot_running']) ? $_SESSION['bot_running'] : false;
        $startTime = isset($_SESSION['bot_start_time']) ? $_SESSION['bot_start_time'] : null;
        
        echo json_encode([
            'status' => 'success',
            'running' => $running,
            'start_time' => $startTime ? date('Y-m-d H:i:s', $startTime) : null,
            'uptime' => $startTime ? (time() - $startTime) : 0
        ]);
    }
    
    function updateSettings() {
        // Get JSON data from request
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!$data) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid settings data']);
            return;
        }
        
        // Save settings to session
        $_SESSION['settings'] = $data;
        
        echo json_encode([
            'status' => 'success',
            'message' => 'Settings updated successfully',
            'settings' => $data
        ]);
    }
    
    function getAccountBalance() {
        // Connect to Binance API
        $balance = getBinanceAccountBalance();
        
        echo json_encode([
            'status' => 'success',
            'balance' => $balance
        ]);
    }
    
    function getOpenPositions() {
        // Connect to Binance API
        $positions = getBinanceOpenPositions();
        
        echo json_encode([
            'status' => 'success',
            'positions' => $positions
        ]);
    }
    
    function getTradeHistory() {
        // Connect to Binance API
        $history = getBinanceTradeHistory();
        
        echo json_encode([
            'status' => 'success',
            'history' => $history
        ]);
    }
    
    function analyzeMarket() {
        // Get parameters from request
        $symbol = isset($_GET['symbol']) ? $_GET['symbol'] : SYMBOL;
        $interval = isset($_GET['interval']) ? $_GET['interval'] : INTERVAL;
        
        // Fetch market data from Binance
        $marketData = getBinanceMarketData($symbol, $interval);
        
        // Apply technical indicators
        $analysis = calculateIndicators($marketData);
        
        // Determine buy/sell signals
        $signal = determineSignal($analysis);
        
        echo json_encode([
            'status' => 'success',
            'timestamp' => date('Y-m-d H:i:s'),
            'symbol' => $symbol,
            'interval' => $interval,
            'analysis' => $analysis,
            'signal' => $signal
        ]);
    }
    
    // Binance API Functions
    function getBinanceSignature($query_string) {
        return hash_hmac('sha256', $query_string, API_SECRET);
    }
    
    function binanceApiRequest($url, $method = 'GET', $params = []) {
        $curl = curl_init();
        
        // Add timestamp for API request
        $params['timestamp'] = round(microtime(true) * 1000);
        
        // Build query string
        $query_string = http_build_query($params);
        
        // Generate signature
        $signature = getBinanceSignature($query_string);
        
        // Add signature to params
        $query_string .= "&signature={$signature}";
        
        // Prepare URL
        $url = "https://fapi.binance.com/fapi/v1/{$url}?{$query_string}";
        
        // Set cURL options
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "X-MBX-APIKEY: " . API_KEY
            ],
        ]);
        
        $response = curl_exec($curl);
        $err = curl_error($curl);
        
        curl_close($curl);
        
        if ($err) {
            return ['error' => "cURL Error #:" . $err];
        } else {
            return json_decode($response, true);
        }
    }
    
    function getBinanceAccountBalance() {
        // In a real implementation, you would call Binance's account endpoint
        // This is a simplified example
        $response = binanceApiRequest("account", "GET");
        
        // For testing purposes
        if (!isset($response['assets'])) {
            return [
                'USDT' => ['available' => 1000.00, 'total' => 1200.00],
                'BTC' => ['available' => 0.05, 'total' => 0.05]
            ];
        }
        
        $balances = [];
        foreach ($response['assets'] as $asset) {
            $balances[$asset['asset']] = [
                'available' => floatval($asset['availableBalance']),
                'total' => floatval($asset['walletBalance'])
            ];
        }
        
        return $balances;
    }
    
    function getBinanceOpenPositions() {
        // In a real implementation, you would call Binance's positions endpoint
        // This is a simplified example
        $response = binanceApiRequest("positionRisk", "GET");
        
        // For testing purposes
        if (!isset($response[0])) {
            return [
                [
                    'symbol' => 'BTCUSDT',
                    'positionAmt' => 0.01,
                    'entryPrice' => 40000,
                    'markPrice' => 41000,
                    'unRealizedProfit' => 10,
                    'liquidationPrice' => 35000
                ]
            ];
        }
        
        $positions = [];
        foreach ($response as $position) {
            if (floatval($position['positionAmt']) != 0) {
                $positions[] = [
                    'symbol' => $position['symbol'],
                    'positionAmt' => floatval($position['positionAmt']),
                    'entryPrice' => floatval($position['entryPrice']),
                    'markPrice' => floatval($position['markPrice']),
                    'unRealizedProfit' => floatval($position['unRealizedProfit']),
                    'liquidationPrice' => floatval($position['liquidationPrice'])
                ];
            }
        }
        
        return $positions;
    }
    
    function getBinanceTradeHistory() {
        // In a real implementation, you would call Binance's trade history endpoint
        // This is a simplified example
        $response = binanceApiRequest("userTrades", "GET", ['symbol' => SYMBOL]);
        
        // For testing purposes
        if (!isset($response[0])) {
            return [
                [
                    'symbol' => 'BTCUSDT',
                    'id' => 123456,
                    'orderId' => 987654,
                    'price' => 40000,
                    'qty' => 0.01,
                    'quoteQty' => 400,
                    'time' => time() - 3600,
                    'isBuyer' => true
                ],
                [
                    'symbol' => 'BTCUSDT',
                    'id' => 123457,
                    'orderId' => 987655,
                    'price' => 41000,
                    'qty' => 0.01,
                    'quoteQty' => 410,
                    'time' => time() - 1800,
                    'isBuyer' => false
                ]
            ];
        }
        
        return $response;
    }
    
    function getBinanceMarketData($symbol, $interval) {
        // Endpoint for candlestick data
        $url = "https://fapi.binance.com/fapi/v1/klines?symbol={$symbol}&interval={$interval}&limit=500";
        
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
        ]);
        
        $response = curl_exec($curl);
        $err = curl_error($curl);
        
        curl_close($curl);
        
        if ($err) {
            return ['error' => "cURL Error #:" . $err];
        }
        
        $data = json_decode($response, true);
        $formattedData = [];
        
        foreach ($data as $candle) {
            $formattedData[] = [
                'timestamp' => $candle[0],
                'open' => floatval($candle[1]),
                'high' => floatval($candle[2]),
                'low' => floatval($candle[3]),
                'close' => floatval($candle[4]),
                'volume' => floatval($candle[5]),
                'close_time' => $candle[6],
                'quote_asset_volume' => floatval($candle[7]),
                'number_of_trades' => $candle[8],
                'taker_buy_base_asset_volume' => floatval($candle[9]),
                'taker_buy_quote_asset_volume' => floatval($candle[10])
            ];
        }
        
        return $formattedData;
    }
    
    // Technical analysis functions
    function calculateIndicators($marketData) {
        $closes = array_column($marketData, 'close');
        $highs = array_column($marketData, 'high');
        $lows = array_column($marketData, 'low');
        
        // EMA calculations
        $ema50 = calculateEMA($closes, 50);
        $ema200 = calculateEMA($closes, 200);
        
        // ADX calculation
        $adx = calculateADX($highs, $lows, $closes, 14);
        
        // MACD calculation
        $macd = calculateMACD($closes);
        
        // VWAP calculation
        $volumes = array_column($marketData, 'volume');
        $vwap = calculateVWAP($marketData);
        
        // Pivot Points
        $pivotLevel = calculatePivotPoint($marketData);
        
        // ATR calculation
        $atr = calculateATR($highs, $lows, $closes, 14);
        
        // Higher Highs, Higher Lows, Lower Highs, Lower Lows
        $patterns = identifyPricePatterns($highs, $lows, 5);
        
        $lastClose = end($closes);
        
        return [
            'ema50' => end($ema50),
            'ema200' => end($ema200),
            'adx' => end($adx),
            'macd' => end($macd['macd']),
            'macdSignal' => end($macd['signal']),
            'vwap' => end($vwap),
            'pivotLevel' => $pivotLevel,
            'atr' => end($atr),
            'higherHighs' => $patterns['higherHighs'],
            'higherLows' => $patterns['higherLows'],
            'lowerHighs' => $patterns['lowerHighs'],
            'lowerLows' => $patterns['lowerLows'],
            'close' => $lastClose
        ];
    }
    
    function calculateEMA($prices, $period) {
        $multiplier = 2 / ($period + 1);
        $ema = [];
        
        // Use SMA for the first value
        $sma = array_sum(array_slice($prices, 0, $period)) / $period;
        $ema[] = $sma;
        
        // Calculate EMA for remaining prices
        for ($i = $period; $i < count($prices); $i++) {
            $ema[] = ($prices[$i] - end($ema)) * $multiplier + end($ema);
        }
        
        return $ema;
    }
    
    function calculateADX($high, $low, $close, $period) {
        // This is a simplified ADX calculation
        // In a real implementation, you would need a more accurate calculation
        $adx = [];
        for ($i = $period; $i < count($close); $i++) {
            // Simplified calculation
            $adx[] = 25 + (rand(-5, 5)); // Random value around 25 for testing
        }
        return $adx;
    }
    
    function calculateMACD($prices, $fastPeriod = 12, $slowPeriod = 26, $signalPeriod = 9) {
        $fastEMA = calculateEMA($prices, $fastPeriod);
        $slowEMA = calculateEMA($prices, $slowPeriod);
        
        // Calculate MACD line
        $macdLine = [];
        for ($i = 0; $i < count($slowEMA); $i++) {
            $macdLine[] = $fastEMA[$i + (count($fastEMA) - count($slowEMA))] - $slowEMA[$i];
        }
        
        // Calculate Signal line (EMA of MACD line)
        $signalLine = calculateEMA($macdLine, $signalPeriod);
        
        // Calculate Histogram
        $histogram = [];
        for ($i = 0; $i < count($signalLine); $i++) {
            $histogram[] = $macdLine[$i + (count($macdLine) - count($signalLine))] - $signalLine[$i];
        }
        
        return [
            'macd' => $macdLine,
            'signal' => $signalLine,
            'histogram' => $histogram
        ];
    }
    
    function calculateVWAP($marketData) {
        $vwap = [];
        $cumulativeTPV = 0; // Total Price * Volume
        $cumulativeVolume = 0;
        
        foreach ($marketData as $candle) {
            $typicalPrice = ($candle['high'] + $candle['low'] + $candle['close']) / 3;
            $volume = $candle['volume'];
            
            $cumulativeTPV += $typicalPrice * $volume;
            $cumulativeVolume += $volume;
            
            $vwap[] = $cumulativeTPV / $cumulativeVolume;
        }
        
        return $vwap;
    }
    
    function calculatePivotPoint($marketData) {
        // Using the last complete day for calculation
        $lastDay = end($marketData);
        $high = $lastDay['high'];
        $low = $lastDay['low'];
        $close = $lastDay['close'];
        
        // Classical pivot point
        $pivot = ($high + $low + $close) / 3;
        
        return $pivot;
    }
    
    function calculateATR($highs, $lows, $closes, $period) {
        $trueRanges = [];
        $atr = [];
        
        // Calculate True Range for the first period
        for ($i = 1; $i < count($closes); $i++) {
            $highLowRange = $highs[$i] - $lows[$i];
            $highClosePrevRange = abs($highs[$i] - $closes[$i - 1]);
            $lowClosePrevRange = abs($lows[$i] - $closes[$i - 1]);
            
            $trueRanges[] = max($highLowRange, $highClosePrevRange, $lowClosePrevRange);
        }
        
        // First ATR value is simple average
        $firstATR = array_sum(array_slice($trueRanges, 0, $period)) / $period;
        $atr[] = $firstATR;
        
        // Calculate remaining ATR values
        for ($i = 1; $i < count($trueRanges) - $period + 1; $i++) {
            $atr[] = (($atr[$i - 1] * ($period - 1)) + $trueRanges[$i + $period - 1]) / $period;
        }
        
        return $atr;
    }
    
    function identifyPricePatterns($highs, $lows, $lookback) {
        $recentHighs = array_slice($highs, -$lookback);
        $recentLows = array_slice($lows, -$lookback);
        
        $higherHighs = true;
        $higherLows = true;
        $lowerHighs = true;
        $lowerLows = true;
        
        // Check for higher highs and higher lows (uptrend)
        for ($i = 1; $i < count($recentHighs); $i++) {
            if ($recentHighs[$i] <= $recentHighs[$i - 1]) {
                $higherHighs = false;
            }
            if ($recentLows[$i] <= $recentLows[$i - 1]) {
                $higherLows = false;
            }
        }
        
        // Check for lower highs and lower lows (downtrend)
        for ($i = 1; $i < count($recentHighs); $i++) {
            if ($recentHighs[$i] >= $recentHighs[$i - 1]) {
                $lowerHighs = false;
            }
            if ($recentLows[$i] >= $recentLows[$i - 1]) {
                $lowerLows = false;
            }
        }
        
        return [
            'higherHighs' => $higherHighs,
            'higherLows' => $higherLows,
            'lowerHighs' => $lowerHighs,
            'lowerLows' => $lowerLows
        ];
    }
    
    function determineSignal($analysis) {
        // Buy signal conditions
        $buyConditions = 
            $analysis['ema50'] > $analysis['ema200'] &&
            $analysis['adx'] > 25 &&
            $analysis['macd'] > $analysis['macdSignal'] &&
            $analysis['close'] > $analysis['vwap'] &&
            $analysis['close'] > $analysis['pivotLevel'] &&
            $analysis['atr'] > getATRThreshold() &&
            $analysis['higherHighs'] &&
            $analysis['higherLows'];
        
        // Sell signal conditions
        $sellConditions = 
            $analysis['ema50'] < $analysis['ema200'] &&
            $analysis['adx'] > 25 &&
            $analysis['macd'] < $analysis['macdSignal'] &&
            $analysis['close'] < $analysis['vwap'] &&
            $analysis['close'] < $analysis['pivotLevel'] &&
            $analysis['atr'] > getATRThreshold() &&
            $analysis['lowerHighs'] &&
            $analysis['lowerLows'];
        
        if ($buyConditions) {
            return 'BUY';
        } elseif ($sellConditions) {
            return 'SELL';
        } else {
            return 'NEUTRAL';
        }
    }
    
    function getATRThreshold() {
        // Get from settings or use default
        return isset($_SESSION['settings']['atrThreshold']) ? $_SESSION['settings']['atrThreshold'] : ATR_THRESHOLD;
    }
    
    // Place market order (simplified example)
    function placeBinanceOrder($symbol, $side, $quantity) {
        $params = [
            'symbol' => $symbol,
            'side' => $side, // BUY or SELL
            'type' => 'MARKET',
            'quantity' => $quantity
        ];
        
        return binanceApiRequest("order", "POST", $params);
    }
    Testnet testi yapılmadı dikkatli kullanın.. sağlıklı veri 4h 12h olur genelde scalping için uygun değildir.
  • 27-04-2025, 14:34:03
    #7
    Misafir adlı üyeden alıntı: mesajı görüntüle
    adx hatasını çözerseniz oldukça başarılı.


    mevcut fakat, paylaşabileceğim hali budur.

    manuel ve tek coin için başka bir bot daha vereyim test edilmedi(sinyal olmadığı için)

    index.php

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Binance Futures Trading Bot</title>
        <!-- Bootstrap CSS -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
        <!-- Font Awesome -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <!-- Chart.js -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.min.css" rel="stylesheet">
        <style>
            body {
                padding-top: 20px;
                background-color: #f5f5f5;
            }
            .card {
                border-radius: 10px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                margin-bottom: 20px;
            }
            .card-header {
                background-color: #f8f9fa;
                border-bottom: 1px solid #e3e6f0;
                font-weight: bold;
            }
            .indicator {
                display: inline-block;
                width: 12px;
                height: 12px;
                border-radius: 50%;
                margin-right: 5px;
            }
            .indicator-green {
                background-color: #28a745;
            }
            .indicator-red {
                background-color: #dc3545;
            }
            .indicator-yellow {
                background-color: #ffc107;
            }
            .table td, .table th {
                vertical-align: middle;
            }
            .signal-buy {
                color: #28a745;
                font-weight: bold;
            }
            .signal-sell {
                color: #dc3545;
                font-weight: bold;
            }
            .signal-neutral {
                color: #6c757d;
            }
            #tradingChart {
                height: 300px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row mb-4">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center">
                        <h1>Binance Futures Trading Bot</h1>
                        <div>
                            <span id="botStatus" class="badge bg-danger">Stopped</span>
                            <button id="toggleBot" class="btn btn-success ms-2">Start Bot</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <!-- Market Overview -->
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span>Market Overview</span>
                            <div>
                                <select id="symbolSelect" class="form-select form-select-sm d-inline-block" style="width: auto;">
                                    <option value="BTCUSDT">BTCUSDT</option>
                                    <option value="ETHUSDT">ETHUSDT</option>
                                    <option value="BNBUSDT">BNBUSDT</option>
                                    <option value="SOLUSDT">SOLUSDT</option>
                                </select>
                                <select id="intervalSelect" class="form-select form-select-sm d-inline-block ms-2" style="width: auto;">
                                    <option value="1m">1m</option>
                                    <option value="5m">5m</option>
                                    <option value="15m">15m</option>
                                    <option value="1h" selected>1h</option>
                                    <option value="4h">4h</option>
                                    <option value="1d">1d</option>
                                </select>
                            </div>
                        </div>
                        <div class="card-body">
                            <canvas id="tradingChart"></canvas>
                        </div>
                    </div>
                    
                    <!-- Technical Indicators -->
                    <div class="card">
                        <div class="card-header">
                            Technical Indicators
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table table-sm">
                                        <tbody>
                                            <tr>
                                                <td>EMA(50)</td>
                                                <td id="ema50">--</td>
                                                <td id="ema50Status"></td>
                                            </tr>
                                            <tr>
                                                <td>EMA(200)</td>
                                                <td id="ema200">--</td>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td>ADX</td>
                                                <td id="adx">--</td>
                                                <td id="adxStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>MACD</td>
                                                <td id="macd">--</td>
                                                <td id="macdStatus"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table table-sm">
                                        <tbody>
                                            <tr>
                                                <td>VWAP</td>
                                                <td id="vwap">--</td>
                                                <td id="vwapStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>Pivot Level</td>
                                                <td id="pivotLevel">--</td>
                                                <td id="pivotStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>ATR</td>
                                                <td id="atr">--</td>
                                                <td id="atrStatus"></td>
                                            </tr>
                                            <tr>
                                                <td>Price Pattern</td>
                                                <td id="pricePattern">--</td>
                                                <td id="patternStatus"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="alert mt-3 text-center" id="signalAlert">
                                <strong id="signalText">Waiting for signal...</strong>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Account Overview -->
                <div class="col-md-4">
                    <!-- Bot Settings -->
                    <div class="card">
                        <div class="card-header">
                            Bot Settings
                        </div>
                        <div class="card-body">
                            <form id="settingsForm">
                                <div class="mb-3">
                                    <label class="form-label">Trading Pair</label>
                                    <select id="tradingPair" class="form-select">
                                        <option value="BTCUSDT">BTCUSDT</option>
                                        <option value="ETHUSDT">ETHUSDT</option>
                                        <option value="BNBUSDT">BNBUSDT</option>
                                        <option value="SOLUSDT">SOLUSDT</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Interval</label>
                                    <select id="tradingInterval" class="form-select">
                                        <option value="1m">1 Minute</option>
                                        <option value="5m">5 Minutes</option>
                                        <option value="15m">15 Minutes</option>
                                        <option value="1h" selected>1 Hour</option>
                                        <option value="4h">4 Hours</option>
                                        <option value="1d">1 Day</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Trade Amount (USDT)</label>
                                    <input type="number" id="tradeAmount" class="form-control" value="100">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">ATR Threshold</label>
                                    <input type="number" id="atrThreshold" class="form-control" value="50">
                                </div>
                                <button type="submit" class="btn btn-primary">Save Settings</button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Account Balance -->
                    <div class="card">
                        <div class="card-header">
                            Account Balance
                        </div>
                        <div class="card-body">
                            <table class="table table-sm">
                                <tbody id="balanceTable">
                                    <tr>
                                        <td>USDT</td>
                                        <td class="text-end">0.00</td>
                                    </tr>
                                    <tr>
                                        <td>BTC</td>
                                        <td class="text-end">0.00</td>
                                    </tr>
                                </tbody>
                            </table>
                            <button id="refreshBalance" class="btn btn-sm btn-outline-secondary">Refresh</button>
                        </div>
                    </div>
                    
                    <!-- Open Positions -->
                    <div class="card">
                        <div class="card-header">
                            Open Positions
                        </div>
                        <div class="card-body">
                            <table class="table table-sm" id="positionsTable">
                                <thead>
                                    <tr>
                                        <th>Symbol</th>
                                        <th>Size</th>
                                        <th>PnL</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="3" class="text-center">No open positions</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Recent Trades -->
                    <div class="card">
                        <div class="card-header">
                            Recent Trades
                        </div>
                        <div class="card-body">
                            <table class="table table-sm" id="tradesTable">
                                <thead>
                                    <tr>
                                        <th>Symbol</th>
                                        <th>Side</th>
                                        <th>Price</th>
                                        <th>Time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="4" class="text-center">No recent trades</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- jQuery -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
        <!-- Bootstrap JS -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
        <!-- Chart.js -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
        
        <script>
        $(document).ready(function() {
            // Global variables
            let chart;
            let botRunning = false;
            let intervalId;
            const API_URL = 'api.php'; // Backend PHP endpoint
            
            // Initialize
            initializeChart();
            updateMarketData();
            checkBotStatus();
            
            // Event handlers
            $('#toggleBot').on('click', toggleBot);
            $('#symbolSelect, #intervalSelect').on('change', updateMarketData);
            $('#refreshBalance').on('click', loadAccountBalance);
            $('#settingsForm').on('submit', saveSettings);
            
            // Initialize Chart
            function initializeChart() {
                const ctx = document.getElementById('tradingChart').getContext('2d');
                chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Price',
                            data: [],
                            borderColor: 'rgb(75, 192, 192)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false
                            }
                        }
                    }
                });
            }
            
            // Load and update market data
            function updateMarketData() {
                const symbol = $('#symbolSelect').val();
                const interval = $('#intervalSelect').val();
                
                $.ajax({
                    url: `${API_URL}?action=analyze&symbol=${symbol}&interval=${interval}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updateChart(response.analysis);
                            updateIndicators(response.analysis);
                            updateSignal(response.signal);
                        } else {
                            showError('Failed to fetch market data');
                        }
                    },
                    error: function() {
                        showError('Failed to connect to API');
                    }
                });
            }
            
            // Update chart with new data
            function updateChart(analysis) {
                // For a real implementation, you would format the actual market data
                // This is a placeholder that would be replaced with real data
                const timestamps = Array.from({length: 50}, (_, i) => new Date(Date.now() - i * 3600000).toLocaleTimeString());
                const prices = Array.from({length: 50}, (_, i) => 40000 + Math.random() * 2000);
                
                chart.data.labels = timestamps.reverse();
                chart.data.datasets[0].data = prices.reverse();
                chart.update();
            }
            
            // Update technical indicators display
            function updateIndicators(analysis) {
                // Update EMA values
                $('#ema50').text(analysis.ema50.toFixed(2));
                $('#ema200').text(analysis.ema200.toFixed(2));
                
                // Update ADX
                $('#adx').text(analysis.adx.toFixed(2));
                
                // Update MACD
                $('#macd').text(analysis.macd.toFixed(6));
                
                // Update VWAP
                $('#vwap').text(analysis.vwap.toFixed(2));
                
                // Update Pivot
                $('#pivotLevel').text(analysis.pivotLevel.toFixed(2));
                
                // Update ATR
                $('#atr').text(analysis.atr.toFixed(2));
                
                // Update Price Pattern
                let patternText = '';
                if (analysis.higherHighs && analysis.higherLows) {
                    patternText = 'Uptrend';
                    $('#patternStatus').html('<span class="indicator indicator-green"></span>');
                } else if (analysis.lowerHighs && analysis.lowerLows) {
                    patternText = 'Downtrend';
                    $('#patternStatus').html('<span class="indicator indicator-red"></span>');
                } else {
                    patternText = 'Sideways';
                    $('#patternStatus').html('<span class="indicator indicator-yellow"></span>');
                }
                $('#pricePattern').text(patternText);
                
                // Update indicator status
                $('#ema50Status').html(analysis.ema50 > analysis.ema200 ?
                    '<span class="indicator indicator-green"></span>' :
                    '<span class="indicator indicator-red"></span>');
                    
                $('#adxStatus').html(analysis.adx > 25 ?
                    '<span class="indicator indicator-green"></span>' :
                    '<span class="indicator indicator-red"></span>');
                    
                $('#macdStatus').html(analysis.macd > analysis.macdSignal ?
                    '<span class="indicator indicator-green"></span>' :
                    '<span class="indicator indicator-red"></span>');
                    
                $('#vwapStatus').html(analysis.close > analysis.vwap ?
                    '<span class="indicator indicator-green"></span>' :
                    '<span class="indicator indicator-red"></span>');
                    
                $('#pivotStatus').html(analysis.close > analysis.pivotLevel ?
                    '<span class="indicator indicator-green"></span>' :
                    '<span class="indicator indicator-red"></span>');
                    
                $('#atrStatus').html(analysis.atr > $('#atrThreshold').val() ?
                    '<span class="indicator indicator-green"></span>' :
                    '<span class="indicator indicator-red"></span>');
            }
            
            // Update signal display
            function updateSignal(signal) {
                let alertClass = 'alert-secondary';
                let signalClass = 'signal-neutral';
                
                if (signal === 'BUY') {
                    alertClass = 'alert-success';
                    signalClass = 'signal-buy';
                } else if (signal === 'SELL') {
                    alertClass = 'alert-danger';
                    signalClass = 'signal-sell';
                }
                
                $('#signalAlert').removeClass('alert-success alert-danger alert-secondary').addClass(alertClass);
                $('#signalText').removeClass('signal-buy signal-sell signal-neutral').addClass(signalClass).text(`Signal: ${signal}`);
            }
            
            // Toggle bot status
            function toggleBot() {
                const action = botRunning ? 'stop' : 'start';
                
                $.ajax({
                    url: `${API_URL}?action=${action}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            botRunning = action === 'start';
                            updateBotStatusUI();
                            
                            if (botRunning) {
                                // Start automatic data refresh
                                intervalId = setInterval(refreshData, 30000); // Refresh every 30 seconds
                            } else {
                                // Stop automatic refresh
                                clearInterval(intervalId);
                            }
                        } else {
                            showError(`Failed to ${action} bot`);
                        }
                    },
                    error: function() {
                        showError('Failed to connect to API');
                    }
                });
            }
            
            // Check bot status on page load
            function checkBotStatus() {
                $.ajax({
                    url: `${API_URL}?action=status`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            botRunning = response.running;
                            updateBotStatusUI();
                            
                            if (botRunning) {
                                // Start automatic data refresh
                                intervalId = setInterval(refreshData, 30000); // Refresh every 30 seconds
                            }
                        }
                    }
                });
                
                // Load initial data
                loadAccountBalance();
                loadOpenPositions();
                loadTradeHistory();
            }
            
            // Update bot status UI
            function updateBotStatusUI() {
                if (botRunning) {
                    $('#botStatus').removeClass('bg-danger').addClass('bg-success').text('Running');
                    $('#toggleBot').removeClass('btn-success').addClass('btn-danger').text('Stop Bot');
                } else {
                    $('#botStatus').removeClass('bg-success').addClass('bg-danger').text('Stopped');
                    $('#toggleBot').removeClass('btn-danger').addClass('btn-success').text('Start Bot');
                }
            }
            
            // Refresh all data
            function refreshData() {
                updateMarketData();
                loadAccountBalance();
                loadOpenPositions();
                loadTradeHistory();
            }
            
            // Load account balance
            function loadAccountBalance() {
                $.ajax({
                    url: `${API_URL}?action=balance`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updateBalanceTable(response.balance);
                        }
                    }
                });
            }
            
            // Update balance table
            function updateBalanceTable(balances) {
                let tableHtml = '';
                
                for (const asset in balances) {
                    tableHtml += `
                    <tr>
                        <td>${asset}</td>
                        <td class="text-end">${balances[asset].available.toFixed(asset === 'USDT' ? 2 : 8)}</td>
                    </tr>
                    `;
                }
                
                $('#balanceTable').html(tableHtml);
            }
            
            // Load open positions
            function loadOpenPositions() {
                $.ajax({
                    url: `${API_URL}?action=positions`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updatePositionsTable(response.positions);
                        }
                    }
                });
            }
            
            // Update positions table
            function updatePositionsTable(positions) {
                let tableHtml = '';
                
                if (positions.length === 0) {
                    tableHtml = '<tr><td colspan="3" class="text-center">No open positions</td></tr>';
                } else {
                    positions.forEach(function(position) {
                        const pnlClass = position.unRealizedProfit >= 0 ? 'text-success' : 'text-danger';
                        
                        tableHtml += `
                        <tr>
                            <td>${position.symbol}</td>
                            <td>${position.positionAmt}</td>
                            <td class="${pnlClass}">${position.unRealizedProfit.toFixed(2)}</td>
                        </tr>
                        `;
                    });
                }
                
                $('#positionsTable tbody').html(tableHtml);
            }
            
            // Load trade history
            function loadTradeHistory() {
                $.ajax({
                    url: `${API_URL}?action=history`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            updateTradesTable(response.history);
                        }
                    }
                });
            }
            
            // Update trades table
            function updateTradesTable(trades) {
                let tableHtml = '';
                
                if (trades.length === 0) {
                    tableHtml = '<tr><td colspan="4" class="text-center">No recent trades</td></tr>';
                } else {
                    trades.forEach(function(trade) {
                        const side = trade.isBuyer ? 'BUY' : 'SELL';
                        const sideClass = trade.isBuyer ? 'text-success' : 'text-danger';
                        const time = new Date(trade.time).toLocaleString();
                        
                        tableHtml += `
                        <tr>
                            <td>${trade.symbol}</td>
                            <td class="${sideClass}">${side}</td>
                            <td>${parseFloat(trade.price).toFixed(2)}</td>
                            <td>${time}</td>
                        </tr>
                        `;
                    });
                }
                
                $('#tradesTable tbody').html(tableHtml);
            }
            
            // Save bot settings
            function saveSettings(e) {
                e.preventDefault();
                
                const settings = {
                    symbol: $('#tradingPair').val(),
                    interval: $('#tradingInterval').val(),
                    tradeAmount: parseFloat($('#tradeAmount').val()),
                    atrThreshold: parseFloat($('#atrThreshold').val())
                };
                
                $.ajax({
                    url: `${API_URL}?action=settings`,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(settings),
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            showSuccess('Settings saved successfully');
                            
                            // Update chart symbol and interval if needed
                            if ($('#symbolSelect').val() !== settings.symbol) {
                                $('#symbolSelect').val(settings.symbol);
                            }
                            
                            if ($('#intervalSelect').val() !== settings.interval) {
                                $('#intervalSelect').val(settings.interval);
                            }
                            
                            updateMarketData();
                        } else {
                            showError('Failed to save settings');
                        }
                    },
                    error: function() {
                        showError('Failed to connect to API');
                    }
                });
            }
            
            // Show error message
            function showError(message) {
                alert(`Error: ${message}`);
            }
            
            // Show success message
            function showSuccess(message) {
                alert(`Success: ${message}`);
            }
        });
        </script>
    </body>
    </html>
    api.php

    <?php
    // Binance Futures Trading Bot - Backend Implementation
    // This script handles the connection to Binance API and executes trading logic
    
    // Configuration
    define('API_KEY', 'YOUR_BINANCE_API_KEY');
    define('API_SECRET', 'YOUR_BINANCE_API_SECRET');
    define('SYMBOL', 'BTCUSDT'); // Default trading pair
    define('INTERVAL', '4h');    // Default timeframe
    define('QUANTITY', 0.001);   // Default trading quantity
    define('ATR_THRESHOLD', 50); // Default ATR threshold
    
    // Error reporting
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // Request handling
    header('Content-Type: application/json');
    session_start();
    
    // Router
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    
    switch ($action) {
        case 'start':
            startBot();
            break;
        case 'stop':
            stopBot();
            break;
        case 'status':
            getBotStatus();
            break;
        case 'settings':
            updateSettings();
            break;
        case 'balance':
            getAccountBalance();
            break;
        case 'positions':
            getOpenPositions();
            break;
        case 'history':
            getTradeHistory();
            break;
        case 'analyze':
            analyzeMarket();
            break;
        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    }
    
    function startBot() {
        // Set status in session
        $_SESSION['bot_running'] = true;
        $_SESSION['bot_start_time'] = time();
        
        echo json_encode([
            'status' => 'success',
            'message' => 'Bot started successfully',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
    function stopBot() {
        // Set status in session
        $_SESSION['bot_running'] = false;
        
        echo json_encode([
            'status' => 'success',
            'message' => 'Bot stopped successfully',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
    function getBotStatus() {
        $running = isset($_SESSION['bot_running']) ? $_SESSION['bot_running'] : false;
        $startTime = isset($_SESSION['bot_start_time']) ? $_SESSION['bot_start_time'] : null;
        
        echo json_encode([
            'status' => 'success',
            'running' => $running,
            'start_time' => $startTime ? date('Y-m-d H:i:s', $startTime) : null,
            'uptime' => $startTime ? (time() - $startTime) : 0
        ]);
    }
    
    function updateSettings() {
        // Get JSON data from request
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!$data) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid settings data']);
            return;
        }
        
        // Save settings to session
        $_SESSION['settings'] = $data;
        
        echo json_encode([
            'status' => 'success',
            'message' => 'Settings updated successfully',
            'settings' => $data
        ]);
    }
    
    function getAccountBalance() {
        // Connect to Binance API
        $balance = getBinanceAccountBalance();
        
        echo json_encode([
            'status' => 'success',
            'balance' => $balance
        ]);
    }
    
    function getOpenPositions() {
        // Connect to Binance API
        $positions = getBinanceOpenPositions();
        
        echo json_encode([
            'status' => 'success',
            'positions' => $positions
        ]);
    }
    
    function getTradeHistory() {
        // Connect to Binance API
        $history = getBinanceTradeHistory();
        
        echo json_encode([
            'status' => 'success',
            'history' => $history
        ]);
    }
    
    function analyzeMarket() {
        // Get parameters from request
        $symbol = isset($_GET['symbol']) ? $_GET['symbol'] : SYMBOL;
        $interval = isset($_GET['interval']) ? $_GET['interval'] : INTERVAL;
        
        // Fetch market data from Binance
        $marketData = getBinanceMarketData($symbol, $interval);
        
        // Apply technical indicators
        $analysis = calculateIndicators($marketData);
        
        // Determine buy/sell signals
        $signal = determineSignal($analysis);
        
        echo json_encode([
            'status' => 'success',
            'timestamp' => date('Y-m-d H:i:s'),
            'symbol' => $symbol,
            'interval' => $interval,
            'analysis' => $analysis,
            'signal' => $signal
        ]);
    }
    
    // Binance API Functions
    function getBinanceSignature($query_string) {
        return hash_hmac('sha256', $query_string, API_SECRET);
    }
    
    function binanceApiRequest($url, $method = 'GET', $params = []) {
        $curl = curl_init();
        
        // Add timestamp for API request
        $params['timestamp'] = round(microtime(true) * 1000);
        
        // Build query string
        $query_string = http_build_query($params);
        
        // Generate signature
        $signature = getBinanceSignature($query_string);
        
        // Add signature to params
        $query_string .= "&signature={$signature}";
        
        // Prepare URL
        $url = "https://fapi.binance.com/fapi/v1/{$url}?{$query_string}";
        
        // Set cURL options
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "X-MBX-APIKEY: " . API_KEY
            ],
        ]);
        
        $response = curl_exec($curl);
        $err = curl_error($curl);
        
        curl_close($curl);
        
        if ($err) {
            return ['error' => "cURL Error #:" . $err];
        } else {
            return json_decode($response, true);
        }
    }
    
    function getBinanceAccountBalance() {
        // In a real implementation, you would call Binance's account endpoint
        // This is a simplified example
        $response = binanceApiRequest("account", "GET");
        
        // For testing purposes
        if (!isset($response['assets'])) {
            return [
                'USDT' => ['available' => 1000.00, 'total' => 1200.00],
                'BTC' => ['available' => 0.05, 'total' => 0.05]
            ];
        }
        
        $balances = [];
        foreach ($response['assets'] as $asset) {
            $balances[$asset['asset']] = [
                'available' => floatval($asset['availableBalance']),
                'total' => floatval($asset['walletBalance'])
            ];
        }
        
        return $balances;
    }
    
    function getBinanceOpenPositions() {
        // In a real implementation, you would call Binance's positions endpoint
        // This is a simplified example
        $response = binanceApiRequest("positionRisk", "GET");
        
        // For testing purposes
        if (!isset($response[0])) {
            return [
                [
                    'symbol' => 'BTCUSDT',
                    'positionAmt' => 0.01,
                    'entryPrice' => 40000,
                    'markPrice' => 41000,
                    'unRealizedProfit' => 10,
                    'liquidationPrice' => 35000
                ]
            ];
        }
        
        $positions = [];
        foreach ($response as $position) {
            if (floatval($position['positionAmt']) != 0) {
                $positions[] = [
                    'symbol' => $position['symbol'],
                    'positionAmt' => floatval($position['positionAmt']),
                    'entryPrice' => floatval($position['entryPrice']),
                    'markPrice' => floatval($position['markPrice']),
                    'unRealizedProfit' => floatval($position['unRealizedProfit']),
                    'liquidationPrice' => floatval($position['liquidationPrice'])
                ];
            }
        }
        
        return $positions;
    }
    
    function getBinanceTradeHistory() {
        // In a real implementation, you would call Binance's trade history endpoint
        // This is a simplified example
        $response = binanceApiRequest("userTrades", "GET", ['symbol' => SYMBOL]);
        
        // For testing purposes
        if (!isset($response[0])) {
            return [
                [
                    'symbol' => 'BTCUSDT',
                    'id' => 123456,
                    'orderId' => 987654,
                    'price' => 40000,
                    'qty' => 0.01,
                    'quoteQty' => 400,
                    'time' => time() - 3600,
                    'isBuyer' => true
                ],
                [
                    'symbol' => 'BTCUSDT',
                    'id' => 123457,
                    'orderId' => 987655,
                    'price' => 41000,
                    'qty' => 0.01,
                    'quoteQty' => 410,
                    'time' => time() - 1800,
                    'isBuyer' => false
                ]
            ];
        }
        
        return $response;
    }
    
    function getBinanceMarketData($symbol, $interval) {
        // Endpoint for candlestick data
        $url = "https://fapi.binance.com/fapi/v1/klines?symbol={$symbol}&interval={$interval}&limit=500";
        
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
        ]);
        
        $response = curl_exec($curl);
        $err = curl_error($curl);
        
        curl_close($curl);
        
        if ($err) {
            return ['error' => "cURL Error #:" . $err];
        }
        
        $data = json_decode($response, true);
        $formattedData = [];
        
        foreach ($data as $candle) {
            $formattedData[] = [
                'timestamp' => $candle[0],
                'open' => floatval($candle[1]),
                'high' => floatval($candle[2]),
                'low' => floatval($candle[3]),
                'close' => floatval($candle[4]),
                'volume' => floatval($candle[5]),
                'close_time' => $candle[6],
                'quote_asset_volume' => floatval($candle[7]),
                'number_of_trades' => $candle[8],
                'taker_buy_base_asset_volume' => floatval($candle[9]),
                'taker_buy_quote_asset_volume' => floatval($candle[10])
            ];
        }
        
        return $formattedData;
    }
    
    // Technical analysis functions
    function calculateIndicators($marketData) {
        $closes = array_column($marketData, 'close');
        $highs = array_column($marketData, 'high');
        $lows = array_column($marketData, 'low');
        
        // EMA calculations
        $ema50 = calculateEMA($closes, 50);
        $ema200 = calculateEMA($closes, 200);
        
        // ADX calculation
        $adx = calculateADX($highs, $lows, $closes, 14);
        
        // MACD calculation
        $macd = calculateMACD($closes);
        
        // VWAP calculation
        $volumes = array_column($marketData, 'volume');
        $vwap = calculateVWAP($marketData);
        
        // Pivot Points
        $pivotLevel = calculatePivotPoint($marketData);
        
        // ATR calculation
        $atr = calculateATR($highs, $lows, $closes, 14);
        
        // Higher Highs, Higher Lows, Lower Highs, Lower Lows
        $patterns = identifyPricePatterns($highs, $lows, 5);
        
        $lastClose = end($closes);
        
        return [
            'ema50' => end($ema50),
            'ema200' => end($ema200),
            'adx' => end($adx),
            'macd' => end($macd['macd']),
            'macdSignal' => end($macd['signal']),
            'vwap' => end($vwap),
            'pivotLevel' => $pivotLevel,
            'atr' => end($atr),
            'higherHighs' => $patterns['higherHighs'],
            'higherLows' => $patterns['higherLows'],
            'lowerHighs' => $patterns['lowerHighs'],
            'lowerLows' => $patterns['lowerLows'],
            'close' => $lastClose
        ];
    }
    
    function calculateEMA($prices, $period) {
        $multiplier = 2 / ($period + 1);
        $ema = [];
        
        // Use SMA for the first value
        $sma = array_sum(array_slice($prices, 0, $period)) / $period;
        $ema[] = $sma;
        
        // Calculate EMA for remaining prices
        for ($i = $period; $i < count($prices); $i++) {
            $ema[] = ($prices[$i] - end($ema)) * $multiplier + end($ema);
        }
        
        return $ema;
    }
    
    function calculateADX($high, $low, $close, $period) {
        // This is a simplified ADX calculation
        // In a real implementation, you would need a more accurate calculation
        $adx = [];
        for ($i = $period; $i < count($close); $i++) {
            // Simplified calculation
            $adx[] = 25 + (rand(-5, 5)); // Random value around 25 for testing
        }
        return $adx;
    }
    
    function calculateMACD($prices, $fastPeriod = 12, $slowPeriod = 26, $signalPeriod = 9) {
        $fastEMA = calculateEMA($prices, $fastPeriod);
        $slowEMA = calculateEMA($prices, $slowPeriod);
        
        // Calculate MACD line
        $macdLine = [];
        for ($i = 0; $i < count($slowEMA); $i++) {
            $macdLine[] = $fastEMA[$i + (count($fastEMA) - count($slowEMA))] - $slowEMA[$i];
        }
        
        // Calculate Signal line (EMA of MACD line)
        $signalLine = calculateEMA($macdLine, $signalPeriod);
        
        // Calculate Histogram
        $histogram = [];
        for ($i = 0; $i < count($signalLine); $i++) {
            $histogram[] = $macdLine[$i + (count($macdLine) - count($signalLine))] - $signalLine[$i];
        }
        
        return [
            'macd' => $macdLine,
            'signal' => $signalLine,
            'histogram' => $histogram
        ];
    }
    
    function calculateVWAP($marketData) {
        $vwap = [];
        $cumulativeTPV = 0; // Total Price * Volume
        $cumulativeVolume = 0;
        
        foreach ($marketData as $candle) {
            $typicalPrice = ($candle['high'] + $candle['low'] + $candle['close']) / 3;
            $volume = $candle['volume'];
            
            $cumulativeTPV += $typicalPrice * $volume;
            $cumulativeVolume += $volume;
            
            $vwap[] = $cumulativeTPV / $cumulativeVolume;
        }
        
        return $vwap;
    }
    
    function calculatePivotPoint($marketData) {
        // Using the last complete day for calculation
        $lastDay = end($marketData);
        $high = $lastDay['high'];
        $low = $lastDay['low'];
        $close = $lastDay['close'];
        
        // Classical pivot point
        $pivot = ($high + $low + $close) / 3;
        
        return $pivot;
    }
    
    function calculateATR($highs, $lows, $closes, $period) {
        $trueRanges = [];
        $atr = [];
        
        // Calculate True Range for the first period
        for ($i = 1; $i < count($closes); $i++) {
            $highLowRange = $highs[$i] - $lows[$i];
            $highClosePrevRange = abs($highs[$i] - $closes[$i - 1]);
            $lowClosePrevRange = abs($lows[$i] - $closes[$i - 1]);
            
            $trueRanges[] = max($highLowRange, $highClosePrevRange, $lowClosePrevRange);
        }
        
        // First ATR value is simple average
        $firstATR = array_sum(array_slice($trueRanges, 0, $period)) / $period;
        $atr[] = $firstATR;
        
        // Calculate remaining ATR values
        for ($i = 1; $i < count($trueRanges) - $period + 1; $i++) {
            $atr[] = (($atr[$i - 1] * ($period - 1)) + $trueRanges[$i + $period - 1]) / $period;
        }
        
        return $atr;
    }
    
    function identifyPricePatterns($highs, $lows, $lookback) {
        $recentHighs = array_slice($highs, -$lookback);
        $recentLows = array_slice($lows, -$lookback);
        
        $higherHighs = true;
        $higherLows = true;
        $lowerHighs = true;
        $lowerLows = true;
        
        // Check for higher highs and higher lows (uptrend)
        for ($i = 1; $i < count($recentHighs); $i++) {
            if ($recentHighs[$i] <= $recentHighs[$i - 1]) {
                $higherHighs = false;
            }
            if ($recentLows[$i] <= $recentLows[$i - 1]) {
                $higherLows = false;
            }
        }
        
        // Check for lower highs and lower lows (downtrend)
        for ($i = 1; $i < count($recentHighs); $i++) {
            if ($recentHighs[$i] >= $recentHighs[$i - 1]) {
                $lowerHighs = false;
            }
            if ($recentLows[$i] >= $recentLows[$i - 1]) {
                $lowerLows = false;
            }
        }
        
        return [
            'higherHighs' => $higherHighs,
            'higherLows' => $higherLows,
            'lowerHighs' => $lowerHighs,
            'lowerLows' => $lowerLows
        ];
    }
    
    function determineSignal($analysis) {
        // Buy signal conditions
        $buyConditions =
            $analysis['ema50'] > $analysis['ema200'] &&
            $analysis['adx'] > 25 &&
            $analysis['macd'] > $analysis['macdSignal'] &&
            $analysis['close'] > $analysis['vwap'] &&
            $analysis['close'] > $analysis['pivotLevel'] &&
            $analysis['atr'] > getATRThreshold() &&
            $analysis['higherHighs'] &&
            $analysis['higherLows'];
        
        // Sell signal conditions
        $sellConditions =
            $analysis['ema50'] < $analysis['ema200'] &&
            $analysis['adx'] > 25 &&
            $analysis['macd'] < $analysis['macdSignal'] &&
            $analysis['close'] < $analysis['vwap'] &&
            $analysis['close'] < $analysis['pivotLevel'] &&
            $analysis['atr'] > getATRThreshold() &&
            $analysis['lowerHighs'] &&
            $analysis['lowerLows'];
        
        if ($buyConditions) {
            return 'BUY';
        } elseif ($sellConditions) {
            return 'SELL';
        } else {
            return 'NEUTRAL';
        }
    }
    
    function getATRThreshold() {
        // Get from settings or use default
        return isset($_SESSION['settings']['atrThreshold']) ? $_SESSION['settings']['atrThreshold'] : ATR_THRESHOLD;
    }
    
    // Place market order (simplified example)
    function placeBinanceOrder($symbol, $side, $quantity) {
        $params = [
            'symbol' => $symbol,
            'side' => $side, // BUY or SELL
            'type' => 'MARKET',
            'quantity' => $quantity
        ];
        
        return binanceApiRequest("order", "POST", $params);
    }
    Testnet testi yapılmadı dikkatli kullanın.. sağlıklı veri 4h 12h olur genelde scalping için uygun değildir.
    Teşekkür ederim