<?php

// Replace with your Bybit API credentials
$api_key = 'ATKpagYXMd22yzPfCm';
$secret_key = 'rTj3hThcJ5gvo4yRwB29bvXDQB90xh3tRuQI';

// Position details
$symbol = 'BOMEUSDT';
$side = 'Sell';  // Opposite side to close the Buy position
$qty = 2600;     // Quantity of contracts to close the position

// Prepare timestamp and parameters for the order
$timestamp = round(microtime(true) * 1000);
$orderParams = [
    'api_key' => $api_key,
    'symbol' => $symbol,
    'side' => $side,
    'order_type' => 'Market', // Use market order for immediate closure
    'qty' => $qty,
    'time_in_force' => 'GoodTillCancel', // Ensures order stays until filled
    'reduce_only' => true, // To close the position, not open a new one
    'timestamp' => $timestamp
];

// Generate the signature for the request
$queryString = http_build_query($orderParams);
$sign = hash_hmac('sha256', $queryString, $api_secret);
$orderParams['sign'] = $sign;

// Send request to Bybit API to place the order
$url = "https://api.bybit.com/v5/order/create";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderParams));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

// Handle response
if ($result['retCode'] === 0) {
    echo "Position closed successfully for symbol $symbol.\n";
} else {
    echo "Error closing position: " . $result['retMsg'] . "\n";
}

?>