#!/usr/bin/env python3 """ MEXC Order Fix V2 - Based on Exact Postman Collection Examples """ import os import sys import time import hmac import hashlib import requests from urllib.parse import urlencode from pathlib import Path # Add project root to path project_root = Path(__file__).parent sys.path.insert(0, str(project_root)) def create_mexc_signature_v2(api_key: str, secret_key: str, params: dict) -> tuple: """Create MEXC signature based on exact Postman examples""" # Current timestamp in milliseconds timestamp = str(int(time.time() * 1000)) # Add timestamp and recvWindow to params params_with_time = params.copy() params_with_time['timestamp'] = timestamp params_with_time['recvWindow'] = '5000' # Sort parameters alphabetically (as shown in MEXC examples) sorted_params = dict(sorted(params_with_time.items())) # Create query string exactly like the examples query_string = urlencode(sorted_params, doseq=True) print(f"API Key: {api_key}") print(f"Timestamp: {timestamp}") print(f"Query String: {query_string}") # MEXC signature formula: HMAC-SHA256(query_string, secret_key) # This matches the curl examples in their documentation signature = hmac.new( secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256 ).hexdigest() print(f"Generated Signature: {signature}") return signature, timestamp, query_string def test_mexc_order_v2(): """Test MEXC order placement with V2 signature method""" print("Testing MEXC Order V2 - Exact Postman Method...") print("=" * 60) # Get API credentials api_key = os.getenv('MEXC_API_KEY', '') api_secret = os.getenv('MEXC_SECRET_KEY', '') if not api_key or not api_secret: print("āŒ No MEXC API credentials found") return # Order parameters matching MEXC examples params = { 'symbol': 'ETHUSDC', 'side': 'BUY', 'type': 'LIMIT', 'quantity': '0.003', # Very small quantity 'price': '2900.0', # Price below market 'timeInForce': 'GTC' } print(f"Order Parameters: {params}") # Create signature signature, timestamp, query_string = create_mexc_signature_v2(api_key, api_secret, params) # Build final URL with all parameters base_url = "https://api.mexc.com/api/v3/order" full_url = f"{base_url}?{query_string}&signature={signature}" # Headers matching Postman examples headers = { 'X-MEXC-APIKEY': api_key, 'Content-Type': 'application/x-www-form-urlencoded' } try: print(f"\nMaking POST request to: {full_url}") print(f"Headers: {headers}") # POST request with query parameters (as shown in examples) response = requests.post(full_url, headers=headers, timeout=10) print(f"\nResponse Status: {response.status_code}") print(f"Response: {response.text}") if response.status_code == 200: result = response.json() print("āœ… Order placed successfully!") print(f"Order result: {result}") # Cancel immediately if successful if 'orderId' in result: print(f"\nšŸ”„ Canceling order {result['orderId']}...") cancel_order(api_key, api_secret, 'ETHUSDC', result['orderId']) else: print("āŒ Order placement failed") except Exception as e: print(f"āŒ Request error: {e}") def cancel_order(api_key: str, secret_key: str, symbol: str, order_id: str): """Cancel a MEXC order""" params = { 'symbol': symbol, 'orderId': order_id } signature, timestamp, query_string = create_mexc_signature_v2(api_key, secret_key, params) url = f"https://api.mexc.com/api/v3/order?{query_string}&signature={signature}" headers = {'X-MEXC-APIKEY': api_key} response = requests.delete(url, headers=headers, timeout=10) print(f"Cancel response: {response.status_code} - {response.text}") if __name__ == "__main__": test_mexc_order_v2()