35761-vm/api/analysis.php
Flatlogic Bot ffa84da26a V.1.14
2025-11-15 10:49:49 +00:00

62 lines
1.5 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
// --- Parameters ---
// Example: /api/analysis.php?symbol=BTCUSDT&indicator=sma&period=20
$symbol = $_GET['symbol'] ?? 'BTCUSDT';
$indicator = $_GET['indicator'] ?? 'sma';
$period = (int)($_GET['period'] ?? 20);
if ($period <= 0) {
echo json_encode(['error' => '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);