<?php
/**
 * Cron Job - Close Expired Trades
 * 
 * Run this file every minute via cron:
 * * * * * * php /path/to/binary-options/cron/close-trades.php
 */

// Prevent web access
if (php_sapi_name() !== 'cli' && !isset($_GET['key'])) {
    die('This script must be run from command line or with a security key.');
}

// Security key for web access (optional)
$securityKey = 'your-secret-cron-key-change-this';
if (isset($_GET['key']) && $_GET['key'] !== $securityKey) {
    die('Invalid security key.');
}

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/TradingEngine.php';

// Log start
$startTime = microtime(true);
echo "[" . date('Y-m-d H:i:s') . "] Starting trade closure process...\n";

// Close expired trades
$results = trading()->closeExpiredTrades();

// Log results
$elapsed = round((microtime(true) - $startTime) * 1000, 2);
echo "[" . date('Y-m-d H:i:s') . "] Processed: {$results['processed']} trades\n";
echo "  - Won: {$results['won']}\n";
echo "  - Lost: {$results['lost']}\n";
echo "  - Tie: {$results['tie']}\n";
echo "  - Time: {$elapsed}ms\n";
echo "[" . date('Y-m-d H:i:s') . "] Trade closure process completed.\n";
