import os import httpx from fastapi import FastAPI, HTTPException from pydantic import BaseModel from loguru import logger from datetime import datetime from exchange_factory import get_exchange from alpaca.trading.requests import MarketOrderRequest from alpaca.trading.enums import OrderSide, TimeInForce from risk_manager import RiskManager import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # --- Configuration --- TELEGRAM_BOT = os.getenv("TELEGRAM_BOT_TOKEN") TELEGRAM_CHAT = os.getenv("TELEGRAM_CHAT_ID") DASHBOARD_URL = "https://huggingface.co/spaces/rickyviale/polymonte-v113" RISK_TRADE = 0.005 CAPITAL = 10000.0 app = FastAPI(title="PolyMonte Executor") # Initialisation de l'exchange (Alpaca ou Mock) exchange = get_exchange() risk_manager = RiskManager() # --- Fonctions Utilitaires --- def send_telegram(msg: str): if not TELEGRAM_BOT or not TELEGRAM_CHAT: logger.info(f"[TELEGRAM SIM] {msg}") return try: keyboard = {"inline_keyboard": [[{"text": "Dashboard", "url": DASHBOARD_URL}]]} with httpx.Client(verify=False) as client: client.post( f"https://149.154.167.220/bot{TELEGRAM_BOT}/sendMessage", json={ "chat_id": TELEGRAM_CHAT, "text": msg, "reply_markup": keyboard, "parse_mode": "HTML" }, headers={'Host': 'api.telegram.org', 'Connection': 'close'}, timeout=10 ) except Exception as e: logger.error(f"Telegram error: {e}") def compute_qty(price: float, atr: float, lstm_prob: float = 0.5) -> int: return risk_manager.position_size(CAPITAL, price, atr, lstm_prob) # --- Schemas de donnees --- class TradeRequest(BaseModel): symbol: str side: str price: float atr: float lstm_prob: float = 0.5 stop_loss: float | None = None take_profit: float | None = None trailing_stop: float | None = None # --- Endpoints API --- @app.post("/execute") async def execute_trade(request: TradeRequest): try: qty = compute_qty(request.price, request.atr, request.lstm_prob) side = request.side.upper() logger.info(f"Executing {side} {qty} {request.symbol}") order_status = "simulated" try: if hasattr(exchange, "submit_order"): alpaca_side = OrderSide.BUY if side == "BUY" else OrderSide.SELL order_data = MarketOrderRequest( symbol=request.symbol, qty=qty, side=alpaca_side, time_in_force=TimeInForce.GTC ) exchange.submit_order(order_data) order_status = "submitted" elif hasattr(exchange, "create_order"): exchange.create_order(request.symbol, "market", side.lower(), qty) order_status = "submitted" except Exception as trade_err: logger.error(f"Trade Execution Error: {trade_err}") order_status = f"failed: {trade_err}" send_telegram( f"Trade {order_status.upper()}\n{side} {qty} {request.symbol} @ {request.price}\n" f"SL={request.stop_loss or 'n/a'} | TP={request.take_profit or 'n/a'}" ) return {"status": "success", "qty": qty, "order_status": order_status} except Exception as e: logger.error(f"Global error in /execute: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/account") async def get_account(): try: if hasattr(exchange, "get_account"): acc = exchange.get_account() return { "equity": float(getattr(acc, "equity", 0)), "cash": float(getattr(acc, "cash", 0)), "buying_power": float(getattr(acc, "buying_power", 0)), "portfolio_value": float(getattr(acc, "portfolio_value", getattr(acc, "equity", 0))), } elif hasattr(exchange, "fetch_balance"): bal = exchange.fetch_balance() eq = bal["total"].get("USDT", bal["total"].get("USD", 0)) return {"equity": float(eq), "cash": float(eq), "buying_power": float(eq) * 2} return {"error": "Exchange method not implemented"} except Exception as e: return {"error": str(e)} @app.get("/positions") async def get_positions(): try: if hasattr(exchange, "get_all_positions"): pos = exchange.get_all_positions() return [ { "symbol": p.symbol, "qty": float(p.qty), "market_value": float(p.market_value), "unrealized_pl": float(p.unrealized_pl), } for p in pos ] elif hasattr(exchange, "fetch_positions"): return exchange.fetch_positions() return [] except Exception as e: return {"error": str(e)} @app.get("/") async def root(): return {"status": "running", "broker": getattr(exchange, "broker", "alpaca")} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8002)