38239-vm/api.php
2026-02-07 05:53:52 +00:00

92 lines
3.0 KiB
PHP

<?php
include_once 'config.php';
$action = $_GET['action'] ?? '';
if ($action === 'market_data') {
// In a real app, this would fetch from Binance or a cache.
// For now, we'll fetch from our cryptocurrencies table and mix with some dummy data for variety.
$stmt = db()->query("SELECT * FROM cryptocurrencies WHERE is_active = 1");
$coins = $stmt->fetchAll();
foreach ($coins as &$coin) {
// Simple mock: fluctuate price slightly
$variation = (mt_rand(-100, 100) / 10000); // +/- 1%
$coin['price'] = (float)$coin['current_price'] * (1 + $variation);
$coin['change'] = (float)$coin['change_24h'];
}
header('Content-Type: application/json');
echo json_encode($coins);
exit;
}
if ($action === 'submit_order') {
check_auth();
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
exit;
}
$user_id = $_SESSION['user_id'];
$account = get_account($user_id);
$symbol = $data['symbol'] ?? 'BTCUSDT';
$side = $data['side'] ?? 'BUY';
$trade_type = $data['trade_type'] ?? 'SPOT';
$order_type = $data['order_type'] ?? 'LIMIT';
$price = $data['price'] ?? null;
$amount = (float)($data['amount'] ?? 0);
$leverage = (int)($data['leverage'] ?? 1);
// Basic validation
if ($amount <= 0) {
echo json_encode(['status' => 'error', 'message' => 'Invalid amount']);
exit;
}
// Logic for SPOT / CONTRACT balance checks
// This is a simplified version
$total_cost = 0;
if ($trade_type === 'SPOT') {
if ($side === 'BUY') {
$exec_price = $price ?: 50000; // Mock price if market
$total_cost = $amount * $exec_price;
if ($account['balance'] < $total_cost) {
echo json_encode(['status' => 'error', 'message' => '余额不足']);
exit;
}
}
} else {
// Contract logic
$total_cost = ($amount * 100) / $leverage;
if ($account['balance'] < $total_cost) {
echo json_encode(['status' => 'error', 'message' => '保证金不足']);
exit;
}
}
try {
$db = db();
$db->beginTransaction();
// Deduct balance
$stmt = $db->prepare("UPDATE accounts SET balance = balance - ? WHERE id = ?");
$stmt->execute([$total_cost, $account['id']]);
// Insert order
$stmt = $db->prepare("INSERT INTO orders (account_id, symbol, trade_type, side, order_type, price, amount, leverage, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')");
$stmt->execute([$account['id'], $symbol, $trade_type, $side, $order_type, $price, $amount, $leverage]);
$db->commit();
echo json_encode(['status' => 'success']);
} catch (Exception $e) {
$db->rollBack();
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
exit;
}
?>