$api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_USERAGENT => 'FlatlogicMarketDetector/1.0' ]); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($http_code !== 200) { error_log("CoinGecko API request failed with HTTP code {$http_code}: {$response}"); return null; } $data = json_decode($response, true); if (isset($data['error'])) { error_log("CoinGecko API error: " . $data['error']); return null; } return $data; } // --- Database Logging --- function log_candlestick_data($pdo, $symbol, $exchange, $interval, $kline) { $sql = <<prepare($sql); $stmt->execute([ ':symbol' => $symbol, ':exchange' => $exchange, ':interval_time' => $interval, ':open_time' => $kline[0], ':open_price' => $kline[1], ':high_price' => $kline[2], ':low_price' => $kline[3], ':close_price' => $kline[4], ]); } // --- Main Execution --- $latest_tickers = []; try { $pdo = db(); foreach ($symbols as $symbol) { $klines = fetch_candlestick_data($symbol, $interval); if (empty($klines) || !is_array($klines)) { continue; // Skip this symbol if data fetching fails } foreach ($klines as $kline) { log_candlestick_data($pdo, $symbol, $exchange, $interval, $kline); } // For the frontend, provide the most recent ticker data $latest_kline = end($klines); $latest_tickers[] = [ 'exchange' => $exchange, 'symbol' => strtoupper($symbol), 'price' => $latest_kline[4], // Close price 'change_24h_percent' => 0, // Placeholder 'signal' => '-' ]; } } catch (Exception $e) { http_response_code(500); // Log error and exit gracefully error_log('Ticker script failed: ' . $e->getMessage()); echo json_encode(['error' => 'An internal error occurred.']); exit; } // --- Output for Frontend --- if (isset($_GET['symbol'])) { $symbol_to_find = strtoupper($_GET['symbol']); foreach ($latest_tickers as $ticker) { if ($ticker['symbol'] === $symbol_to_find) { echo json_encode($ticker); exit; } } // Fallback if the requested symbol wasn't processed echo json_encode(['error' => 'Data for symbol not found.']); } else { // If no symbol is specified, do not return anything for now. // The frontend will request each symbol individually. echo json_encode(['status' => 'OK', 'message' => 'Data processed.']); }