Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro

fix/nan-prices-cli-demo-mode
py 525 lines 20.2 KB
Raw
1 """CLI interface for open-alice."""
2
3 from __future__ import annotations
4
5 import argparse
6 import getpass
7 import sys
8
9 from open_alice.broker import (
10 clear_credentials,
11 get_credentials_path,
12 list_headway_servers,
13 load_credentials,
14 resolve_headway_server,
15 save_credentials,
16 )
17 from open_alice.broker.mt5 import MT5Broker
18 from open_alice.data import add_returns, fetch_ohlcv
19 from open_alice.engine import run_backtest, run_paper
20 from open_alice.signals.webhook import TradingViewSignalReceiver, create_webhook_app
21 from open_alice.strategies import (
22 BollingerStrategy,
23 MacdStrategy,
24 RsiStrategy,
25 SmaCrossover,
26 Strategy,
27 )
28
29 STRATEGIES: dict[str, type[Strategy]] = {
30 "sma_crossover": SmaCrossover,
31 "rsi": RsiStrategy,
32 "macd": MacdStrategy,
33 "bollinger": BollingerStrategy,
34 }
35
36
37 def main() -> None:
38 parser = argparse.ArgumentParser(
39 prog="alice",
40 description="Alice — an open-source AI trading bot",
41 )
42 subparsers = parser.add_subparsers(dest="command", required=True)
43
44 # Backtest command
45 bt = subparsers.add_parser("backtest", help="Run a backtest")
46 bt.add_argument("--symbol", default="AAPL", help="Ticker symbol")
47 bt.add_argument("--strategy", default="sma_crossover", choices=STRATEGIES.keys())
48 bt.add_argument("--period", default="1y", help="Data period")
49 bt.add_argument("--capital", type=float, default=100_000, help="Initial capital")
50 bt.add_argument("--fast", type=int, default=20, help="Fast SMA period")
51 bt.add_argument("--slow", type=int, default=50, help="Slow SMA period")
52 bt.add_argument("--use-mt5", action="store_true", help="Use MT5 for data")
53
54 # Paper trading command
55 paper = subparsers.add_parser("paper", help="Run paper trading simulation")
56 paper.add_argument("--symbol", default="AAPL", help="Ticker symbol")
57 paper.add_argument("--strategy", default="sma_crossover", choices=STRATEGIES.keys())
58 paper.add_argument("--period", default="1y", help="Data period")
59 paper.add_argument("--capital", type=float, default=100_000, help="Initial capital")
60 paper.add_argument("--risk", type=float, default=0.02, help="Risk per trade")
61 paper.add_argument("--use-mt5", action="store_true", help="Use MT5 for data")
62
63 # Live trading command (Headway via MT5)
64 live = subparsers.add_parser("live", help="Run live trading with MT5/Headway")
65 live.add_argument("--symbol", default="EURUSD", help="Ticker symbol")
66 live.add_argument("--strategy", default="sma_crossover", choices=STRATEGIES.keys())
67 live.add_argument("--fast", type=int, default=20, help="Fast SMA period")
68 live.add_argument("--slow", type=int, default=50, help="Slow SMA period")
69 live.add_argument("--login", type=int, help="MT5 login (defaults to saved)")
70 live.add_argument("--password", type=str, help="MT5 password (defaults to saved)")
71 live.add_argument("--server", type=str, help="MT5 server (defaults to saved)")
72 live.add_argument("--demo", action="store_true", help="Use Headway demo server")
73 live.add_argument("--risk", type=float, default=0.02, help="Risk per trade")
74 live.add_argument("--interval", type=int, default=60, help="Check interval (seconds)")
75 live.add_argument("--execute", action="store_true", help="Actually place orders")
76 live.add_argument("--yes", action="store_true", help="Skip the live-orders confirmation")
77
78 # Broker account management (Headway via MT5)
79 broker = subparsers.add_parser("broker", help="Manage MT5 / Headway login")
80 broker_sub = broker.add_subparsers(dest="broker_command", required=True)
81
82 b_login = broker_sub.add_parser("login", help="Save Headway MT5 credentials")
83 b_login.add_argument("--login", type=int, help="MT5 account number")
84 b_login.add_argument("--server", type=str, help="MT5 server or 'demo'/'real'")
85 b_login.add_argument("--demo", action="store_true", help="Shortcut for Headway demo")
86 b_login.add_argument("--terminal-path", type=str, help="Path to terminal64.exe")
87
88 broker_sub.add_parser("status", help="Show saved login and test connection")
89 broker_sub.add_parser("logout", help="Delete saved MT5 credentials")
90
91 # Webhook server command
92 webhook = subparsers.add_parser("serve", help="Start webhook server for signals")
93 webhook.add_argument("--host", default="0.0.0.0", help="Host to bind to")
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":
105 _run_backtest(args)
106 elif args.command == "paper":
107 _run_paper(args)
108 elif args.command == "live":
109 _run_live(args)
110 elif args.command == "broker":
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:
119 if name == "sma_crossover":
120 fast = int(getattr(args, "fast", 20))
121 slow = int(getattr(args, "slow", 50))
122 return SmaCrossover(fast=fast, slow=slow)
123 factory = STRATEGIES[name]
124 return factory()
125
126
127 def _mt5_login_from_args(args: argparse.Namespace) -> tuple[int | None, str | None, str | None]:
128 """Resolve MT5 credentials from flags, then saved file, then env."""
129 login = getattr(args, "login", None)
130 password = getattr(args, "password", None)
131 server = getattr(args, "server", None)
132 if login is not None and password is not None and server is not None:
133 return int(login), str(password), str(server)
134 saved = load_credentials()
135 if saved is not None:
136 return int(saved["login"]), saved["password"], saved["server"]
137 return None, None, None
138
139
140 def _run_backtest(args: argparse.Namespace) -> None:
141 use_mt5 = bool(getattr(args, "use_mt5", False))
142 print(f"\n{'='*60}")
143 print(f" Alice Backtest — {args.symbol}")
144 print(f" Strategy: {args.strategy} | Period: {args.period} | Capital: ${args.capital:,.0f}")
145 print(f" Data Source: {'MT5' if use_mt5 else 'Yahoo Finance'}")
146 print(f"{'='*60}\n")
147
148 if use_mt5:
149 import datetime
150
151 login, password, server = _mt5_login_from_args(args)
152 broker = MT5Broker(login=login, password=password, server=server)
153 try:
154 if broker.connect():
155 end_date = datetime.datetime.now()
156 start_date = end_date - datetime.timedelta(days=365)
157 df = broker.get_historical_data(args.symbol, "1D", start_date, end_date)
158 broker.disconnect()
159 if df.empty:
160 print("Warning: MT5 returned no data, falling back to Yahoo Finance")
161 df = fetch_ohlcv(args.symbol, period=args.period)
162 else:
163 print("Warning: MT5 connect failed, falling back to Yahoo Finance")
164 df = fetch_ohlcv(args.symbol, period=args.period)
165 except Exception as exc:
166 print(f"Warning: MT5 error ({exc}), falling back to Yahoo Finance")
167 df = fetch_ohlcv(args.symbol, period=args.period)
168 else:
169 df = fetch_ohlcv(args.symbol, period=args.period)
170
171 df = add_returns(df)
172
173 strategy = _build_strategy(args.strategy, args)
174 df = strategy.generate_signals(df)
175
176 result = run_backtest(df, initial_capital=args.capital)
177
178 print(f" Total Return: {result.total_return:>10.2%}")
179 print(f" Sharpe Ratio: {result.sharpe_ratio:>10.2f}")
180 print(f" Max Drawdown: {result.max_drawdown:>10.2%}")
181 print(f" Num Trades: {result.num_trades:>10d}")
182 print(f" Win Rate: {result.win_rate:>10.2%}")
183 print(f"\n{'='*60}\n")
184
185
186 def _run_paper(args: argparse.Namespace) -> None:
187 use_mt5 = bool(getattr(args, "use_mt5", False))
188 print(f"\n{'='*60}")
189 print(f" Alice Paper Trading — {args.symbol}")
190 print(f" Strategy: {args.strategy} | Period: {args.period} | Capital: ${args.capital:,.0f}")
191 print(f" Data Source: {'MT5' if use_mt5 else 'Yahoo Finance'}")
192 print(f"{'='*60}\n")
193
194 if use_mt5:
195 login, password, server = _mt5_login_from_args(args)
196 broker = MT5Broker(login=login, password=password, server=server)
197 try:
198 from typing import Any
199
200 mt5: Any = __import__("MetaTrader5")
201 if broker.connect():
202 df = broker.get_rates(args.symbol, mt5.TIMEFRAME_D1, 100)
203 broker.disconnect()
204 if df.empty:
205 print("Warning: MT5 returned no data, falling back to Yahoo Finance")
206 df = fetch_ohlcv(args.symbol, period=args.period)
207 else:
208 print("Warning: MT5 connect failed, falling back to Yahoo Finance")
209 df = fetch_ohlcv(args.symbol, period=args.period)
210 except Exception as exc:
211 print(f"Warning: MT5 error ({exc}), falling back to Yahoo Finance")
212 df = fetch_ohlcv(args.symbol, period=args.period)
213 else:
214 df = fetch_ohlcv(args.symbol, period=args.period)
215
216 df = add_returns(df)
217
218 strategy = _build_strategy(args.strategy, args)
219 portfolio = run_paper(
220 df,
221 strategy,
222 args.symbol,
223 initial_capital=args.capital,
224 risk_per_trade=args.risk,
225 )
226
227 print(f" Final Equity: ${portfolio.equity:>10,.2f}")
228 print(f" Cash Remaining: ${portfolio.cash:>10,.2f}")
229 print(f" Total Trades: {len(portfolio.trades):>10d}")
230
231 if portfolio.trades:
232 total_pnl = sum(t.pnl or 0.0 for t in portfolio.trades)
233 print(f" Total P&L: ${total_pnl:>10,.2f}")
234
235 print("\n --- Trade Log ---")
236 for t in portfolio.trades[:20]:
237 pnl_str = f" P&L: ${t.pnl:,.2f}" if t.pnl is not None else ""
238 print(
239 f" {t.time.strftime('%Y-%m-%d %H:%M')} | {t.action:>4} | "
240 f"{t.symbol:>6} | {t.shares:>6} @ "
241 f"${t.price:>8.2f}{pnl_str}"
242 )
243
244 if len(portfolio.trades) > 20:
245 print(f" ... and {len(portfolio.trades) - 20} more trades")
246
247 print(f"\n{'='*60}\n")
248
249
250 def _run_broker(args: argparse.Namespace) -> None:
251 action = getattr(args, "broker_command", None)
252 if action == "login":
253 _broker_login(args)
254 elif action == "status":
255 _broker_status()
256 elif action == "logout":
257 if clear_credentials():
258 print("Saved MT5 credentials deleted.")
259 else:
260 print("No saved MT5 credentials found.")
261
262
263 def _broker_login(args: argparse.Namespace) -> None:
264 servers = list_headway_servers()
265 print("\n Headway MT5 servers:")
266 print(f" Demo: {', '.join(servers['demo'])}")
267 print(f" Real: {', '.join(servers['real'])}")
268 print(" Tip: install MT5 from Headway so these servers are preloaded.\n")
269
270 raw_login = getattr(args, "login", None)
271 if raw_login is None:
272 entered = input(" MT5 login (account number): ").strip()
273 if not entered:
274 print(" Login cancelled.")
275 return
276 raw_login = int(entered)
277
278 raw_server = getattr(args, "server", None)
279 demo = bool(getattr(args, "demo", False))
280 if raw_server is None and not demo:
281 entered = input(" MT5 server [Headway-Demo / Headway-Real]: ").strip()
282 raw_server = entered or None
283 server = resolve_headway_server(raw_server, demo=demo)
284
285 password = getpass.getpass(f" MT5 password for {raw_login} on {server}: ")
286 if not password:
287 print(" Login cancelled (empty password).")
288 return
289
290 terminal_path = getattr(args, "terminal_path", None)
291 broker = MT5Broker(login=int(raw_login), password=password, server=server)
292 if terminal_path:
293 broker.terminal_path = terminal_path
294 print(f"\n Connecting to {server} as {raw_login} ...")
295 try:
296 ok = broker.connect()
297 except RuntimeError as exc:
298 print(f"\n {exc}")
299 return
300 if not ok:
301 print(" Login failed. Check login / password / server and retry.")
302 return
303 try:
304 info = broker.get_account_info()
305 print(f" Connected! Balance: {info.balance:.2f} {info.currency} "
306 f"Equity: {info.equity:.2f}")
307 finally:
308 broker.disconnect()
309 path = save_credentials(int(raw_login), password, server)
310 print(f" Credentials saved to {path} (mode 600).")
311 print(" Future commands (live/backtest/paper --use-mt5) will reuse them.\n")
312
313
314 def _broker_status() -> None:
315 saved = load_credentials()
316 if saved is None:
317 print(f"No saved credentials ({get_credentials_path()}).")
318 print("Run: alice broker login --demo (or --server Headway-Real)")
319 return
320 print(f"Saved login: {saved['login']} server: {saved['server']}")
321 print(f"File: {get_credentials_path()}")
322 print("Testing connection ...")
323 broker = MT5Broker(
324 login=int(saved["login"]),
325 password=saved["password"],
326 server=saved["server"],
327 )
328 try:
329 if not broker.connect():
330 print("Connection failed. Re-run 'alice broker login'.")
331 return
332 info = broker.get_account_info()
333 print(f"OK: balance={info.balance:.2f} {info.currency} equity={info.equity:.2f} "
334 f"leverage=1:{info.leverage} trade_allowed={info.trade_allowed}")
335 positions = broker.get_positions()
336 print(f"Open positions: {len(positions)}")
337 for pos in positions[:10]:
338 side = "BUY" if pos.type == 0 else "SELL"
339 print(f" #{pos.ticket} {side} {pos.symbol} {pos.volume} "
340 f"open={pos.price_open} now={pos.price_current} pnl={pos.profit:.2f}")
341 except RuntimeError as exc:
342 print(f"{exc}")
343 finally:
344 if broker.connected:
345 broker.disconnect()
346
347
348 def _run_live(args: argparse.Namespace) -> None:
349 print(f"\n{'='*60}")
350 print(f" Alice Live Trading — {args.symbol}")
351 print(f" Strategy: {args.strategy}")
352 print(f"{'='*60}\n")
353
354 try:
355 from typing import Any
356
357 mt5: Any = __import__("MetaTrader5")
358 except ImportError:
359 print("Error: MetaTrader5 package not installed (Windows only).")
360 print("Run on Windows / a Windows VPS with Headway MT5 installed:")
361 print(" pip install MetaTrader5")
362 sys.exit(1)
363
364 demo = bool(getattr(args, "demo", False))
365 raw_server = getattr(args, "server", None)
366 login = getattr(args, "login", None)
367 password = getattr(args, "password", None)
368 if login is None or password is None or raw_server is None:
369 saved = load_credentials()
370 if saved is not None:
371 if login is None:
372 login = int(saved["login"])
373 if password is None:
374 password = saved["password"]
375 if raw_server is None:
376 raw_server = saved["server"]
377 server = resolve_headway_server(raw_server, demo=demo)
378 if login is None or password is None:
379 print("No MT5 credentials. Run first:")
380 print(" alice broker login --demo # or --server Headway-Real")
381 sys.exit(1)
382
383 broker = MT5Broker(login=int(login), password=password, server=server)
384 if not broker.connect():
385 print("Failed to connect. Check credentials and that MT5 is installed.")
386 sys.exit(1)
387
388 execute = bool(getattr(args, "execute", False))
389 if execute and not bool(getattr(args, "yes", False)):
390 print(" WARNING: --execute places REAL orders on your Headway account.")
391 confirm = input(" Type YES to continue with live orders: ").strip()
392 if confirm != "YES":
393 print(" Aborted. Re-run without --execute for a dry run.")
394 broker.disconnect()
395 return
396 try:
397 strategy = _build_strategy(args.strategy, args)
398
399 print(f"Connected to MT5 account #{broker.get_account_info().login} ({server})")
400 print(f"Trading {args.symbol} with {args.strategy} "
401 f"(risk={args.risk*100:.1f}%, every {args.interval}s)")
402 print(f"Mode: {'LIVE ORDERS' if execute else 'SIGNALS ONLY (dry run)'}")
403 print("Press Ctrl+C to stop\n")
404
405 import datetime
406 import time
407
408 while True:
409 try:
410 df = broker.get_rates(args.symbol, mt5.TIMEFRAME_H1, 100)
411 df = add_returns(df)
412 df = strategy.generate_signals(df)
413
414 latest = df.iloc[-1]
415 prev = df.iloc[-2] if len(df) > 1 else latest
416 price = float(latest["Close"])
417
418 if latest["Signal"] == 1 and prev["Signal"] != 1:
419 print(f"[{datetime.datetime.now()}] BUY signal {args.symbol} @ {price:.5f}")
420 _handle_signal(broker, args.symbol, True, price, args.risk, execute)
421 elif latest["Signal"] == -1 and prev["Signal"] != -1:
422 print(f"[{datetime.datetime.now()}] SELL signal {args.symbol} @ {price:.5f}")
423 _handle_signal(broker, args.symbol, False, price, args.risk, execute)
424
425 positions = broker.get_positions(args.symbol)
426 for pos in positions:
427 if pos.type == 0 and latest["Signal"] == -1:
428 print(f"[{datetime.datetime.now()}] Opposite signal: "
429 f"close LONG #{pos.ticket}")
430 if execute:
431 broker.close_position(pos.ticket)
432 elif pos.type == 1 and latest["Signal"] == 1:
433 print(f"[{datetime.datetime.now()}] Opposite signal: "
434 f"close SHORT #{pos.ticket}")
435 if execute:
436 broker.close_position(pos.ticket)
437
438 time.sleep(args.interval)
439
440 except KeyboardInterrupt:
441 print("\nStopping live trading...")
442 break
443 except Exception as exc:
444 print(f"Error in trading loop: {exc} (retrying)")
445 import time as _time
446
447 _time.sleep(args.interval)
448
449 finally:
450 broker.disconnect()
451 print("Disconnected from MT5")
452
453
454 def _handle_signal(
455 broker: MT5Broker,
456 symbol: str,
457 is_buy: bool,
458 price: float,
459 risk: float,
460 execute: bool,
461 ) -> None:
462 """Size a position from equity risk and optionally submit it."""
463 account = broker.get_account_info()
464 risk_amount = account.equity * risk
465 stop_distance = price * 0.02 # simplified 2% stop
466 if stop_distance <= 0:
467 return
468 lots = max(0.01, round(risk_amount / (stop_distance * 100000), 2))
469 side = "BUY" if is_buy else "SELL"
470 stop = price * (0.98 if is_buy else 1.02)
471 target = price * (1.04 if is_buy else 0.96)
472 print(f" {side} {lots} lots @ {price:.5f} SL={stop:.5f} TP={target:.5f}")
473 if not execute:
474 print(" Dry run: add --execute to place the order.")
475 return
476 if is_buy:
477 broker.buy(symbol, lots, stop, target, "Alice Bot Signal")
478 else:
479 broker.sell(symbol, lots, stop, target, "Alice Bot Signal")
480
481
482 def _run_webhook(args: argparse.Namespace) -> None:
483 print(f"\n{'='*60}")
484 print(" Alice Webhook Server")
485 print(f" Host: {args.host}")
486 print(f" Port: {args.port}")
487 print(f"{'='*60}\n")
488
489 receiver = TradingViewSignalReceiver(secret=args.secret)
490 app = create_webhook_app(receiver, args.host, args.port)
491
492 if app is None:
493 print("Error: Flask not installed. Install with: pip install -e '.[web]'")
494 sys.exit(1)
495
496 try:
497 import os
498
499 os.environ["FLASK_ENV"] = "development"
500 app.run(host=args.host, port=args.port, debug=True)
501 except KeyboardInterrupt:
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()