Spaces:
Sleeping
Sleeping
File size: 5,415 Bytes
3385fde 6231c1d 3385fde 6231c1d 3385fde 6231c1d 3385fde 6231c1d 3385fde 6231c1d 3385fde 6231c1d 3385fde | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | 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"<b>Trade {order_status.upper()}</b>\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)
|