PNG IHDR x sBIT|d pHYs + tEXtSoftware www.inkscape.org< ,tEXtComment
<?php
// Turn off error output to screen
ini_set('display_errors', 0);
error_reporting(E_ALL);
session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');
header('Content-Type: application/json');
// 1. Check Authentication and CSRF Token
if (!isset($_SESSION['Email']) || !isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
echo json_encode(['status' => 'error', 'message' => 'Security token invalid or session expired.']);
exit();
}
$user = GetMember1($_SESSION['Email']);
if (!$user) {
echo json_encode(['status' => 'error', 'message' => 'User not found']);
exit();
}
$userId = $user['ID'];
$tradeId = isset($_POST['trade_id']) ? intval($_POST['trade_id']) : 0;
if ($tradeId <= 0) {
echo json_encode(['status' => 'error', 'message' => 'Invalid trade ID.']);
exit();
}
try {
// Start Transaction
$conn->begin_transaction();
// 2. Verify the trade exists, belongs to the user, and is still OPEN
$stmt = $conn->prepare("SELECT trade_amount, entry_price FROM trades WHERE id = ? AND user_id = ? AND status = 'OPEN' FOR UPDATE");
$stmt->bind_param("ii", $tradeId, $userId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
echo json_encode(['status' => 'error', 'message' => 'Trade not found or already closed.']);
$conn->rollback();
exit();
}
$trade = $result->fetch_assoc();
$stmt->close();
$tradeAmount = floatval($trade['trade_amount']);
// 3. SERVER-SIDE PNL CALCULATION
// Because we don't have a live daemon, we simulate realistic market movement
// biased by the user's signal strength (just like the frontend animation).
$signalStrength = isset($user['signal_strength']) ? intval($user['signal_strength']) : 50;
// Max 15% swing per trade based on signal strength
$volatility = ($signalStrength / 100) * 0.15;
// Generate a random multiplier between -1.0 and 1.0
$randomFactor = (mt_rand(-100, 100) / 100);
$pnlPercentage = $randomFactor * $volatility;
$finalPnl = $tradeAmount * $pnlPercentage;
// Safety check: User cannot lose more than they put into this specific trade
if ($finalPnl < -$tradeAmount) {
$finalPnl = -$tradeAmount;
}
$closePrice = floatval($trade['entry_price']) * (1 + $pnlPercentage);
$closedAt = date('Y-m-d H:i:s');
$status = 'CLOSED';
// 4. Update the Trades table
$updateTrade = $conn->prepare("UPDATE trades SET status = ?, close_price = ?, pnl = ?, closed_at = ? WHERE id = ?");
$updateTrade->bind_param("sddsi", $status, $closePrice, $finalPnl, $closedAt, $tradeId);
$updateTrade->execute();
$updateTrade->close();
// 5. Update User Balances
// The initial invested amount goes back into `Capital`.
// The profit/loss goes into `Profit`.
$userCapital = floatval($user['Capital']);
$userProfit = floatval($user['Profit']);
$newCapital = $userCapital + $tradeAmount; // Return the margin
$newProfit = $userProfit + $finalPnl; // Add/Subtract the PNL
$updateUser = $conn->prepare("UPDATE members SET Capital = ?, Profit = ? WHERE ID = ?");
$capStr = strval($newCapital);
$profStr = strval($newProfit);
$updateUser->bind_param("ssi", $capStr, $profStr, $userId);
$updateUser->execute();
$updateUser->close();
// Commit Transaction
$conn->commit();
// Format for nice display in SweetAlert
$pnlFormatted = ($finalPnl >= 0 ? '+' : '') . $user['sym'] . number_format($finalPnl, 2);
echo json_encode([
'status' => 'success',
'message' => 'Trade closed successfully. Final PNL: ' . $pnlFormatted
]);
} catch (Exception $e) {
$conn->rollback();
echo json_encode(['status' => 'error', 'message' => 'System error closing trade.']);
}
?>
b IDATxytVսϓ22 A@IR:hCiZ[v*E:WũZA ^dQeQ @ !jZ'>gsV仿$|?g)&x-E