<?php 

error_reporting(E_ALL);
ini_set('display_errors', 1);

function getCandles($coin, $period) {
    $url = "https://api.binance.com/api/v3/klines?symbol={$coin}&interval={$period}&limit=200";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);

    if ($response === false) {
        echo "cURL Hatası: " . curl_error($ch);
        curl_close($ch);
        return [];
    }

    curl_close($ch);

    $decoded = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "JSON Decode Hatası: " . json_last_error_msg();
        return [];
    }

    return $decoded;
}

function calculateBBWidth($closes, $period = 20) {
    $subset = array_slice($closes, -$period);
    if (count($subset) < $period) return null;
    $sma = array_sum($subset) / $period;
    $std_dev = 0;
    foreach ($subset as $close) {
        $std_dev += pow($close - $sma, 2);
    }
    $std_dev = sqrt($std_dev / $period);
    $upper_band = $sma + 2 * $std_dev;
    $lower_band = $sma - 2 * $std_dev;
    $width = ($upper_band - $lower_band) / $sma * 100;
    return $width;
}

function calculateRSI($closes, $period = 14) {
    $len = count($closes);
    if ($len < $period + 1) return null;
    $gains = $losses = 0;
    for ($i = $len - $period - 1; $i < $len - 1; $i++) {
        $delta = $closes[$i + 1] - $closes[$i];
        if ($delta > 0) {
            $gains += $delta;
        } else {
            $losses -= $delta;
        }
    }
    if ($losses == 0) return 100;
    $rs = $gains / $losses;
    return 100 - (100 / (1 + $rs));
}

function calculateVolumeAverage($candles, $period = 20) {
    $subset = array_slice($candles, -$period);
    if (count($subset) < $period) return null;
    $sum = 0;
    foreach ($subset as $candle) {
        $sum += (float)$candle[5];
    }
    return $sum / $period;
}
 
$coin = $_GET['coin'];
$period = $_GET['period'];

$mumlar = getCandles($coin, $period);

$closes = array_map(function($c) {
    return (float)$c[4];
}, $mumlar);
$last_close = $closes[count($closes) - 1];
$previous_close = $closes[count($closes) - 2];
$volume_current = (float)$mumlar[count($mumlar) - 1][5];
$volume_avg_20 = calculateVolumeAverage($mumlar, 20);
$BB_width = calculateBBWidth($closes, 20);
$RSI = calculateRSI($closes, 14);

if ($BB_width !== null && $volume_avg_20 !== null && $RSI !== null) {
    if ($BB_width < 15 && $volume_current > 3.5 * $volume_avg_20 && $RSI < 5) {
        echo "1";
    } else {
        echo "0";
    }
} else {
    echo "null";
}

?>
