<?php
require_once 'functionsT.php';
error_reporting(E_ALL);
ini_set('display_errors', '1');
// یک بار کانکشن ایجاد می‌کنیم
$globalCurl = curl_init();

// ثبت تابع shutdown برای بستن کانکشن حتی در صورت خطا
register_shutdown_function(function () {
    global $globalCurl;
    if (is_resource($globalCurl)) {
        curl_close($globalCurl);
        // echo "Connection closed safely.\n"; // فقط برای دیباگ
    }
});

// اجرای سفارش
//$res = sendOrder('ADAUSDT', 'SPOT', 'buy', 'limit', 5, 0.5, 'ShockStoch', false);
//print_r($res);

// لغو سفارش
//print_r(cancelOrder(152179737425, 'ADAUSDT'));
//$coinex = [];
//$coinex['QKCUSDT'] = coinexorderbook("transactions", 'QKCUSDT');
//print_r($coinex['QKCUSDT']->created_at);
$def = [];
$coinexPath = 'data/CoinexOrderBook/' . (time() - 1) . '.json';//end($files2);
$coinex = readJson($coinexPath);
$BinPath = '../nobitex/data/binancePrices/' . (time() - 1) . '.json';//end($files2);
$binance = readJson($BinPath);
$symbolsPath = 'data/symbols.json';//end($files2);
$symbols = readJson($symbolsPath);
$Binind = 'data/BinanceIndicators.json';//end($files2);
$Binind = readJson($Binind);
//print_r($symbols);
$def_bin_last = $def_ask_bid = $def_bin_ask = $def_bin_bid = [];
$atrsum = $count1 = 0;

$Binind = json_decode(json_encode($Binind), true);

// حذف کلید زمان
unset($Binind['time']);

// مرتب‌سازی بر اساس ATR
uasort($Binind, function($a, $b) {
    return $b['ATR'] <=> $a['ATR']; // برای ترتیب نزولی
});
$Binind = array_values($Binind);

for($i = 4; $i < count($Binind)-5; $i++) {
        $atrsum += $Binind[$i]['ATR'];
//        echo $Binind[$i]['ATR']/$Binind[$i]['LastClose'].'<br/>';
        $count1++;
}
$atrsum = $atrsum / $count1;
echo 'ATR avg : ' . $atrsum . '</br>';
if ($coinex) { //isset($coinex->BTCUSDT)
    foreach ($coinex as $sym => $val) {
        if (
            in_array($sym, $symbols) && // اینجا باید $sym چک شود، چون $val کل آبجکت مربوط به symbol است
            isset($val->depth->asks[0][0], $val->depth->bids[0][0]) &&
            $val->depth->asks[0][0] > 0 &&
            $val->depth->bids[0][0] > 0
        ) {
//            $def[] = $binance->$sym / $val->depth->last;
            $def1 = $binance->$sym - $val->depth->last;
            $def_bin_last[] = $def1 * 100 / $binance->$sym;
            $def1 = $binance->$sym - $val->depth->asks[0][0];
            $def_bin_ask[] = $def1 * 100 / $binance->$sym;
            $def1 = $binance->$sym - $val->depth->bids[0][0];
            $def_bin_bid[] = $def1 * 100 / $binance->$sym;
            $def1 = $val->depth->asks[0][0] - $val->depth->bids[0][0];
            $def_ask_bid[] = $def1 * 100 / $val->depth->asks[0][0];

        }
//        echo $sym . "\n"; // برای تست، چاپ نام نماد
    }
    $sum_bin_last = $sum_bin_ask = $sum_bin_bid = $sum_ask_bid = $count = 0;
    usort($def_bin_ask, function ($a, $b) {
        return $a <=> $b;
    });
    usort($def_bin_bid, function ($a, $b) {
        return $a <=> $b;
    });
    usort($def_bin_last, function ($a, $b) {
        return $a <=> $b;
    });
    usort($def_ask_bid, function ($a, $b) {
        return $a <=> $b;
    });

    for ($i = 5; $i < count($def_bin_last) - 6; $i++) {
        $sum_bin_last += $def_bin_last[$i];
        $sum_bin_ask += $def_bin_ask[$i];
        $sum_bin_bid += $def_bin_bid[$i];
        $sum_ask_bid += $def_ask_bid[$i];
        $count++;
    }
    echo '$sum_bin_ask : ' . $sum_bin_ask / $count . '</br>';
    echo '$sum_bin_last : ' . $sum_bin_last / $count . '</br>';
    echo '$sum_bin_bid : ' . $sum_bin_bid / $count . '</br></br>';
    echo '$sum_ask_bid : ' . $sum_ask_bid / $count . '</br>';

}


//echo '<pre>' . print_r($def, true) . '</pre>';

// -------------------- توابع --------------------

function readJson($path)
{
    if (!file_exists($path)) {
        usleep(300000);
        if (!file_exists($path)) {
            return [];
        }
    }
    $fileSize = filesize($path);
    if ($fileSize === 0) return [];

    $file = fopen($path, "r");
    if (!$file) return [];

    $response = fread($file, $fileSize);
    fclose($file);
    return json_decode($response) ?: [];
}


function sendOrder($market, $marketType, $side, $type, $amount, $price, $client_id, $isHide = false)
{
    $data = json_encode([
        'market' => $market,
        'market_type' => $marketType,
        'side' => $side,
        'type' => $type,
        'amount' => $amount,
        'price' => $price,
        'client_id' => $client_id,
        'is_hide' => (bool)$isHide,
        'stp_mode' => 'both'
    ]);

    return coinexCurl('/v2/spot/order', 'POST', $data);
}

function cancelOrder($id, $market)
{
    $data = json_encode([
        'order_id' => $id,
        'market' => $market,
        'market_type' => 'SPOT'
    ]);

    return coinexCurl('/v2/spot/cancel-order', 'POST', $data);
}

function coinexCurl($request_path, $method = 'GET', $data = '')
{
    global $AccessID, $SecretKey, $globalCurl;

    $url = 'https://api.coinex.com' . $request_path;
    $timestamp = round(microtime(true) * 1000);

    $signatureData = $method . $request_path . $data . $timestamp;
    $signed_str = strtolower(hash_hmac('sha256', $signatureData, $SecretKey));

    $headers = [
        'Accept: application/json',
        'Content-Type: application/json',
        'X-COINEX-KEY: ' . $AccessID,
        'X-COINEX-SIGN: ' . $signed_str,
        'X-COINEX-TIMESTAMP: ' . $timestamp
    ];

    curl_setopt($globalCurl, CURLOPT_URL, $url);
    curl_setopt($globalCurl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($globalCurl, CURLOPT_HTTPHEADER, $headers);

    if ($method === 'POST') {
        curl_setopt($globalCurl, CURLOPT_POST, true);
        curl_setopt($globalCurl, CURLOPT_POSTFIELDS, $data);
    } else {
        curl_setopt($globalCurl, CURLOPT_POST, false);
        curl_setopt($globalCurl, CURLOPT_POSTFIELDS, null);
    }

    $response = curl_exec($globalCurl);

    if ($response === false) {
        return ['error' => curl_error($globalCurl)];
    }

    $decoded_response = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'error' => 'Invalid JSON response: ' . json_last_error_msg(),
            'raw_response' => $response
        ];
    }

    return $decoded_response;
}


function coinexorderbook($type, $symbol)
{
    $url = "http://93.127.180.241:8080/api/data?type=$type&symbol=$symbol";
    $response = file_get_contents($url);

    if ($response !== false) {
        $response = json_decode($response);
        if ($type == 'orderbooks')
            return $response->data->depth;
        else
            return $response->data->deal_list[0];

    } else {
        return false;
    }

}