'Period must be a positive integer.']); exit; } function calculate_sma($symbol, $period) { $pdo = db(); // Fetch the last 'period' number of closing prices for the given symbol, most recent first. $stmt = $pdo->prepare( "SELECT close FROM candlestick_data WHERE symbol = :symbol ORDER BY timestamp DESC LIMIT :period" ); $stmt->bindParam(':symbol', $symbol, PDO::PARAM_STR); $stmt->bindParam(':period', $period, PDO::PARAM_INT); $stmt->execute(); $closes = $stmt->fetchAll(PDO::FETCH_COLUMN); if (count($closes) < $period) { return null; // Not enough data to calculate SMA } $sum = array_sum($closes); $sma = $sum / $period; return $sma; } $result = null; if (strtolower($indicator) === 'sma') { $result = calculate_sma($symbol, $period); } else { echo json_encode(['error' => 'Invalid indicator specified.']); exit; } $response = [ 'symbol' => $symbol, 'indicator' => 'SMA', 'period' => $period, 'value' => $result, 'timestamp' => time() ]; echo json_encode($response);