$api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_HTTPHEADER => [ 'Accept: application/json' ], // It's good practice to set a user-agent CURLOPT_USERAGENT => 'FlatlogicMarketDetector/1.0' ]); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); // --- Response Handling --- if ($error) { http_response_code(500); echo json_encode(['error' => 'cURL Error: ' . $error]); exit; } if ($http_code !== 200) { http_response_code($http_code); echo json_encode(['error' => 'Bitget API returned non-200 status', 'details' => json_decode($response)]); exit; } $data = json_decode($response, true); // --- Data Validation & Output --- if (json_last_error() !== JSON_ERROR_NONE || empty($data['data'])) { http_response_code(500); echo json_encode(['error' => 'Failed to parse JSON response or data is empty']); exit; } // Extract the first ticker object from the response data array $ticker_data = $data['data'][0] ?? null; if (!$ticker_data) { http_response_code(404); echo json_encode(['error' => 'Ticker data for symbol not found in API response']); exit; } // --- Log to Database --- try { require_once __DIR__ . '/../db/config.php'; $price_to_log = $ticker_data['lastPr'] ?? null; if ($price_to_log) { $pdo = db(); $stmt = $pdo->prepare( "INSERT INTO price_history (symbol, price) VALUES (:symbol, :price)" ); $stmt->execute(['symbol' => $symbol, 'price' => $price_to_log]); } } catch (Exception $e) { // If DB fails, log error but don't crash the API endpoint error_log('DB logging failed in ticker.php: ' . $e->getMessage()); } // --- Sanitize and Structure Output --- // We select and sanitize the fields we want to send to the frontend. $output = [ 'exchange' => 'Bitget', 'symbol' => $ticker_data['symbol'] ?? 'N/A', 'price' => $ticker_data['lastPr'] ?? '0.00', // Bitget provides the 24h change as a decimal, e.g., 0.025 for +2.5% 'change_24h_percent' => isset($ticker_data['priceChangePercent']) ? (float)$ticker_data['priceChangePercent'] * 100 : 0, 'signal' => '-' // Placeholder for future signal detection ]; echo json_encode($output);