<?php
die();
error_reporting(E_ALL);
ini_set('display_errors', '1');
//ini_set("memory_limit", "-1");
//set_time_limit(55);
require_once 'functions.php';
$min = date('i');
do {
    $symbols = readJson('data/symbols.json');
    if (!$symbols) sleep(2);
    else
        break;
} while ($min == date('i'));

$files1 = scan_dir('data/trades');
foreach ($symbols as $key => $value) {
    if (!in_array($value . '.json', $files1)) {
        file_put_contents('data/trades/' . $value . '.json', '');
    }
}

$sec = date('s');
$min = date('i');
while ($min == date('i') || $sec < date('s')) {
    $files = scan_dir('data/trades');
    $list = [];
    $listUpdate = [];
    foreach ($files as $value) {
        $symbol = str_replace('.json', '', $value);
        if (!in_array($symbol, $symbols)) {
            unlink('data/trades/' . $value);
            continue;
        }
        $lastTrade = curl("https://api.coinex.com/v2/spot/deals?market=$symbol");
        if (json_decode($lastTrade)) {
            $list[$symbol] = $lastTrade;
            $listUpdate[$symbol] = time();
            file_put_contents('data/trades/' . $symbol . '.json', $lastTrade);
        }
        usleep(500000);
        if ($min != date('i'))
            break;
    }

}


function scan_dir($dir)
{
    $ignored = array('.', '..', '.svn', '.htaccess');
    $files = array();
    foreach (scandir($dir) as $file) {
        if (in_array($file, $ignored)) continue;
        $files[$file] = filemtime($dir . '/' . $file);
    }

    asort($files);
    $files = array_keys($files);

    return $files;
}



function readJson($path)
{
    if (!filesize($path))
        usleep(300000);

    if (!filesize($path))
        return [];

    $file = fopen($path, "r");
    $response = fread($file, filesize($path));
    fclose($file);

    return json_decode($response);
}