""" Darwinex DWX Connect execution layer. Same interface as MT5 executor but uses DWX Connect. """ import asyncio import logging from database import db as database logger = logging.getLogger("gap_system.execution.darwinex") _dwx_available = False _dwx = None try: from dwx_connect import dwx_client _dwx_available = True except ImportError: logger.warning("dwx-connect not installed — Darwinex execution disabled") async def initialize() -> bool: """Initialise Darwinex connection.""" global _dwx if not _dwx_available: logger.warning("DWX Connect not available") return False try: _dwx = dwx_client() await asyncio.sleep(2) # allow connection to establish if _dwx.open_orders or True: # connected logger.info("Darwinex DWX connected") return True return False except Exception as e: logger.error("Darwinex init error: %s", e) return False async def execute_trade( symbol: str, direction: str, lot_size: float, hold_seconds: int, ) -> dict: """Execute through Darwinex — same interface as MT5.""" if not _dwx_available or _dwx is None: return {"status": "failed", "error": "Darwinex not available"} try: order_type = "buy" if direction == "BULLISH" else "sell" # Open trade _dwx.open_order( symbol=symbol, order_type=order_type, lots=lot_size, comment=f"GapAI_{direction}_{hold_seconds}s", ) trade_id = await database.insert_trade( asset=symbol, direction=direction, lot_size=lot_size, hold_seconds=hold_seconds, ) logger.info("Darwinex trade opened: %s %s %.2f (hold %ds)", symbol, direction, lot_size, hold_seconds) # Wait hold_seconds await asyncio.sleep(hold_seconds) # Close all trades for this symbol _dwx.close_all_orders() await database.close_trade(trade_id, 0, 0, 0) return { "status": "closed", "hold_seconds": hold_seconds, "trade_id": trade_id, } except Exception as e: logger.error("Darwinex trade error: %s", e) return {"status": "failed", "error": str(e)}