<?php
$conn= mysqli_connect("localhost","tradebot_revotech","revotech@123","tradebot_revotech");
 
 $pairs=mysqli_query($conn,"select * from tradepair_list where status='1'");
 
 $pair=array();
 while($pairz=mysqli_fetch_array($pairs))
 {
     $pair[]=$pairz['pair_name'].'USDT';
     
     
 }
 
 
 function fetchBinanceCandlestickData($pair, $interval = '1m') {
    $baseUrl = 'https://api.binance.com/api/v3/klines';
    $url = $baseUrl . '?symbol=' . strtoupper($pair) . '&interval=' . $interval.'&limit=1';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'cURL error: ' . curl_error($ch) . "\n";
        curl_close($ch);
        return [];
    }

    curl_close($ch);

    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo 'JSON decode error: ' . json_last_error_msg() . "\n";
        return [];
    }

    // Extract the most recent candlestick data
    $candlesticks = [];
    foreach ($data as $candle) {
        $openPrice = $candle[1];
        $closePrice = $candle[4];
        $highPrice = $candle[2];
        $lowPrice = $candle[3];
        $timestamp = $candle[0];
        
        // Calculate the percentage change
        $priceChangePercentage = $openPrice != 0 ? (($closePrice - $openPrice) / $openPrice) * 100 : 0;
        $priceChangePercentage = number_format($priceChangePercentage,4);
        $candlesticks = [
            'symbol' => $pair,
            'openPrice' => $openPrice,
            'closePrice' => $closePrice,
            'highPrice' => $highPrice,
            'lastPrice' => $closePrice,
            'priceChangePercentage' => $priceChangePercentage,
           
        ];
    }

    return $candlesticks;

    
}

// Example usage

$interval = '1m'; // Time interval for candlesticks (e.g., '1m', '5m', '1h', '1d')
$candlestickData = [];

foreach ($pair as $pair) {
    $candlestickData[] = fetchBinanceCandlestickData($pair, $interval);
}

 file_put_contents('trading_pairs.json', json_encode($candlestickData, JSON_PRETTY_PRINT));

?>
