import os import json import socket import ssl import struct import logging import time import asyncio import threading from datetime import datetime import requests from fastapi import FastAPI, Request, Form, HTTPException from fastapi.responses import HTMLResponse, RedirectResponse # Import Protobuf definitions from ctrader-open-api from ctrader_open_api.messages.OpenApiCommonMessages_pb2 import ProtoMessage from ctrader_open_api.messages.OpenApiMessages_pb2 import * from ctrader_open_api.messages.OpenApiModelMessages_pb2 import * # Logging Setup logging.basicConfig(level=logging.INFO) logger = logging.getLogger("CloudBot") app = FastAPI(title="cTra Webhook Bot") # Config from Environment variables (Hugging Face Secrets) CLIENT_ID = os.environ.get("CTRADER_CLIENT_ID", "").strip() CLIENT_SECRET = os.environ.get("CTRADER_CLIENT_SECRET", "").strip() CTRADER_ENV = os.environ.get("CTRADER_ENV", "demo").lower().strip() # "demo" or "live" # Per-symbol volume settings (in lots). Each symbol can have its own lot size. # The conversion to protocol units happens at trade time using the broker's lotSize. DEFAULT_VOLUME_LOTS = 0.01 # fallback for any unlisted symbol symbol_volumes = { "NAS100": 0.05, "NAS100m": 0.05, "USTEC": 0.05, "US500": 0.05, "US500m": 0.05, "US30": 0.05, "US30m": 0.05, "BTCUSD": 0.01, "ETHUSD": 0.01, "EURUSD": 0.01, "_DEFAULT_FOREX": 0.01, # catch-all for any forex pair not explicitly listed "_DEFAULT_CRYPTO": 0.01, # catch-all for any crypto pair not explicitly listed } # Per-symbol BUY/SELL/STOP-TRADE/ANCHOR toggle (controlled from dashboard, NOT TradingView) symbol_status = { "NAS100": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "NAS100m": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "USTEC": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "US500": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "US500m": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "US30": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "US30m": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "BTCUSD": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "ETHUSD": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "EURUSD": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "_DEFAULT_FOREX": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, "_DEFAULT_CRYPTO": {"buy": True, "sell": True, "stop-trade": True, "anchor": True}, } CONFIG_FILE = "bot_config.json" def load_config(): """Load persisted volumes + status toggles from disk.""" global symbol_volumes, symbol_status if os.path.exists(CONFIG_FILE): try: with open(CONFIG_FILE, "r") as f_conf: config = json.load(f_conf) if "volumes" in config: symbol_volumes.update(config["volumes"]) if "status" in config: for k, v in config["status"].items(): if k in symbol_status: symbol_status[k].update(v) else: symbol_status[k] = v logger.info("Configuration loaded from bot_config.json") except Exception as e: logger.error(f"Error loading bot_config.json: {e}") def save_config(): """Persist current volumes + status toggles to disk.""" try: config = {"volumes": symbol_volumes, "status": symbol_status} with open(CONFIG_FILE, "w") as f_conf: json.dump(config, f_conf, indent=4) logger.info("Configuration saved to bot_config.json") except Exception as e: logger.error(f"Error saving bot_config.json: {e}") load_config() logger.info(f"Per-symbol volumes initialized: {symbol_volumes}") logger.info(f"Per-symbol statuses initialized: {symbol_status}") # Global caches to eliminate latency of symbol resolution and limits querying SYMBOL_ID_CACHE = {} # symbol_name_upper -> symbol_id SYMBOL_LIMITS_CACHE = {} # symbol_id -> limits_dict (lotSize, maxVolume, minVolume, stepVolume) # ── PERSISTENT SOCKET ──────────────────────────────────────────────────────── # Instead of creating a new SSL socket on every webhook (adds ~500-1000ms), # we keep ONE authenticated socket alive with background heartbeats. _persistent_socket = None # The reusable authenticated SSL socket _persistent_socket_lock = threading.Lock() # Thread-safe access _heartbeat_thread = None # Background thread sending keepalive pings _heartbeat_stop = threading.Event() # Signal to stop the heartbeat thread # In-memory webhook log storage for the dashboard WEBHOOK_LOGS = [] TOKEN_FILE = "/tmp/tokens.json" if os.environ.get("SPACE_ID") else "tokens.json" # Helper: Save tokens to file def save_tokens(tokens): try: with open(TOKEN_FILE, "w") as f: json.dump(tokens, f) except Exception as e: logger.error(f"Failed to save tokens: {e}") # Helper: Load tokens from file def load_tokens(): if os.path.exists(TOKEN_FILE): try: with open(TOKEN_FILE, "r") as f: return json.load(f) except Exception as e: logger.error(f"Failed to load tokens: {e}") # Fallback to environment secrets if token file doesn't exist env_refresh = os.environ.get("CTRADER_REFRESH_TOKEN") env_access = os.environ.get("CTRADER_ACCESS_TOKEN") env_acc_id = os.environ.get("CTRADER_ACCOUNT_ID") if env_refresh or env_access: logger.info("Using tokens from environment secrets") return { "refresh_token": env_refresh.strip() if env_refresh else "", "access_token": env_access.strip() if env_access else "", "account_id": env_acc_id.strip() if env_acc_id else "", "updated_at": time.time() } return None # Helper: Exchange authorization code or refresh token def fetch_token_from_api(payload): url = "https://openapi.ctrader.com/apps/token" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Accept": "application/json, text/plain, */*" } # Attempt 1: GET request with custom headers try: res = requests.get(url, params=payload, headers=headers, timeout=10) if res.status_code == 200: data = res.json() logger.info("Token request successful (GET)") return data except Exception as e: logger.warning(f"GET token request exception: {e}") # Attempt 2: POST request fallback with form-encoded data try: res = requests.post(url, data=payload, headers=headers, timeout=10) if res.status_code == 200: data = res.json() logger.info("Token request successful (POST)") return data elif res.status_code == 429: logger.warning("cTrader API rate limited (HTTP 429). Cloudflare/WAF blocked request.") return None else: logger.error(f"Token exchange failed (HTTP {res.status_code}): {res.text[:200]}") return None except Exception as e: logger.error(f"POST token request exception: {e}") return None # Helper: Send protocol buffer message over SSL Socket def send_proto_message(ssl_socket, message, payload_type, client_msg_id=None): inner_payload = message.SerializeToString() proto_msg = ProtoMessage() proto_msg.payloadType = payload_type proto_msg.payload = inner_payload if client_msg_id is not None: proto_msg.clientMsgId = str(client_msg_id) serialized = proto_msg.SerializeToString() length = len(serialized) header = struct.pack(">I", length) ssl_socket.sendall(header + serialized) # Helper: Receive protocol buffer message from SSL Socket def receive_proto_message(ssl_socket): try: header = ssl_socket.recv(4) if not header or len(header) < 4: return None length = struct.unpack(">I", header)[0] data = b"" while len(data) < length: chunk = ssl_socket.recv(length - len(data)) if not chunk: break data += chunk if len(data) < length: return None proto_msg = ProtoMessage() proto_msg.ParseFromString(data) return proto_msg except Exception as e: logger.error(f"Socket receive error: {e}") return None # Helper: Open socket & Authenticate Application + Account def get_authenticated_socket(account_id, access_token): tokens = load_tokens() env = tokens.get("environment", CTRADER_ENV) if tokens else CTRADER_ENV # Try preferred environment first, then fallback to the other envs_to_try = [env, "demo" if env == "live" else "live"] last_error = "" for try_env in envs_to_try: host = "live.ctraderapi.com" if try_env == "live" else "demo.ctraderapi.com" logger.info(f"Attempting connection to {host} for account {account_id}...") try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10.0) ssl_sock = ssl.wrap_socket(sock) ssl_sock.connect((host, 5035)) # 1. Application Auth app_req = ProtoOAApplicationAuthReq() app_req.clientId = CLIENT_ID app_req.clientSecret = CLIENT_SECRET send_proto_message(ssl_sock, app_req, 2100) proto_msg = receive_proto_message(ssl_sock) if not proto_msg or proto_msg.payloadType != 2101: error_detail = "" if proto_msg: try: err = ProtoOAErrorRes() err.ParseFromString(proto_msg.payload) error_detail = f" (payloadType={proto_msg.payloadType}, error={err.errorCode}: {err.description})" except Exception: error_detail = f" (payloadType={proto_msg.payloadType})" last_error = f"App auth rejected on {host}{error_detail}" logger.warning(last_error) ssl_sock.close() continue logger.info(f"App auth successful on {host}") # 2. Account Auth acc_req = ProtoOAAccountAuthReq() acc_req.ctidTraderAccountId = int(account_id) acc_req.accessToken = access_token send_proto_message(ssl_sock, acc_req, 2102) proto_msg = receive_proto_message(ssl_sock) if not proto_msg or proto_msg.payloadType != 2103: error_detail = "" if proto_msg: try: err = ProtoOAErrorRes() err.ParseFromString(proto_msg.payload) error_detail = f" (payloadType={proto_msg.payloadType}, error={err.errorCode}: {err.description})" except Exception: error_detail = f" (payloadType={proto_msg.payloadType})" last_error = f"Account auth rejected on {host} for account {account_id}{error_detail}" logger.warning(last_error) ssl_sock.close() continue logger.info(f"Account auth successful on {host} for account {account_id}") # If we connected on a different env than saved, update the saved env if try_env != env: logger.info(f"Updating saved environment from '{env}' to '{try_env}' (fallback succeeded)") if tokens: tokens["environment"] = try_env save_tokens(tokens) return ssl_sock except Exception as e: last_error = f"Connection failed to {host}: {e}" logger.warning(last_error) continue raise Exception(f"Could not authenticate on any server. Last error: {last_error}") # ── PERSISTENT SOCKET MANAGEMENT ───────────────────────────────────────────── def _drain_socket(ssl_sock, timeout=0.05): """Drain any pending messages (heartbeat responses, spot events, etc.) from the socket. This prevents stale data from interfering with the next request/response pair.""" ssl_sock.settimeout(timeout) drained = 0 try: while True: header = ssl_sock.recv(4) if not header or len(header) < 4: break length = struct.unpack(">I", header)[0] data = b"" while len(data) < length: chunk = ssl_sock.recv(length - len(data)) if not chunk: break data += chunk drained += 1 except (socket.timeout, ssl.SSLError, OSError): pass # No more data — this is expected finally: ssl_sock.settimeout(10.0) # Restore normal timeout if drained > 0: logger.debug(f"Drained {drained} stale message(s) from persistent socket.") def _heartbeat_worker(): """Background thread that sends heartbeat pings every 10 seconds to keep the persistent socket alive. cTrader disconnects idle sockets after ~30s.""" global _persistent_socket logger.info("Heartbeat worker started.") while not _heartbeat_stop.is_set(): _heartbeat_stop.wait(10) # Sleep 10 seconds (interruptible) if _heartbeat_stop.is_set(): break with _persistent_socket_lock: sock = _persistent_socket if sock is None: continue try: hb = ProtoMessage() hb.payloadType = 51 # ProtoHeartbeatEvent serialized = hb.SerializeToString() header = struct.pack(">I", len(serialized)) sock.sendall(header + serialized) logger.debug("Heartbeat sent on persistent socket.") except Exception as e: logger.warning(f"Heartbeat failed — marking socket as dead: {e}") _invalidate_persistent_socket() logger.info("Heartbeat worker stopped.") def _invalidate_persistent_socket(): """Close and discard the persistent socket so the next call creates a fresh one.""" global _persistent_socket with _persistent_socket_lock: if _persistent_socket is not None: try: _persistent_socket.close() except Exception: pass _persistent_socket = None logger.info("Persistent socket invalidated.") def get_or_create_socket(account_id, access_token): """Return the persistent authenticated socket, creating one if needed. This eliminates ~500-1000ms of TCP+SSL+Auth overhead on every webhook.""" global _persistent_socket, _heartbeat_thread with _persistent_socket_lock: # Quick health check on existing socket if _persistent_socket is not None: try: # Try a zero-byte peek to see if socket is alive _persistent_socket.settimeout(0.01) # Drain any pending heartbeat responses _drain_socket(_persistent_socket, timeout=0.02) _persistent_socket.settimeout(10.0) logger.info("Reusing persistent socket (0ms connection overhead).") return _persistent_socket except Exception as e: logger.warning(f"Persistent socket dead ({e}), creating new one...") try: _persistent_socket.close() except Exception: pass _persistent_socket = None # Create a fresh authenticated socket logger.info("Creating new persistent socket...") new_sock = get_authenticated_socket(account_id, access_token) _persistent_socket = new_sock # Start heartbeat thread if not running if _heartbeat_thread is None or not _heartbeat_thread.is_alive(): _heartbeat_stop.clear() _heartbeat_thread = threading.Thread(target=_heartbeat_worker, daemon=True) _heartbeat_thread.start() return _persistent_socket # Helper: Resolve Symbol Name to cTrader Symbol ID (with global caching) def resolve_symbol_id(ssl_sock, account_id, symbol_name): symbol_name_upper = symbol_name.upper() if symbol_name_upper in SYMBOL_ID_CACHE: logger.info(f"Resolved symbol ID for {symbol_name_upper} from cache: {SYMBOL_ID_CACHE[symbol_name_upper]}") return SYMBOL_ID_CACHE[symbol_name_upper] logger.info(f"Symbol ID for {symbol_name_upper} not in cache. Fetching list from broker...") req = ProtoOASymbolsListReq() req.ctidTraderAccountId = int(account_id) send_proto_message(ssl_sock, req, 2114) while True: proto_msg = receive_proto_message(ssl_sock) if not proto_msg: break if proto_msg.payloadType == 2115: # ProtoOASymbolsListRes res = ProtoOASymbolsListRes() res.ParseFromString(proto_msg.payload) for sym in res.symbol: SYMBOL_ID_CACHE[sym.symbolName.upper()] = sym.symbolId logger.info(f"Cached {len(res.symbol)} symbols from list response.") break return SYMBOL_ID_CACHE.get(symbol_name_upper) # Helper: Get volume limits and lotSize for a symbol from broker (with global caching) def get_symbol_volume_limits(ssl_sock, account_id, symbol_id): """Query the broker for the symbol's volume limits and lotSize. Returns dict with maxVolume, minVolume, stepVolume (protocol units) and lotSize (units per 1 lot).""" if symbol_id in SYMBOL_LIMITS_CACHE: logger.info(f"Resolved volume limits for symbol ID {symbol_id} from cache: {SYMBOL_LIMITS_CACHE[symbol_id]}") return SYMBOL_LIMITS_CACHE[symbol_id] result = {} try: logger.info(f"Volume limits for symbol ID {symbol_id} not in cache. Fetching details from broker...") req = ProtoOASymbolByIdReq() req.ctidTraderAccountId = int(account_id) req.symbolId.append(int(symbol_id)) send_proto_message(ssl_sock, req, 2116) while True: proto_msg = receive_proto_message(ssl_sock) if not proto_msg: break if proto_msg.payloadType == 2117: # ProtoOASymbolByIdRes res = ProtoOASymbolByIdRes() res.ParseFromString(proto_msg.payload) for sym in res.symbol: if hasattr(sym, 'maxVolume') and sym.maxVolume: result['maxVolume'] = sym.maxVolume if hasattr(sym, 'minVolume') and sym.minVolume: result['minVolume'] = sym.minVolume if hasattr(sym, 'stepVolume') and sym.stepVolume: result['stepVolume'] = sym.stepVolume # Extract lotSize: number of units per 1 standard lot if hasattr(sym, 'lotSize') and sym.lotSize: result['lotSize'] = sym.lotSize SYMBOL_LIMITS_CACHE[symbol_id] = result logger.info(f"Symbol {symbol_id} info cached: lotSize={result.get('lotSize', 'N/A')}, max={result.get('maxVolume', 'N/A')}, min={result.get('minVolume', 'N/A')}, step={result.get('stepVolume', 'N/A')}") break except Exception as e: logger.warning(f"Could not fetch volume limits for symbol {symbol_id}: {e}") return result # Helper: Convert lots to cTrader protocol volume using broker's lotSize def lots_to_protocol_volume(lots, lot_size): """Convert a lot value to cTrader protocol units. Protocol volume = lots × lotSize e.g. EURUSD: 0.01 lots × 100000 lotSize = 1,000 e.g. BTCUSD: 0.01 lots × 100 lotSize = 1 e.g. NAS100: 0.05 lots × 100 lotSize = 5""" result = int(lots * lot_size) logger.info(f"lots_to_protocol_volume: {lots} lots × {lot_size} lotSize = {result} protocol units") return result # Helper: Get the configured lot size for a given ticker def get_volume_for_symbol(ticker): """Look up the per-symbol volume (in lots). Falls back to _DEFAULT_CRYPTO or _DEFAULT_FOREX, then DEFAULT_VOLUME_LOTS.""" ticker_upper = ticker.upper() if ticker_upper in symbol_volumes: return symbol_volumes[ticker_upper] # Known crypto suffixes CRYPTO_BASES = ["BTC", "ETH", "XLM", "BCH", "SOL", "DOGE", "BNB", "LTC", "ADA", "AVAX", "LNK", "MATIC", "EOS", "DOT", "XRP", "SHIB", "UNI", "LINK"] if any(ticker_upper.startswith(base) for base in CRYPTO_BASES) and ticker_upper.endswith("USD"): return symbol_volumes.get('_DEFAULT_CRYPTO', DEFAULT_VOLUME_LOTS) # Fallback: if it looks like a forex pair (6 chars, all letters), use default forex if len(ticker_upper) == 6 and ticker_upper.isalpha(): return symbol_volumes.get('_DEFAULT_FOREX', DEFAULT_VOLUME_LOTS) return DEFAULT_VOLUME_LOTS # Helper: Place market order with automatic volume reduction on "Not enough funds" def place_market_order_smart(ssl_sock, account_id, symbol_id, trade_side, volume, min_volume=100, step_volume=100): """Try placing an order. If 'Not enough funds', halve volume and retry until min_volume.""" attempt = 0 try_volume = volume while try_volume >= min_volume: attempt += 1 # Round down to nearest step if step_volume > 0: try_volume = (try_volume // step_volume) * step_volume if try_volume < min_volume: break logger.info(f"Order attempt {attempt}: volume={try_volume} protocol units") res = place_market_order(ssl_sock, account_id, symbol_id, trade_side, int(try_volume)) if res.get('status') == 'success': if attempt > 1: logger.info(f"Order succeeded on attempt {attempt} with reduced volume {try_volume}") return res error_msg = res.get('message', '') if 'not enough funds' in error_msg.lower() or 'Not enough' in error_msg: # Halve the volume and retry try_volume = try_volume // 2 logger.info(f"Not enough funds — reducing volume to {try_volume} and retrying...") else: # Different error, don't retry return res return {"status": "error", "message": f"Not enough funds even at minimum volume ({min_volume} protocol units)"} # Helper: Fetch Account Balance/Details def get_trader_details(ssl_sock, account_id): req = ProtoOATraderReq() req.ctidTraderAccountId = int(account_id) send_proto_message(ssl_sock, req, 2118) while True: proto_msg = receive_proto_message(ssl_sock) if not proto_msg: break if proto_msg.payloadType == 2119: # ProtoOATraderRes res = ProtoOATraderRes() res.ParseFromString(proto_msg.payload) return res.trader return None # Helper: Fetch Open Positions def get_open_positions(ssl_sock, account_id): req = ProtoOAReconcileReq() req.ctidTraderAccountId = int(account_id) send_proto_message(ssl_sock, req, 2124) while True: proto_msg = receive_proto_message(ssl_sock) if not proto_msg: break if proto_msg.payloadType == 2125: # ProtoOAReconcileRes res = ProtoOAReconcileRes() res.ParseFromString(proto_msg.payload) return res.position return [] # Config: Max losing positions allowed per direction per symbol MAX_LOSING_POSITIONS = 2 # Helper: Get current spot price (bid/ask) for a symbol def get_spot_price(ssl_sock, account_id, symbol_id): current_bid = None current_ask = None try: spot_req = ProtoOASubscribeSpotsReq() spot_req.ctidTraderAccountId = int(account_id) spot_req.symbolId.append(int(symbol_id)) send_proto_message(ssl_sock, spot_req, 2127) # Read responses until we get a spot event for _ in range(10): proto_msg = receive_proto_message(ssl_sock) if not proto_msg: break if proto_msg.payloadType == 2131: # ProtoOASpotEvent spot = ProtoOASpotEvent() spot.ParseFromString(proto_msg.payload) if hasattr(spot, 'bid') and spot.bid: current_bid = spot.bid / 100000.0 # Convert from protocol price if hasattr(spot, 'ask') and spot.ask: current_ask = spot.ask / 100000.0 if current_bid and current_ask: break elif proto_msg.payloadType == 2128: # Subscribe confirmation continue # Unsubscribe from spots try: unsub_req = ProtoOAUnsubscribeSpotsReq() unsub_req.ctidTraderAccountId = int(account_id) unsub_req.symbolId.append(int(symbol_id)) send_proto_message(ssl_sock, unsub_req, 2129) receive_proto_message(ssl_sock) # Consume the response except Exception: pass except Exception as e: logger.warning(f"Could not fetch spot price: {e}") return current_bid, current_ask # Helper: Count losing positions in a given direction def count_losing_positions(positions, trade_side, current_bid, current_ask): """Count positions that are currently in loss. trade_side: 1 = BUY positions, 2 = SELL positions""" count = 0 for p in positions: if p.tradeData.tradeSide != trade_side: continue entry_price = p.price if trade_side == 1: # BUY position is losing when bid <= entry if current_bid and current_bid <= entry_price: count += 1 elif not current_bid: count += 1 # Can't determine, assume losing to be safe else: # SELL position is losing when ask >= entry if current_ask and current_ask >= entry_price: count += 1 elif not current_ask: count += 1 return count # Helper: Place Market Order or Close Position def place_market_order(ssl_sock, account_id, symbol_id, trade_side, volume, position_id=None): if position_id is not None: req = ProtoOAClosePositionReq() req.ctidTraderAccountId = int(account_id) req.positionId = int(position_id) req.volume = int(volume) send_proto_message(ssl_sock, req, 2111) else: req = ProtoOANewOrderReq() req.ctidTraderAccountId = int(account_id) req.symbolId = int(symbol_id) req.orderType = ProtoOAOrderType.MARKET req.tradeSide = trade_side req.volume = int(volume) send_proto_message(ssl_sock, req, 2106) while True: proto_msg = receive_proto_message(ssl_sock) if not proto_msg: break if proto_msg.payloadType == 2126: # ProtoOAExecutionEvent res = ProtoOAExecutionEvent() res.ParseFromString(proto_msg.payload) return {"status": "success", "orderId": res.order.orderId} elif proto_msg.payloadType == 2132: # ProtoOAOrderErrorEvent res = ProtoOAOrderErrorEvent() res.ParseFromString(proto_msg.payload) return {"status": "error", "message": res.description} elif proto_msg.payloadType == 2142: # ProtoOAErrorRes res = ProtoOAErrorRes() res.ParseFromString(proto_msg.payload) return {"status": "error", "message": f"cTra Error: {res.errorCode} - {res.description}"} elif proto_msg.payloadType == 50: # ProtoErrorRes res = ProtoErrorRes() res.ParseFromString(proto_msg.payload) return {"status": "error", "message": f"cTra Generic Error: {res.errorCode} - {res.description}"} else: logger.info(f"place_market_order: Received other payloadType: {proto_msg.payloadType}") return {"status": "error", "message": "No execution response received"} # Rate-limit guard: track last refresh attempt to avoid hammering the API _last_refresh_attempt = 0 REFRESH_COOLDOWN = 3600 # seconds between refresh attempts (1 hour — prevents 429 on cloud IPs) # Helper: Refresh tokens and return active ones def get_valid_tokens(): global _last_refresh_attempt tokens = load_tokens() if not tokens: return None access_token = tokens.get("access_token") refresh_token = tokens.get("refresh_token") updated_at = tokens.get("updated_at", 0) # Only refresh if the access token is missing or older than 24 hours (86400 seconds) # AND we haven't tried refreshing in the last REFRESH_COOLDOWN seconds if not access_token or (time.time() - updated_at > 86400): if time.time() - _last_refresh_attempt < REFRESH_COOLDOWN: logger.info(f"Skipping token refresh (cooldown: {REFRESH_COOLDOWN - (time.time() - _last_refresh_attempt):.0f}s remaining)") if access_token: return tokens return None _last_refresh_attempt = time.time() if refresh_token: payload = { "grant_type": "refresh_token", "refresh_token": refresh_token, "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET } res_data = fetch_token_from_api(payload) if res_data and "accessToken" in res_data: tokens["access_token"] = res_data["accessToken"] tokens["refresh_token"] = res_data["refreshToken"] tokens["updated_at"] = time.time() # Auto-discover the correct account ID from the new access token # This prevents stale CTRADER_ACCOUNT_ID env secrets from breaking things try: for try_env in ["demo", "live"]: try: disc_host = "live.ctraderapi.com" if try_env == "live" else "demo.ctraderapi.com" disc_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) disc_sock.settimeout(10.0) disc_ssl = ssl.wrap_socket(disc_sock) disc_ssl.connect((disc_host, 5035)) app_req = ProtoOAApplicationAuthReq() app_req.clientId = CLIENT_ID app_req.clientSecret = CLIENT_SECRET send_proto_message(disc_ssl, app_req, 2100) app_resp = receive_proto_message(disc_ssl) if not app_resp or app_resp.payloadType != 2101: disc_ssl.close() continue acc_list_req = ProtoOAGetAccountListByAccessTokenReq() acc_list_req.accessToken = res_data["accessToken"] send_proto_message(disc_ssl, acc_list_req, 2149) proto_msg = receive_proto_message(disc_ssl) if proto_msg and proto_msg.payloadType == 2150: acc_list_res = ProtoOAGetAccountListByAccessTokenRes() acc_list_res.ParseFromString(proto_msg.payload) if acc_list_res.ctidTraderAccount: # Pick the account matching CTRADER_ENV preference selected = None for a in acc_list_res.ctidTraderAccount: is_live = getattr(a, "isLive", False) if (CTRADER_ENV == "live" and is_live) or (CTRADER_ENV == "demo" and not is_live): selected = a break if not selected: selected = acc_list_res.ctidTraderAccount[0] tokens["account_id"] = str(selected.ctidTraderAccountId) tokens["environment"] = "live" if getattr(selected, "isLive", False) else "demo" logger.info(f"Auto-discovered account {tokens['account_id']} ({tokens['environment']}) after token refresh") disc_ssl.close() if tokens.get("account_id"): break except Exception as inner_e: logger.warning(f"Account discovery failed on {try_env}: {inner_e}") continue except Exception as e: logger.warning(f"Account auto-discovery failed: {e}") save_tokens(tokens) return tokens else: logger.error(f"Failed to refresh token: {res_data}") # Return existing tokens if still fresh/valid if access_token: return tokens return None # ── FASTAPI ROUTING ───────────────────────────────────────────────────────── @app.get("/", response_class=HTMLResponse) async def dashboard(request: Request): # Dashboard uses get_valid_tokens() to automatically manage and refresh expired tokens. # This reads from the local cache file, only querying cTrader API if the token is >50m old. tokens = get_valid_tokens() is_authenticated = tokens is not None and bool(tokens.get("access_token")) account_id = tokens.get("account_id", "") if is_authenticated else "" access_token = tokens.get("access_token", "") if is_authenticated else "" balance = "N/A" positions = [] error_msg = "" if is_authenticated and account_id: try: # Connect to cTrader and load live account details ssl_sock = get_authenticated_socket(account_id, access_token) trader = get_trader_details(ssl_sock, account_id) if trader: balance = f"${trader.balance / 100:.2f}" positions_raw = get_open_positions(ssl_sock, account_id) for p in positions_raw: positions.append({ "id": p.positionId, "symbol_id": p.tradeData.symbolId, "side": "BUY" if p.tradeData.tradeSide == 1 else "SELL", "volume": f"{p.tradeData.volume / 10000000:.2f} lots", "entry_price": p.price, "pnl": f"${p.commission / 100:.2f}" # Note: commission/pnl properties depend on cTrader API model }) ssl_sock.close() except Exception as e: error_msg = f"Failed to connect to cTra: {e}" logger.error(error_msg) # 1. Construct positions table HTML (avoiding nested f-strings) positions_html = "" if positions: rows = "".join( f"
| Position ID | Symbol ID | Side | Volume | Entry Price |
|---|
No active positions found.
' # 1b. Construct per-symbol volume rows HTML display_order = ["NAS100", "NAS100m", "USTEC", "US500", "US500m", "US30", "US30m", "BTCUSD", "ETHUSD", "EURUSD", "_DEFAULT_FOREX", "_DEFAULT_CRYPTO"] volume_rows_html = "" for sym in display_order: if sym not in symbol_volumes: continue vol = symbol_volumes[sym] status = symbol_status.get(sym, {"buy": True, "sell": True, "stop-trade": True, "anchor": True}) buy_on = status.get("buy", True) sell_on = status.get("sell", True) stop_on = status.get("stop-trade", True) anchor_on = status.get("anchor", True) display_name = "Default Forex" if sym == "_DEFAULT_FOREX" else "Default Crypto" if sym == "_DEFAULT_CRYPTO" else sym row_bg = "#0f172a" if display_order.index(sym) % 2 == 0 else "#111827" # Build toggle buttons for all 4 actions def _btn(label, key, is_on, on_color): color = on_color if is_on else "#475569" text = f"{label} \u2713" if is_on else f"{label} \u2717" val = "false" if is_on else "true" return f'''''' buy_btn = _btn("BUY", "buy", buy_on, "#00E676") sell_btn = _btn("SELL", "sell", sell_on, "#FF5252") stop_btn = _btn("STOP", "stop-trade", stop_on, "#FF9800") anchor_btn = _btn("ANCHOR", "anchor", anchor_on, "#FF9800") volume_rows_html += f'''Please connect your cTra account to authorize the bot to execute trades on your behalf.
Authorize Bot with cTraSet the lot size for each instrument. Conversion to broker units happens automatically using the broker's lotSize.
| Symbol | Lot Size | Allow Trade |
|---|
Hugging Face Cloud Server ({CTRADER_ENV} environment)