'Method not allowed']); exit; } // Configuration $config = [ 'ai_provider' => 'openai', // openai, claude, or glm 'api_key' => '', // Replace with your actual API key 'model' => 'gpt-4', // gpt-4, gpt-3.5-turbo, claude-3, etc. 'max_tokens' => 500, 'temperature' => 0.3, 'log_file' => __DIR__ . '/logs/trading_' . date('Y-m-d') . '.log', 'confidence_threshold' => 0.7 ]; // Ensure logs directory exists if (!file_exists(__DIR__ . '/logs')) { mkdir(__DIR__ . '/logs', 0755, true); } // Get input data $jsonInput = file_get_contents('php://input'); $data = json_decode($jsonInput, true); // Validate input if (!$data || !isset($data['symbol']) || !isset($data['structure'])) { http_response_code(400); echo json_encode(['error' => 'Invalid input data']); exit; } // Log the request logMessage("Request received: " . $jsonInput); // Build AI prompt $prompt = buildPrompt($data); // Get AI decision $decision = getAIDecision($prompt, $config); // Log the response logMessage("AI Response: " . json_encode($decision)); // Return decision echo json_encode($decision); /** * Build the prompt for the AI model */ function buildPrompt($data) { $prompt = "You are a professional forex analyst with expertise in price action trading.\n\n"; $prompt .= "Given this market data:\n"; $prompt .= json_encode($data, JSON_PRETTY_PRINT) . "\n\n"; $prompt .= "Determine if the next likely move is BUY, SELL, or WAIT.\n\n"; $prompt .= "Base your analysis on:\n"; $prompt .= "- Market structure (uptrend, downtrend, or ranging)\n"; $prompt .= "- Trendline state (bounce, break, or retest)\n"; $prompt .= "- Liquidity sweeps (stop hunts)\n"; $prompt .= "- Candlestick patterns\n\n"; $prompt .= "Return a JSON response with these fields:\n"; $prompt .= "- signal: 'BUY', 'SELL', or 'WAIT'\n"; $prompt .= "- entry: Suggested entry price\n"; $prompt .= "- sl: Suggested stop loss price\n"; $prompt .= "- tp: Suggested take profit price\n"; $prompt .= "- confidence: Confidence level (0.0-1.0)\n"; $prompt .= "- reason: Brief explanation of your decision\n\n"; $prompt .= "Example response:\n"; $prompt .= "{\n"; $prompt .= " \"signal\": \"BUY\",\n"; $prompt .= " \"entry\": 1.0732,\n"; $prompt .= " \"sl\": 1.0705,\n"; $prompt .= " \"tp\": 1.0792,\n"; $prompt .= " \"confidence\": 0.86,\n"; $prompt .= " \"reason\": \"Bullish engulfing after trendline retest in uptrend\"\n"; $prompt .= "}\n\n"; $prompt .= "Analyze the data and provide your decision:"; return $prompt; } /** * Get decision from AI model */ function getAIDecision($prompt, $config) { $decision = [ 'signal' => 'WAIT', 'entry' => 0, 'sl' => 0, 'tp' => 0, 'confidence' => 0.5, 'reason' => 'Unable to get AI decision' ]; try { if ($config['ai_provider'] === 'openai') { $response = callOpenAI($prompt, $config); } elseif ($config['ai_provider'] === 'claude') { $response = callClaude($prompt, $config); } elseif ($config['ai_provider'] === 'glm') { $response = callGLM($prompt, $config); } else { logMessage("Unknown AI provider: " . $config['ai_provider']); return $decision; } // Parse the response $parsed = json_decode($response, true); if ($parsed && isset($parsed['signal'])) { $decision = $parsed; // Validate confidence if ($decision['confidence'] < $config['confidence_threshold']) { $decision['signal'] = 'WAIT'; $decision['reason'] .= ' (Low confidence, waiting)'; } } else { logMessage("Failed to parse AI response: " . $response); } } catch (Exception $e) { logMessage("Error getting AI decision: " . $e->getMessage()); } return $decision; } /** * Call OpenAI API */ function callOpenAI($prompt, $config) { $url = 'https://api.openai.com/v1/chat/completions'; $data = [ 'model' => $config['model'], 'messages' => [ [ 'role' => 'system', 'content' => 'You are a professional forex analyst. Always respond with valid JSON.' ], [ 'role' => 'user', 'content' => $prompt ] ], 'max_tokens' => $config['max_tokens'], 'temperature' => $config['temperature'] ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $config['api_key'] ]); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode !== 200) { throw new Exception("OpenAI API error: HTTP $httpCode - $response"); } $result = json_decode($response, true); if (!isset($result['choices'][0]['message']['content'])) { throw new Exception("Invalid OpenAI response format"); } return $result['choices'][0]['message']['content']; } /** * Call Claude API */ function callClaude($prompt, $config) { $url = 'https://api.anthropic.com/v1/messages'; $data = [ 'model' => $config['model'], 'max_tokens' => $config['max_tokens'], 'temperature' => $config['temperature'], 'system' => 'You are a professional forex analyst. Always respond with valid JSON.', 'messages' => [ [ 'role' => 'user', 'content' => $prompt ] ] ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'x-api-key: ' . $config['api_key'], 'anthropic-version: 2023-06-01' ]); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode !== 200) { throw new Exception("Claude API error: HTTP $httpCode - $response"); } $result = json_decode($response, true); if (!isset($result['content'][0]['text'])) { throw new Exception("Invalid Claude response format"); } return $result['content'][0]['text']; } /** * Call GLM API */ function callGLM($prompt, $config) { $url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions'; $data = [ 'model' => $config['model'], 'messages' => [ [ 'role' => 'system', 'content' => 'You are a professional forex analyst. Always respond with valid JSON.' ], [ 'role' => 'user', 'content' => $prompt ] ], 'max_tokens' => $config['max_tokens'], 'temperature' => $config['temperature'] ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $config['api_key'] ]); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode !== 200) { throw new Exception("GLM API error: HTTP $httpCode - $response"); } $result = json_decode($response, true); if (!isset($result['choices'][0]['message']['content'])) { throw new Exception("Invalid GLM response format"); } return $result['choices'][0]['message']['content']; } /** * Log message to file */ function logMessage($message) { global $config; $timestamp = date('Y-m-d H:i:s'); $logEntry = "[$timestamp] $message\n"; $logFile = $config['ai']['log_dir'] . '/ai.log'; file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX); } ?>