For rsi calculation in php and database .
// Step 1: Store Data in Database
store 16 close data in database
// Step 2: Fetch Data from Database
$sqlrsi = "SELECT close FROM $cand ORDER BY id ASC LIMIT 16";
$rdata = $connection->query($sqlrsi);
$closePrices = [];
while($rowrsi = $rdata->fetch_assoc()) {
$closePrices[] = $rowrsi["close"];
}
// Step 3: Calculate RSI for 14-Period
function calculate_rsi($closePrices, $period = 14) {
$deltas = [];
for ($i = 1; $i < count($closePrices); $i++) {
$deltas[] = $closePrices[$i] - $closePrices[$i - 1];
}
$seed = array_slice($deltas, 0, $period);
$up = 0;
$down = 0;
foreach ($seed as $delta) {
if ($delta >= 0) {
$up += $delta;
} else {
$down += abs($delta);
}
}
$up /= $period;
$down /= $period;
$rs = $up / $down;
$rsi = [100 - 100 / (1 + $rs)];
for ($i = $period; $i < count($closePrices) - 1; $i++) {
$delta = $deltas[$i - 1];
if ($delta > 0) {
$upval = $delta;
$downval = 0;
} else {
$upval = 0;
$downval = abs($delta);
}
$up = ($up * ($period - 1) + $upval) / $period;
$down = ($down * ($period - 1) + $downval) / $period;
$rs = $up / $down;
$rsi[] = 100 - 100 / (1 + $rs);
}
return $rsi;
}
$rsi0 = calculate_rsi($closePrices, 14);
// Output the RSI values
//echo "RSI values: ";
//print_r($rsi);
$rsi = $rsi0["1"];
echo " rsi ". $rsi;