'Nominal', 'symbol' => $symbol, 'change_percent' => 0, 'details' => 'No significant price change detected.' ]; try { $pdo = db(); // 1. Get the most recent price $stmt_latest = $pdo->prepare("SELECT price FROM price_history WHERE symbol = :symbol ORDER BY timestamp DESC LIMIT 1"); $stmt_latest->execute([':symbol' => $symbol]); $latest_price_row = $stmt_latest->fetch(PDO::FETCH_ASSOC); if (!$latest_price_row) { $response['details'] = 'No recent price data available for this symbol.'; echo json_encode($response); exit; } $latest_price = $latest_price_row['price']; // 2. Get the oldest price from the 30-minute window $stmt_oldest = $pdo->prepare( "SELECT price FROM price_history WHERE symbol = :symbol AND timestamp >= NOW() - INTERVAL :minutes MINUTE ORDER BY timestamp ASC LIMIT 1" ); $stmt_oldest->execute([':symbol' => $symbol, ':minutes' => $time_window_minutes]); $oldest_price_row = $stmt_oldest->fetch(PDO::FETCH_ASSOC); if (!$oldest_price_row) { $response['details'] = 'Not enough historical data in the last 30 minutes to calculate change.'; echo json_encode($response); exit; } $oldest_price = $oldest_price_row['price']; // 3. Calculate percentage change if ($oldest_price > 0) { $change_percent = (($latest_price - $oldest_price) / $oldest_price) * 100; $response['change_percent'] = round($change_percent, 2); } else { $change_percent = 0; } // 4. Determine status if ($change_percent <= $crash_threshold) { $response['status'] = 'Crash Alert'; $response['details'] = "Price dropped by " . $response['change_percent'] . "% in the last $time_window_minutes minutes."; } elseif ($change_percent >= $pump_threshold) { $response['status'] = 'Pump Alert'; $response['details'] = "Price surged by " . $response['change_percent'] . "% in the last $time_window_minutes minutes."; } else { $response['details'] = "Price change of " . $response['change_percent'] . "% is within normal limits."; } } catch (PDOException $e) { http_response_code(500); $response['status'] = 'Error'; $response['details'] = 'Database error: ' . $e->getMessage(); } echo json_encode($response);