$api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_USERAGENT => 'FlatlogicMarketDetector/1.0' ]); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); } // --- 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], ':volume' => $kline[5], ':close_time' => $kline[6], ':quote_asset_volume' => $kline[7], ':number_of_trades' => $kline[8], ':taker_buy_base_asset_volume' => $kline[9], ':taker_buy_quote_asset_volume' => $kline[10], ]); } // --- 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' => $symbol, 'price' => $latest_kline[4], // Close price 'change_24h_percent' => 0, // Placeholder, as kline API doesn't provide this directly '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 --- // This part is for the main dashboard display, not the alerts API. 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.']); }