Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
Add web dashboard: account, charts, positions, order ticket
Camo67 committed
Oct 12, 2026 at 19:08 UTC
624e034c979cf4e5c0be18f60487f8f5672e77d7
6 files changed
+571
README.md
+9
@@ -9,6 +9,7 @@
9
- **Risk management** — position sizing, stop-loss, take-profit
10
- **Paper trading** — test without real money
11
- **Live trading** — connect to MetaTrader 5 for execution
12
+- **Web dashboard** — account, charts, positions and order ticket in your browser
13
- **Signal integration** — receive signals from TradingView and other platforms via webhooks
14
- **CLI interface** — simple command-line controls
15
@@ -32,6 +33,10 @@ alice live --symbol EURUSD --strategy sma_crossover --login 12345678 --password
33
34
# Start webhook server for signals (e.g., from TradingView)
35
alice serve --host 0.0.0.0 --port 5000
36
+
37
+# Start the web dashboard (needs Flask: pip install -e ".[web]")
38
+alice dashboard
39
+# then open http://127.0.0.1:8080
40
```
41
42
## Project Structure
@@ -46,6 +51,10 @@ open-alice/
51
│ │ ├── __init__.py
52
│ │ └── mt5.py # MetaTrader 5 integration
53
│ ├── cli.py # CLI entry point
54
+│ ├── dashboard/ # Web dashboard (Flask + Chart.js)
55
+│ │ ├── __init__.py
56
+│ │ ├── app.py # Routes + page (account, chart, orders API)
57
+│ │ └── charts.py # Strategy output -> chart JSON
58
│ ├── data.py # Market data fetching
59
│ ├── engine/ # Backtesting & execution engine
60
│ ├── signals/ # Signal reception
src/open_alice/cli.py
+26
@@ -94,6 +94,11 @@ def main() -> None:
94
webhook.add_argument("--port", type=int, default=5000, help="Port to bind to")
95
webhook.add_argument("--secret", type=str, help="Secret for request validation")
96
97
+ # Dashboard command
98
+ dash = subparsers.add_parser("dashboard", help="Start the web dashboard")
99
+ dash.add_argument("--host", default="127.0.0.1", help="Host to bind to")
100
+ dash.add_argument("--port", type=int, default=8080, help="Port to bind to")
101
+
102
args = parser.parse_args()
103
104
if args.command == "backtest":
@@ -106,6 +111,8 @@ def main() -> None:
111
_run_broker(args)
112
elif args.command == "serve":
113
_run_webhook(args)
114
+ elif args.command == "dashboard":
115
+ _run_dashboard(args)
116
117
118
def _build_strategy(name: str, args: argparse.Namespace) -> Strategy:
@@ -495,5 +502,24 @@ def _run_webhook(args: argparse.Namespace) -> None:
502
print("\nShutting down webhook server...")
503
504
505
+def _run_dashboard(args: argparse.Namespace) -> None:
506
+ print(f"\n{'='*60}")
507
+ print(" Alice Dashboard")
508
+ print(f" Open: http://{args.host}:{args.port}")
509
+ print(f"{'='*60}\n")
510
+
511
+ try:
512
+ from open_alice.dashboard.app import create_dashboard_app
513
+ except RuntimeError as exc:
514
+ print(f"Error: {exc}")
515
+ sys.exit(1)
516
+
517
+ app = create_dashboard_app()
518
+ try:
519
+ app.run(host=args.host, port=args.port, debug=False)
520
+ except KeyboardInterrupt:
521
+ print("\nShutting down dashboard...")
522
+
523
+
524
if __name__ == "__main__":
525
main()
src/open_alice/dashboard/__init__.py
new
+6
@@ -0,0 +1,6 @@
1
+"""Web dashboard for Alice (account, charts, positions, order ticket)."""
2
+
3
+from open_alice.dashboard.app import create_dashboard_app
4
+from open_alice.dashboard.charts import build_strategy, chart_payload
5
+
6
+__all__ = ["create_dashboard_app", "build_strategy", "chart_payload"]
src/open_alice/dashboard/app.py
new
+373
@@ -0,0 +1,373 @@
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
+ if source == "mt5":
296
+ df = _mt5_frame(symbol)
297
+ else:
298
+ df = fetch_ohlcv(symbol, period=period)
299
+ df = add_returns(df)
300
+ return jsonify(chart_payload(df, strategy))
301
+ except Exception as exc:
302
+ return jsonify({"error": str(exc)}), 500
303
+
304
+ @app.route("/api/order", methods=["POST"]) # type: ignore[untyped-decorator]
305
+ def api_order() -> Any:
306
+ from open_alice.broker import load_credentials
307
+ from open_alice.broker.mt5 import MT5Broker
308
+
309
+ data = request.get_json(force=True, silent=True) or {}
310
+ symbol = str(data.get("symbol", "")).strip().upper()
311
+ side = str(data.get("side", "")).strip().lower()
312
+ try:
313
+ volume = float(data.get("volume", 0))
314
+ except (TypeError, ValueError):
315
+ return jsonify({"ok": False, "message": "invalid volume"}), 400
316
+ sl = float(data.get("sl") or 0.0)
317
+ tp = float(data.get("tp") or 0.0)
318
+ live = bool(data.get("live", False))
319
+ if not symbol or side not in ("buy", "sell") or volume <= 0:
320
+ return jsonify({"ok": False, "message": "need symbol, side buy/sell, volume > 0"}), 400
321
+ if not live:
322
+ return jsonify(
323
+ {
324
+ "ok": True,
325
+ "message": f"DRY RUN: {side} {volume} {symbol} "
326
+ f"(SL={sl} TP={tp}). Tick LIVE to send.",
327
+ }
328
+ )
329
+ saved = load_credentials()
330
+ if saved is None:
331
+ return jsonify({"ok": False, "message": "no saved MT5 login"}), 400
332
+ broker = MT5Broker(
333
+ login=int(saved["login"]), password=saved["password"], server=saved["server"]
334
+ )
335
+ try:
336
+ if not broker.connect():
337
+ return jsonify({"ok": False, "message": "MT5 connect failed"}), 500
338
+ ok = broker.buy(symbol, volume, sl, tp) if side == "buy" else broker.sell(
339
+ symbol, volume, sl, tp
340
+ )
341
+ msg = f"LIVE {side} {volume} {symbol} sent." if ok else "order rejected by MT5"
342
+ return jsonify({"ok": ok, "message": msg})
343
+ except RuntimeError as exc:
344
+ return jsonify({"ok": False, "message": str(exc)}), 500
345
+ finally:
346
+ if broker.connected:
347
+ broker.disconnect()
348
+
349
+ return app
350
+
351
+
352
+def _mt5_frame(symbol: str, count: int = 500) -> Any:
353
+ """Fetch recent daily bars from MT5 using saved credentials."""
354
+ from typing import Any as _Any
355
+
356
+ mt5: _Any = __import__("MetaTrader5")
357
+ from open_alice.broker import load_credentials
358
+ from open_alice.broker.mt5 import MT5Broker
359
+ from open_alice.data import add_returns
360
+
361
+ saved = load_credentials()
362
+ if saved is None:
363
+ raise RuntimeError("no saved MT5 login (run: alice broker login)")
364
+ broker = MT5Broker(
365
+ login=int(saved["login"]), password=saved["password"], server=saved["server"]
366
+ )
367
+ try:
368
+ if not broker.connect():
369
+ raise RuntimeError("MT5 connect failed")
370
+ return add_returns(broker.get_rates(symbol, mt5.TIMEFRAME_D1, count))
371
+ finally:
372
+ if broker.connected:
373
+ broker.disconnect()
src/open_alice/dashboard/charts.py
new
+107
@@ -0,0 +1,107 @@
1
+"""Pure helpers that turn strategy output into dashboard JSON payloads."""
2
+
3
+from __future__ import annotations
4
+
5
+from typing import Any
6
+
7
+import pandas as pd
8
+
9
+from open_alice.engine import run_backtest
10
+from open_alice.strategies import (
11
+ BollingerStrategy,
12
+ MacdStrategy,
13
+ RsiStrategy,
14
+ SmaCrossover,
15
+ Strategy,
16
+)
17
+
18
+_OVERLAY_COLUMNS: dict[str, list[str]] = {
19
+ "sma_crossover": ["SMA_fast", "SMA_slow"],
20
+ "rsi": ["RSI"],
21
+ "macd": ["MACD", "MACD_Signal"],
22
+ "bollinger": ["BB_Upper", "BB_Mid", "BB_Lower"],
23
+}
24
+
25
+
26
+def build_strategy(name: str, fast: int = 20, slow: int = 50) -> Strategy:
27
+ """Build a strategy instance by name."""
28
+ if name == "sma_crossover":
29
+ return SmaCrossover(fast=fast, slow=slow)
30
+ factories: dict[str, type[Strategy]] = {
31
+ "rsi": RsiStrategy,
32
+ "macd": MacdStrategy,
33
+ "bollinger": BollingerStrategy,
34
+ }
35
+ return factories[name]()
36
+
37
+
38
+def chart_payload(
39
+ df: pd.DataFrame,
40
+ strategy_name: str,
41
+ fast: int = 20,
42
+ slow: int = 50,
43
+ max_points: int = 300,
44
+) -> dict[str, Any]:
45
+ """Run a strategy + backtest and return a JSON-serializable chart payload.
46
+
47
+ Args:
48
+ df: OHLCV DataFrame with a Returns column (see data.add_returns).
49
+ strategy_name: One of sma_crossover, rsi, macd, bollinger.
50
+ fast: Fast SMA period (sma_crossover only).
51
+ slow: Slow SMA period (sma_crossover only).
52
+ max_points: Downsample to at most this many chart points.
53
+
54
+ Returns:
55
+ Dict with labels, close, overlays, markers, equity and metrics.
56
+ """
57
+ strategy = build_strategy(strategy_name, fast=fast, slow=slow)
58
+ framed = strategy.generate_signals(df)
59
+ if len(framed) > max_points:
60
+ step = len(framed) // max_points + 1
61
+ framed = framed.iloc[::step]
62
+
63
+ result = run_backtest(framed)
64
+
65
+ labels = [_label(ts) for ts in framed.index]
66
+ payload: dict[str, Any] = {
67
+ "labels": labels,
68
+ "close": [float(v) for v in framed["Close"].tolist()],
69
+ "overlays": {
70
+ col: [None if pd.isna(v) else float(v) for v in framed[col].tolist()]
71
+ for col in _OVERLAY_COLUMNS[strategy_name]
72
+ if col in framed.columns
73
+ },
74
+ "markers": _signal_markers(framed),
75
+ "equity": {
76
+ "labels": labels,
77
+ "values": [float(v) for v in result.equity_curve.tolist()],
78
+ },
79
+ "metrics": {
80
+ "total_return": result.total_return,
81
+ "sharpe_ratio": result.sharpe_ratio,
82
+ "max_drawdown": result.max_drawdown,
83
+ "num_trades": result.num_trades,
84
+ "win_rate": result.win_rate,
85
+ },
86
+ }
87
+ return payload
88
+
89
+
90
+def _label(ts: Any) -> str:
91
+ if hasattr(ts, "isoformat"):
92
+ return str(ts.isoformat())
93
+ return str(ts)
94
+
95
+
96
+def _signal_markers(framed: pd.DataFrame) -> list[dict[str, Any]]:
97
+ """Extract fresh buy/sell markers from Signal/Position columns."""
98
+ if "Signal" not in framed.columns:
99
+ return []
100
+ sig = framed["Signal"]
101
+ prev = sig.shift(1).fillna(0)
102
+ markers: list[dict[str, Any]] = []
103
+ for ts, row in framed[(sig == 1) & (prev != 1)].iterrows():
104
+ markers.append({"t": _label(ts), "price": float(row["Close"]), "side": "buy"})
105
+ for ts, row in framed[(sig == -1) & (prev != -1)].iterrows():
106
+ markers.append({"t": _label(ts), "price": float(row["Close"]), "side": "sell"})
107
+ return markers
tests/test_dashboard.py
new
+50
@@ -0,0 +1,50 @@
1
+"""Tests for dashboard chart payloads (no Flask/MT5 required)."""
2
+
3
+import pandas as pd
4
+import pytest
5
+
6
+from open_alice.dashboard.charts import build_strategy, chart_payload
7
+from open_alice.data import add_returns
8
+
9
+
10
+@pytest.fixture
11
+def sample_ohlcv() -> pd.DataFrame:
12
+ dates = pd.date_range("2024-01-01", periods=120, freq="D")
13
+ prices = pd.Series([100.0] * 60 + [200.0] * 60, index=dates)
14
+ df = pd.DataFrame(
15
+ {
16
+ "Open": prices,
17
+ "High": prices + 1,
18
+ "Low": prices - 1,
19
+ "Close": prices,
20
+ "Volume": 1000,
21
+ }
22
+ )
23
+ return add_returns(df)
24
+
25
+
26
+def test_build_strategy_names() -> None:
27
+ for name in ("sma_crossover", "rsi", "macd", "bollinger"):
28
+ assert build_strategy(name) is not None
29
+
30
+
31
+def test_chart_payload_sma(sample_ohlcv: pd.DataFrame) -> None:
32
+ payload = chart_payload(sample_ohlcv, "sma_crossover", fast=5, slow=10)
33
+ assert len(payload["labels"]) == len(payload["close"])
34
+ assert "SMA_fast" in payload["overlays"]
35
+ assert "SMA_slow" in payload["overlays"]
36
+ assert payload["metrics"]["num_trades"] >= 0
37
+ assert len(payload["equity"]["values"]) == len(payload["labels"])
38
+
39
+
40
+def test_chart_payload_all_strategies(sample_ohlcv: pd.DataFrame) -> None:
41
+ for name in ("sma_crossover", "rsi", "macd", "bollinger"):
42
+ payload = chart_payload(sample_ohlcv, name)
43
+ assert payload["labels"]
44
+ assert payload["metrics"]["win_rate"] >= 0
45
+ assert isinstance(payload["markers"], list)
46
+
47
+
48
+def test_chart_payload_downsamples(sample_ohlcv: pd.DataFrame) -> None:
49
+ payload = chart_payload(sample_ohlcv, "rsi", max_points=20)
50
+ assert len(payload["labels"]) <= 20