38350-vm/api/place_order.php
2026-02-11 08:19:17 +00:00

64 lines
2.0 KiB
PHP

<?php
session_start();
require_once '../db/config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'error' => 'Unauthorized']);
exit;
}
$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
echo json_encode(['success' => false, 'error' => 'Invalid data']);
exit;
}
$symbol = $data['symbol'];
$type = $data['type']; // spot or futures
$side = $data['side']; // buy or sell
$order_type = $data['order_type']; // limit or market
$price = $data['price'];
$amount = $data['amount'];
$total = $data['total'];
$leverage = $data['leverage'] ?? 1;
$tp_price = $data['tp_price'] ?? null;
$sl_price = $data['sl_price'] ?? null;
try {
$db = db();
$db->beginTransaction();
// Check balance if buying spot or opening long/short futures (simplified)
$stmt = $db->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
$stmt->execute([$user_id]);
$user = $stmt->fetch();
if ($side === 'buy' || $type === 'futures') {
$cost = $type === 'futures' ? $total / $leverage : $total;
if ($user['balance'] < $cost) {
$db->rollBack();
echo json_encode(['success' => false, 'error' => 'Insufficient balance']);
exit;
}
// Deduct balance
$stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
$stmt->execute([$cost, $user_id]);
}
// Insert order
$stmt = $db->prepare("INSERT INTO trading_orders (user_id, symbol, type, side, order_type, price, amount, total, leverage, tp_price, sl_price) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$user_id, $symbol, $type, $side, $order_type, $price, $amount, $total, $leverage, $tp_price, $sl_price]);
$db->commit();
echo json_encode(['success' => true]);
} catch (Exception $e) {
if (isset($db)) $db->rollBack();
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}