-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
326 lines (261 loc) · 10.7 KB
/
main.py
File metadata and controls
326 lines (261 loc) · 10.7 KB
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python3
"""
AutoGen-TradingSystem Main Runner
Unified entry point for all trading system operations.
Usage:
python main.py # Launch interactive trading assistant
python main.py --help # Show all commands
python main.py --daemon # Run automated scheduler
In CLI, use natural language for trading modes:
> buy SPY aggressively
> I want to be conservative with this AAPL trade
> set risk mode to moderate
"""
import argparse
import asyncio
import os
import sys
import traceback
import yaml
# Add project root to path
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
# Import all trading system components at startup for efficiency
from src.trading.accounts.account_manager import get_account_manager
from src.trading.scheduling.daily_scheduler import DailyScheduler
from src.utils.safe_print import get_symbol, safe_print
def _load_cli_help() -> str:
"""Load and format CLI help text from YAML config."""
config_path = os.path.join(os.path.dirname(__file__), "config_defaults", "cli_help.yaml")
try:
with open(config_path, encoding="utf-8") as f:
config = yaml.safe_load(f)
except (FileNotFoundError, yaml.YAMLError):
return "" # Fall back to no epilog if config unavailable
lines = [
"",
f"{'=' * 66}",
f" {config['title']} v{config['version']}".center(66),
f" {config['subtitle']}".center(66),
f"{'=' * 66}",
"",
"QUICK START:",
]
# Quick start commands
for item in config["quick_start"]:
lines.append(f" {item['command']:<36} # {item['description']}")
# Interactive commands sections
lines.append("")
lines.append("INTERACTIVE CLI COMMANDS (type /help for full list):")
for section in config["interactive_commands"].values():
lines.append("")
lines.append(f" {section['title']}:")
for cmd in section["commands"]:
lines.append(f" > {cmd['example']:<28} # {cmd['description']}")
# Features
lines.append("")
lines.append("FEATURES:")
for feature in config["features"]:
lines.append(f" - {feature}")
return "\n".join(lines)
# CLI imports (may not be available in all environments)
try:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
from cli import CLISession
from core.factory import OrchestratorFactory
from core.trading_modes import get_mode_manager
CLI_AVAILABLE = True
except ImportError:
CLI_AVAILABLE = False
CLISession = None
OrchestratorFactory = None
get_mode_manager = None
def list_accounts():
"""
List all configured trading accounts.
Issue #401: Multi-account portfolio management.
"""
safe_print(f"{get_symbol('INFO')} Configured Trading Accounts:")
print("=" * 60)
manager = get_account_manager()
# Discover all accounts (query Alpaca API for details)
safe_print(f"{get_symbol('GEAR')} Discovering account details...")
manager.discover_all_accounts()
accounts = manager.list_accounts()
if not accounts:
safe_print(f"{get_symbol('WARNING')} No accounts configured.")
print("\nTo add accounts, update config/config.json with:")
print(' "accounts": [')
print(' {"id": "paper_main", "api_key": "...", "api_secret": "...", "alias": "Paper"}')
print(" ]")
return False
for acc in accounts:
status_icon = get_symbol("SUCCESS") if acc.get("has_info") else get_symbol("WARNING")
active_tag = " [ACTIVE]" if acc.get("is_active") else ""
enabled_tag = "" if acc.get("enabled", True) else " [DISABLED]"
print(f"\n{status_icon} {acc['id']}{active_tag}{enabled_tag}")
if acc.get("alias"):
print(f" Alias: {acc['alias']}")
if acc.get("has_info"):
acc_type = acc.get("account_type", "unknown").upper()
print(f" Type: {acc_type}")
print(f" Account #: {acc.get('account_number', 'N/A')}")
print(f" Portfolio: ${acc.get('portfolio_value', 0):,.2f}")
print(f" Buying Power: ${acc.get('buying_power', 0):,.2f}")
print(f" Status: {acc.get('status', 'Unknown')}")
else:
error = acc.get("last_error", "Discovery pending")
print(f" Status: Not discovered ({error})")
print("\n" + "=" * 60)
print(f"Total: {len(accounts)} account(s) configured")
print("\nUsage: python main.py --account <ACCOUNT_ID>")
return True
def trade_assist(account_id: str = None):
"""Interactive CLI trading assistant.
Trading modes can be set via natural language:
> buy SPY aggressively
> set risk mode to conservative
> I want to be careful with this trade
Args:
account_id: Optional account ID to use (#401)
"""
if not CLI_AVAILABLE:
safe_print(f"{get_symbol('ERROR')} CLI components not available")
sys.exit(1)
try:
# Multi-account setup (#401)
alpaca_mode = "paper" # Default
active_account_info = None
if account_id:
manager = get_account_manager()
# Try to set the requested account as active
if manager.set_active_account(account_id):
active_account = manager.get_active_account()
if active_account and active_account.info:
active_account_info = active_account.info
alpaca_mode = active_account_info.account_type.value
safe_print(
f"{get_symbol('SUCCESS')} Using account: {account_id} "
f"({alpaca_mode.upper()})"
)
else:
safe_print(f"{get_symbol('ERROR')} Account '{account_id}' not found or not ready")
safe_print(f"{get_symbol('INFO')} Use --list-accounts to see available accounts")
return False
# Get default mode info for display
mode_manager = get_mode_manager()
mode_params = mode_manager.get_parameters()
safe_print(f"\n{get_symbol('ROCKET')} Starting Trade Assistant (Production Mode)...")
print(
f" - Default Mode: {mode_params.mode.value} (say 'aggressive' or 'conservative' to change)"
)
print(" - LLM Parser: gpt-4o-mini")
print(" - Strategy: RealVoterAgent (MACD+RSI, 0.856 Sharpe)")
if active_account_info:
print(f" - Account: {active_account_info.alias or account_id} ({alpaca_mode})")
print(f" - Portfolio: ${active_account_info.portfolio_value:,.2f}")
else:
print(f" - Execution: AlpacaOrderManager ({alpaca_mode} trading)")
print()
# Create orchestrator with real components
factory = OrchestratorFactory()
orchestrator = factory.create(
order_manager=None, # Auto-create from factory
use_real_voter=True, # Use production VoterAgent
use_real_alpaca=True, # Use real Alpaca OrderManager
alpaca_mode=alpaca_mode, # Use detected mode from account
)
# Create CLI session
session = CLISession(orchestrator)
# Run REPL
asyncio.run(session.run())
return True
except (ImportError, ValueError, RuntimeError) as e:
safe_print(f"{get_symbol('ERROR')} Error starting trade assistant: {e}")
traceback.print_exc()
return False
# =============================================================================
# CLI Command Handlers
# =============================================================================
def _run_interactive_cli(account_id: str = None) -> None:
"""Run interactive trading CLI, optionally with specific account."""
if account_id:
safe_print(f"{get_symbol('ROCKET')} Launching Trading Assistant with account: {account_id}")
else:
safe_print(f"{get_symbol('ROCKET')} Launching Interactive Trading Assistant...")
print(" (Use --help to see all options)")
print()
try:
success = trade_assist(account_id=account_id)
sys.exit(0 if success else 1)
except KeyboardInterrupt:
safe_print(f"\n{get_symbol('STOP')} Cancelled by user")
sys.exit(0)
except (ImportError, ValueError, RuntimeError) as e:
safe_print(f"\n{get_symbol('EXPLOSION')} Error: {e}")
sys.exit(1)
def _run_daemon_mode() -> None:
"""Run scheduler in daemon mode."""
safe_print(f"{get_symbol('ROBOT')} Starting Daily Scheduler Daemon...")
print(" Press Ctrl+C to stop")
print()
try:
scheduler = DailyScheduler()
asyncio.run(scheduler.run_daemon(check_interval_seconds=60))
sys.exit(0)
except KeyboardInterrupt:
safe_print(f"\n{get_symbol('STOP')} Scheduler stopped by user")
sys.exit(0)
except (ImportError, ValueError, RuntimeError) as e:
safe_print(f"\n{get_symbol('EXPLOSION')} Scheduler error: {e}")
sys.exit(1)
def _create_argument_parser() -> argparse.ArgumentParser:
"""Create and configure the argument parser for main()."""
parser = argparse.ArgumentParser(
description="AutoGen Trading System - Production-Ready Multi-Agent Trading Platform",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=_load_cli_help(),
)
parser.add_argument(
"--daemon", action="store_true", help="Run daily scheduler in background (daemon mode)"
)
parser.add_argument(
"--account",
"-a",
type=str,
metavar="ACCOUNT_ID",
help="Select trading account (e.g., --account paper_main)",
)
parser.add_argument(
"--list-accounts",
action="store_true",
help="List all configured trading accounts",
)
return parser
def main():
"""
Main entry point - Unified Interactive CLI.
Default: Launches interactive trading assistant
--daemon: Runs scheduler in background
--list-accounts: List configured accounts
--account: Use specific account
"""
# No arguments = launch interactive CLI
if len(sys.argv) == 1:
_run_interactive_cli()
return
parser = _create_argument_parser()
args = parser.parse_args()
# Handle each mode
if args.list_accounts:
try:
success = list_accounts()
sys.exit(0 if success else 1)
except (ImportError, ValueError, RuntimeError) as e:
safe_print(f"{get_symbol('ERROR')} Error listing accounts: {e}")
sys.exit(1)
if args.account and not args.daemon:
_run_interactive_cli(account_id=args.account)
if args.daemon:
_run_daemon_mode()
if __name__ == "__main__":
main()