Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
| 1 | """Flask web dashboard for Alice (lazy Flask import so CLI works without it).""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from typing import Any |
| 6 | |
| 7 | INDEX_HTML = """<!DOCTYPE html> |
| 8 | <html lang="en"> |
| 9 | <head> |
| 10 | <meta charset="utf-8"> |
| 11 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 12 | <title>Alice Trading Dashboard</title> |
| 13 | <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script> |
| 14 | <style> |
| 15 | :root { --bg:#0d1117; --panel:#161b22; --line:#30363d; --txt:#e6edf3; |
| 16 | --green:#3fb950; --red:#f85149; --blue:#58a6ff; --amber:#d29922; } |
| 17 | * { box-sizing:border-box; } |
| 18 | body { margin:0; background:var(--bg); color:var(--txt); |
| 19 | font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif; } |
| 20 | header { display:flex; align-items:center; gap:12px; padding:14px 20px; |
| 21 | border-bottom:1px solid var(--line); } |
| 22 | header h1 { font-size:18px; margin:0; } |
| 23 | .badge { padding:3px 10px; border-radius:20px; font-size:12px; font-weight:600; } |
| 24 | .off { background:#3a2a2a; color:var(--red); } |
| 25 | .on { background:#1a3a25; color:var(--green); } |
| 26 | main { max-width:1100px; margin:0 auto; padding:20px; display:grid; gap:16px; } |
| 27 | .card { background:var(--panel); border:1px solid var(--line); border-radius:8px; |
| 28 | padding:16px; } |
| 29 | .card h2 { margin:0 0 12px; font-size:14px; text-transform:uppercase; |
| 30 | letter-spacing:.06em; color:#8b949e; } |
| 31 | .row { display:flex; gap:10px; flex-wrap:wrap; align-items:end; } |
| 32 | label { font-size:12px; color:#8b949e; display:block; margin-bottom:4px; } |
| 33 | input,select,button { background:#0d1117; color:var(--txt); border:1px solid var(--line); |
| 34 | border-radius:6px; padding:8px 10px; font-size:14px; } |
| 35 | button { background:#1f6feb; border-color:#1f6feb; cursor:pointer; font-weight:600; } |
| 36 | button:hover { background:#388bfd; } |
| 37 | button.danger { background:#6e1515; border-color:#6e1515; } |
| 38 | .metrics { display:grid; grid-template-columns:repeat(auto-fit,minmax(130px,1fr)); |
| 39 | gap:10px; margin-top:12px; } |
| 40 | .metric { background:#0d1117; border:1px solid var(--line); border-radius:6px; |
| 41 | padding:10px; } |
| 42 | .metric .k { font-size:11px; color:#8b949e; } |
| 43 | .metric .v { font-size:18px; font-weight:700; margin-top:2px; } |
| 44 | .pos { color:var(--green); } .neg { color:var(--red); } |
| 45 | table { width:100%; border-collapse:collapse; font-size:13px; } |
| 46 | th,td { text-align:right; padding:6px 8px; border-bottom:1px solid var(--line); } |
| 47 | th:first-child,td:first-child { text-align:left; } |
| 48 | th { color:#8b949e; font-weight:600; } |
| 49 | canvas { max-height:340px; } |
| 50 | #msg { min-height:20px; font-size:13px; margin-top:8px; } |
| 51 | </style> |
| 52 | </head> |
| 53 | <body> |
| 54 | <header> |
| 55 | <h1>Alice Trading Dashboard</h1> |
| 56 | <span id="conn" class="badge off">disconnected</span> |
| 57 | <span id="acct" style="font-size:13px;color:#8b949e"></span> |
| 58 | </header> |
| 59 | <main> |
| 60 | <div class="card"> |
| 61 | <h2>Analysis</h2> |
| 62 | <div class="row"> |
| 63 | <div><label>Symbol</label><input id="symbol" value="AAPL" size="10"></div> |
| 64 | <div><label>Strategy</label><select id="strategy"> |
| 65 | <option value="sma_crossover">SMA Crossover</option> |
| 66 | <option value="rsi">RSI</option> |
| 67 | <option value="macd">MACD</option> |
| 68 | <option value="bollinger">Bollinger</option> |
| 69 | </select></div> |
| 70 | <div><label>Source</label><select id="source"> |
| 71 | <option value="yahoo">Yahoo Finance</option> |
| 72 | <option value="mt5">MT5 / Headway</option> |
| 73 | </select></div> |
| 74 | <div><label>Period</label><select id="period"> |
| 75 | <option value="6mo">6mo</option> |
| 76 | <option value="1y" selected>1y</option> |
| 77 | <option value="2y">2y</option> |
| 78 | </select></div> |
| 79 | <div><button onclick="loadAnalysis()">Run</button></div> |
| 80 | </div> |
| 81 | <div class="metrics" id="metrics"></div> |
| 82 | </div> |
| 83 | <div class="card"><h2>Price & Signals</h2><canvas id="price"></canvas></div> |
| 84 | <div class="card"><h2>Equity Curve</h2><canvas id="equity"></canvas></div> |
| 85 | <div class="card"> |
| 86 | <h2>Headway Positions</h2> |
| 87 | <table><thead><tr><th>Ticket</th><th>Symbol</th><th>Side</th><th>Vol</th> |
| 88 | <th>Open</th><th>Now</th><th>P&L</th></tr></thead> |
| 89 | <tbody id="positions"><tr><td colspan="7">loading…</td></tr></tbody></table> |
| 90 | </div> |
| 91 | <div class="card"> |
| 92 | <h2>Order Ticket</h2> |
| 93 | <div class="row"> |
| 94 | <div><label>Symbol</label><input id="oSym" value="EURUSD" size="10"></div> |
| 95 | <div><label>Side</label><select id="oSide"> |
| 96 | <option value="buy">Buy</option><option value="sell">Sell</option> |
| 97 | </select></div> |
| 98 | <div><label>Lots</label><input id="oVol" type="number" value="0.01" |
| 99 | step="0.01" min="0.01" style="width:90px"></div> |
| 100 | <div><label>SL (opt)</label><input id="oSL" type="number" step="any" |
| 101 | style="width:110px"></div> |
| 102 | <div><label>TP (opt)</label><input id="oTP" type="number" step="any" |
| 103 | style="width:110px"></div> |
| 104 | <div><label>Real order?</label><select id="oLive"> |
| 105 | <option value="no">Dry run</option><option value="yes">LIVE</option> |
| 106 | </select></div> |
| 107 | <div><button class="danger" onclick="sendOrder()">Send</button></div> |
| 108 | </div> |
| 109 | <div id="msg"></div> |
| 110 | </div> |
| 111 | </main> |
| 112 | <script> |
| 113 | let priceChart=null, equityChart=null; |
| 114 | const OVERLAY_COLORS=['#58a6ff','#d29922','#a371f7','#39c5cf']; |
| 115 | async function api(path, opts){ |
| 116 | const r = await fetch(path, opts); |
| 117 | return r.json(); |
| 118 | } |
| 119 | async function refreshAccount(){ |
| 120 | const a = await api('/api/account'); |
| 121 | const badge = document.getElementById('conn'); |
| 122 | if(a.connected){ |
| 123 | badge.textContent = 'connected #' + a.login; |
| 124 | badge.className = 'badge on'; |
| 125 | document.getElementById('acct').textContent = |
| 126 | a.server + ' Bal ' + Number(a.balance).toFixed(2) + ' ' + a.currency + |
| 127 | ' Eq ' + Number(a.equity).toFixed(2); |
| 128 | } else { |
| 129 | badge.textContent = 'disconnected'; |
| 130 | badge.className = 'badge off'; |
| 131 | document.getElementById('acct').textContent = a.error || ''; |
| 132 | } |
| 133 | } |
| 134 | async function refreshPositions(){ |
| 135 | const rows = await api('/api/positions'); |
| 136 | const tb = document.getElementById('positions'); |
| 137 | if(!rows.length){ tb.innerHTML = '<tr><td colspan="7">no open positions</td></tr>'; return; } |
| 138 | tb.innerHTML = rows.map(p => { |
| 139 | const cls = p.profit >= 0 ? 'pos' : 'neg'; |
| 140 | return '<tr><td>'+p.ticket+'</td><td>'+p.symbol+'</td><td>'+p.side+'</td>' + |
| 141 | '<td>'+p.volume+'</td><td>'+p.price_open+'</td><td>'+p.price_current+'</td>' + |
| 142 | '<td class="'+cls+'">'+Number(p.profit).toFixed(2)+'</td></tr>'; |
| 143 | }).join(''); |
| 144 | } |
| 145 | async function loadAnalysis(){ |
| 146 | const q = new URLSearchParams({ symbol: v('symbol'), strategy: v('strategy'), |
| 147 | source: v('source'), period: v('period') }); |
| 148 | const d = await api('/api/analysis?' + q); |
| 149 | if(d.error){ alert(d.error); return; } |
| 150 | const m = d.metrics; |
| 151 | const rc = m.total_return >= 0 ? 'pos' : 'neg'; |
| 152 | document.getElementById('metrics').innerHTML = |
| 153 | metric('Total Return', (m.total_return*100).toFixed(2)+'%', rc) + |
| 154 | metric('Sharpe', m.sharpe_ratio.toFixed(2), '') + |
| 155 | metric('Max Drawdown', (m.max_drawdown*100).toFixed(2)+'%', 'neg') + |
| 156 | metric('Trades', m.num_trades, '') + |
| 157 | metric('Win Rate', (m.win_rate*100).toFixed(1)+'%', ''); |
| 158 | const ds = [{ label:'Close', data:d.close, borderColor:'#e6edf3', |
| 159 | pointRadius:0, borderWidth:1.5 }]; |
| 160 | Object.keys(d.overlays).forEach((k,i) => ds.push({ label:k, data:d.overlays[k], |
| 161 | borderColor:OVERLAY_COLORS[i%OVERLAY_COLORS.length], pointRadius:0, borderWidth:1 })); |
| 162 | ds.push({ label:'Buy', data:d.markers.filter(x=>x.side==='buy').map(x=>({x:x.t,y:x.price})), |
| 163 | backgroundColor:'#3fb950', pointStyle:'triangle', rotation:0, radius:6, type:'scatter' }); |
| 164 | ds.push({ label:'Sell', data:d.markers.filter(x=>x.side==='sell').map(x=>({x:x.t,y:x.price})), |
| 165 | backgroundColor:'#f85149', pointStyle:'triangle', rotation:180, radius:6, type:'scatter' }); |
| 166 | if(priceChart) priceChart.destroy(); |
| 167 | priceChart = new Chart(document.getElementById('price'), |
| 168 | { type:'line', data:{ labels:d.labels, datasets:ds }, |
| 169 | options:{ animation:false, scales:{ x:{ ticks:{ maxTicksLimit:8 } } } } }); |
| 170 | if(equityChart) equityChart.destroy(); |
| 171 | equityChart = new Chart(document.getElementById('equity'), |
| 172 | { type:'line', data:{ labels:d.equity.labels, |
| 173 | datasets:[{ label:'Equity', data:d.equity.values, borderColor:'#3fb950', |
| 174 | pointRadius:0, borderWidth:1.5 }] }, |
| 175 | options:{ animation:false, scales:{ x:{ ticks:{ maxTicksLimit:8 } } } } }); |
| 176 | } |
| 177 | function metric(k,val,cls){ return '<div class="metric"><div class="k">'+k+'</div>' + |
| 178 | '<div class="v '+cls+'">'+val+'</div></div>'; } |
| 179 | function v(id){ return document.getElementById(id).value; } |
| 180 | async function sendOrder(){ |
| 181 | const body = { symbol:v('oSym'), side:v('oSide'), volume:parseFloat(v('oVol')), |
| 182 | sl:parseFloat(v('oSL'))||0, tp:parseFloat(v('oTP'))||0, live:v('oLive')==='yes' }; |
| 183 | if(body.live && !confirm('Place REAL order: '+body.side+' '+body.volume+ |
| 184 | ' '+body.symbol+'?')) return; |
| 185 | const r = await api('/api/order', { method:'POST', |
| 186 | headers:{'Content-Type':'application/json'}, body:JSON.stringify(body) }); |
| 187 | const el = document.getElementById('msg'); |
| 188 | el.textContent = r.message; |
| 189 | el.style.color = r.ok ? '#3fb950' : '#f85149'; |
| 190 | refreshPositions(); |
| 191 | } |
| 192 | refreshAccount(); refreshPositions(); loadAnalysis(); |
| 193 | setInterval(refreshAccount, 5000); setInterval(refreshPositions, 5000); |
| 194 | </script> |
| 195 | </body> |
| 196 | </html> |
| 197 | """ |
| 198 | |
| 199 | |
| 200 | def create_dashboard_app() -> Any: |
| 201 | """Create the Flask dashboard app (Flask imported lazily).""" |
| 202 | try: |
| 203 | from flask import Flask, jsonify, request |
| 204 | except ImportError as exc: |
| 205 | raise RuntimeError( |
| 206 | "Flask is not installed. Run: pip install -e '.[web]'" |
| 207 | ) from exc |
| 208 | |
| 209 | app = Flask(__name__) |
| 210 | |
| 211 | @app.route("/") # type: ignore[untyped-decorator] |
| 212 | def index() -> Any: |
| 213 | return INDEX_HTML |
| 214 | |
| 215 | @app.route("/api/account") # type: ignore[untyped-decorator] |
| 216 | def api_account() -> Any: |
| 217 | from open_alice.broker import load_credentials |
| 218 | from open_alice.broker.mt5 import MT5Broker |
| 219 | |
| 220 | saved = load_credentials() |
| 221 | if saved is None: |
| 222 | return jsonify({"connected": False, "error": "no saved login (alice broker login)"}) |
| 223 | broker = MT5Broker( |
| 224 | login=int(saved["login"]), password=saved["password"], server=saved["server"] |
| 225 | ) |
| 226 | try: |
| 227 | if not broker.connect(): |
| 228 | return jsonify({"connected": False, "error": "MT5 connect failed"}) |
| 229 | info = broker.get_account_info() |
| 230 | return jsonify( |
| 231 | { |
| 232 | "connected": True, |
| 233 | "login": info.login, |
| 234 | "server": saved["server"], |
| 235 | "balance": info.balance, |
| 236 | "equity": info.equity, |
| 237 | "margin": info.margin, |
| 238 | "free_margin": info.free_margin, |
| 239 | "currency": info.currency, |
| 240 | "leverage": info.leverage, |
| 241 | } |
| 242 | ) |
| 243 | except RuntimeError as exc: |
| 244 | return jsonify({"connected": False, "error": str(exc)}) |
| 245 | finally: |
| 246 | if broker.connected: |
| 247 | broker.disconnect() |
| 248 | |
| 249 | @app.route("/api/positions") # type: ignore[untyped-decorator] |
| 250 | def api_positions() -> Any: |
| 251 | from open_alice.broker import load_credentials |
| 252 | from open_alice.broker.mt5 import MT5Broker |
| 253 | |
| 254 | saved = load_credentials() |
| 255 | if saved is None: |
| 256 | return jsonify([]) |
| 257 | broker = MT5Broker( |
| 258 | login=int(saved["login"]), password=saved["password"], server=saved["server"] |
| 259 | ) |
| 260 | try: |
| 261 | if not broker.connect(): |
| 262 | return jsonify([]) |
| 263 | return jsonify( |
| 264 | [ |
| 265 | { |
| 266 | "ticket": p.ticket, |
| 267 | "symbol": p.symbol, |
| 268 | "side": "BUY" if p.type == 0 else "SELL", |
| 269 | "volume": p.volume, |
| 270 | "price_open": p.price_open, |
| 271 | "price_current": p.price_current, |
| 272 | "profit": p.profit, |
| 273 | } |
| 274 | for p in broker.get_positions() |
| 275 | ] |
| 276 | ) |
| 277 | except RuntimeError: |
| 278 | return jsonify([]) |
| 279 | finally: |
| 280 | if broker.connected: |
| 281 | broker.disconnect() |
| 282 | |
| 283 | @app.route("/api/analysis") # type: ignore[untyped-decorator] |
| 284 | def api_analysis() -> Any: |
| 285 | from open_alice.dashboard.charts import chart_payload |
| 286 | from open_alice.data import add_returns, fetch_ohlcv |
| 287 | |
| 288 | symbol = str(request.args.get("symbol", "AAPL")) |
| 289 | strategy = str(request.args.get("strategy", "sma_crossover")) |
| 290 | source = str(request.args.get("source", "yahoo")) |
| 291 | period = str(request.args.get("period", "1y")) |
| 292 | if strategy not in ("sma_crossover", "rsi", "macd", "bollinger"): |
| 293 | return jsonify({"error": f"unknown strategy: {strategy}"}), 400 |
| 294 | try: |
| 295 | df = _mt5_frame(symbol) if source == "mt5" else fetch_ohlcv(symbol, period=period) |
| 296 | df = add_returns(df) |
| 297 | return jsonify(chart_payload(df, strategy)) |
| 298 | except Exception as exc: |
| 299 | return jsonify({"error": str(exc)}), 500 |
| 300 | |
| 301 | @app.route("/api/order", methods=["POST"]) # type: ignore[untyped-decorator] |
| 302 | def api_order() -> Any: |
| 303 | from open_alice.broker import load_credentials |
| 304 | from open_alice.broker.mt5 import MT5Broker |
| 305 | |
| 306 | data = request.get_json(force=True, silent=True) or {} |
| 307 | symbol = str(data.get("symbol", "")).strip().upper() |
| 308 | side = str(data.get("side", "")).strip().lower() |
| 309 | try: |
| 310 | volume = float(data.get("volume", 0)) |
| 311 | except (TypeError, ValueError): |
| 312 | return jsonify({"ok": False, "message": "invalid volume"}), 400 |
| 313 | sl = float(data.get("sl") or 0.0) |
| 314 | tp = float(data.get("tp") or 0.0) |
| 315 | live = bool(data.get("live", False)) |
| 316 | if not symbol or side not in ("buy", "sell") or volume <= 0: |
| 317 | return jsonify({"ok": False, "message": "need symbol, side buy/sell, volume > 0"}), 400 |
| 318 | if not live: |
| 319 | return jsonify( |
| 320 | { |
| 321 | "ok": True, |
| 322 | "message": f"DRY RUN: {side} {volume} {symbol} " |
| 323 | f"(SL={sl} TP={tp}). Tick LIVE to send.", |
| 324 | } |
| 325 | ) |
| 326 | saved = load_credentials() |
| 327 | if saved is None: |
| 328 | return jsonify({"ok": False, "message": "no saved MT5 login"}), 400 |
| 329 | broker = MT5Broker( |
| 330 | login=int(saved["login"]), password=saved["password"], server=saved["server"] |
| 331 | ) |
| 332 | try: |
| 333 | if not broker.connect(): |
| 334 | return jsonify({"ok": False, "message": "MT5 connect failed"}), 500 |
| 335 | ok = broker.buy(symbol, volume, sl, tp) if side == "buy" else broker.sell( |
| 336 | symbol, volume, sl, tp |
| 337 | ) |
| 338 | msg = f"LIVE {side} {volume} {symbol} sent." if ok else "order rejected by MT5" |
| 339 | return jsonify({"ok": ok, "message": msg}) |
| 340 | except RuntimeError as exc: |
| 341 | return jsonify({"ok": False, "message": str(exc)}), 500 |
| 342 | finally: |
| 343 | if broker.connected: |
| 344 | broker.disconnect() |
| 345 | |
| 346 | return app |
| 347 | |
| 348 | |
| 349 | def _mt5_frame(symbol: str, count: int = 500) -> Any: |
| 350 | """Fetch recent daily bars from MT5 using saved credentials.""" |
| 351 | from typing import Any as _Any |
| 352 | |
| 353 | mt5: _Any = __import__("MetaTrader5") |
| 354 | from open_alice.broker import load_credentials |
| 355 | from open_alice.broker.mt5 import MT5Broker |
| 356 | from open_alice.data import add_returns |
| 357 | |
| 358 | saved = load_credentials() |
| 359 | if saved is None: |
| 360 | raise RuntimeError("no saved MT5 login (run: alice broker login)") |
| 361 | broker = MT5Broker( |
| 362 | login=int(saved["login"]), password=saved["password"], server=saved["server"] |
| 363 | ) |
| 364 | try: |
| 365 | if not broker.connect(): |
| 366 | raise RuntimeError("MT5 connect failed") |
| 367 | return add_returns(broker.get_rates(symbol, mt5.TIMEFRAME_D1, count)) |
| 368 | finally: |
| 369 | if broker.connected: |
| 370 | broker.disconnect() |