-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
517 lines (422 loc) Β· 19.5 KB
/
Copy pathcli.py
File metadata and controls
517 lines (422 loc) Β· 19.5 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#!/usr/bin/env python3
"""
MarketSense AI - Command Line Interface
Interactive CLI for the trading intelligence bot.
"""
import cmd
import json
from datetime import datetime
from typing import Optional
import sys
from bot import MarketSenseBot
from config import DEFAULT_ASSETS, SUPPORTED_TIMEFRAMES
class MarketSenseCLI(cmd.Cmd):
"""Interactive command-line interface for MarketSense AI."""
intro = """
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MarketSense AI - Trading Intelligence Bot β
β β
β π― Purpose: Learning, discipline, and data-driven trading β
β β οΈ Mode: Simulation (No real money) β
β β
β Type 'help' for available commands β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"""
prompt = '\nπ MarketSense> '
def __init__(self):
super().__init__()
self.bot = MarketSenseBot()
self._initialize_bot()
def _initialize_bot(self):
"""Initialize the bot on startup."""
print("\nπ Initializing MarketSense AI...")
result = self.bot.initialize()
if result['success']:
print(f"β
Initialized successfully!")
print(f" Mode: {result['mode']}")
print(f" Assets: {', '.join(result['assets'])}")
print(f" Balance: ${result['balance']:,.2f}")
else:
print(f"β Initialization failed: {result.get('error')}")
def _print_json(self, data: dict, indent: int = 2):
"""Pretty print JSON data."""
print(json.dumps(data, indent=indent, default=str))
def _print_analysis(self, analysis: dict):
"""Print analysis results in a formatted way."""
if analysis.get('error'):
print(f"β Error: {analysis.get('message')}")
return
print("\n" + "="*60)
print(f" ANALYSIS: {analysis['asset']} ({analysis['timeframe']})")
print("="*60)
# Score
score = analysis['score']
print(f"\nπ SCORE: {score['final_score']:.1f}/100 - {score['grade']}")
print(f" {score['recommendation']}")
# AI Prediction
ai = analysis['ai_prediction']
print(f"\nπ€ AI PREDICTION:")
print(f" Probability: {ai.get('probability', 0):.1f}%")
print(f" Risk Level: {ai.get('risk_level', 'N/A')}")
print(f" Recommendation: {ai.get('recommendation', 'N/A')}")
# Signals
signals = analysis['signals']
bias = signals.get('overall_bias', {})
print(f"\nπ SIGNALS:")
print(f" Overall Bias: {bias.get('direction', 'N/A')} ({bias.get('confidence', 0)*100:.0f}% confidence)")
print(f" RSI: {signals.get('rsi', {}).get('value', 0):.1f} ({signals.get('rsi', {}).get('signal', 'N/A')})")
print(f" EMA: {signals.get('ema', {}).get('signal', 'N/A')}")
print(f" MACD: {signals.get('macd', {}).get('trend', 'N/A')}")
# Trap Analysis
trap = analysis['trap_analysis']
if trap.get('traps_detected'):
print(f"\nβ οΈ TRAP WARNING: {trap['assessment']}")
print(f" {trap['recommendation']}")
# Can trade
can_trade, reason = analysis['can_trade']
print(f"\n{'β
' if can_trade else 'β'} Can Trade: {reason}")
print("="*60)
# ==================== COMMANDS ====================
def do_status(self, arg):
"""Show current bot status and account information."""
status = self.bot.get_status()
print("\n" + "="*60)
print(" BOT STATUS")
print("="*60)
sim = status['simulation']
print(f"\nπ° ACCOUNT:")
print(f" Balance: ${sim['balance']:,.2f}")
print(f" P&L: ${sim['pnl']:,.2f} ({sim['pnl_percent']:+.1f}%)")
print(f" Open Trades: {sim['open_trades']}")
print(f" Total Trades: {sim['total_trades']}")
print(f"\nβοΈ SETTINGS:")
print(f" Mode: {status['mode']}")
print(f" Assets: {', '.join(status['preferred_assets'])}")
print(f" Timeframe: {status['preferred_timeframe']}")
print(f" Session: {sim['current_session']}")
psych = status['psychology']
print(f"\nπ§ PSYCHOLOGY:")
print(f" Discipline: {psych['discipline_score']['score']:.0f}/100 ({psych['discipline_score']['grade']})")
print(f" Emotional State: {psych['emotional_state']['state']}")
if psych['warnings']:
print(f"\nβ οΈ WARNINGS:")
for w in psych['warnings']:
print(f" {w}")
if sim['is_paused']:
print(f"\nπ TRADING PAUSED: {sim['pause_reason']}")
print("="*60)
def do_analyze(self, arg):
"""
Analyze a trading setup.
Usage: analyze [asset] [direction]
Example: analyze EUR/USD CALL
"""
args = arg.split()
asset = args[0] if args else self.bot.preferred_assets[0]
direction = args[1].upper() if len(args) > 1 else None
print(f"\nπ Analyzing {asset}...")
analysis = self.bot.analyze(asset, self.bot.preferred_timeframe, direction)
self._print_analysis(analysis)
def do_suggest(self, arg):
"""
Get AI trade suggestion.
Usage: suggest [asset]
Example: suggest EUR/USD
"""
asset = arg.strip() if arg else self.bot.preferred_assets[0]
print(f"\nπ€ Getting suggestion for {asset}...")
suggestion = self.bot.suggest_trade(asset)
if suggestion.get('error'):
print(f"β Error: {suggestion.get('message')}")
return
print("\n" + "="*60)
print(f" AI SUGGESTION: {suggestion['asset']}")
print("="*60)
rec = suggestion['recommendation']
print(f"\nπ ACTION: {rec['action']}")
print(f" Confidence: {rec['confidence']}")
print(f" {rec['message']}")
if suggestion['suggested_direction']:
print(f"\nβ‘οΈ Suggested Direction: {suggestion['suggested_direction']}")
print(f"\nπ Score: {suggestion['score']['final_score']:.1f}")
print(f"π― Probability: {suggestion['ai_prediction'].get('probability', 0):.1f}%")
print("="*60)
def do_trade(self, arg):
"""
Execute a simulated trade.
Usage: trade <asset> <CALL|PUT> [journal entry]
Example: trade EUR/USD CALL "Trend following setup"
"""
if not arg:
print("β Usage: trade <asset> <CALL|PUT> [journal]")
return
parts = arg.split('"')
main_args = parts[0].strip().split()
journal = parts[1] if len(parts) > 1 else None
if len(main_args) < 2:
print("β Usage: trade <asset> <CALL|PUT> [journal]")
return
asset = main_args[0]
direction = main_args[1].upper()
if direction not in ['CALL', 'PUT']:
print("β Direction must be CALL or PUT")
return
print(f"\nπ Executing trade: {asset} {direction}...")
result = self.bot.execute(asset, direction, journal=journal)
if result['success']:
print(f"\nβ
Trade Executed!")
print(f" Trade ID: {result['trade_id']}")
print(f" Entry: {result['entry_price']:.5f}")
print(f" Size: ${result['position_size']:.2f}")
print(f" Score: {result['score']:.1f}")
if result.get('warnings'):
print("\nβ οΈ Warnings:")
for w in result['warnings']:
print(f" {w}")
else:
print(f"\nβ Trade Failed: {result.get('message')}")
def do_close(self, arg):
"""
Close an open trade.
Usage: close <trade_id> [exit_price]
Example: close 1 1.1050
"""
args = arg.split()
if not args:
print("β Usage: close <trade_id> [exit_price]")
return
try:
trade_id = int(args[0])
exit_price = float(args[1]) if len(args) > 1 else None
except ValueError:
print("β Invalid trade ID or price")
return
result = self.bot.close(trade_id, exit_price)
if result['success']:
outcome_emoji = "π’" if result['outcome'] == 'WIN' else "π΄"
print(f"\n{outcome_emoji} Trade #{trade_id} Closed!")
print(f" Exit: {result['exit_price']:.5f}")
print(f" P&L: ${result['pnl']:+.2f}")
print(f" Outcome: {result['outcome']}")
print(f" New Balance: ${result['new_balance']:,.2f}")
else:
print(f"\nβ Failed: {result.get('message')}")
def do_open(self, arg):
"""Show all open trades."""
trades = self.bot.get_open_trades()
if not trades:
print("\nπ No open trades")
return
print("\n" + "="*60)
print(" OPEN TRADES")
print("="*60)
for trade in trades:
print(f"\nπ Trade #{trade['id']}")
print(f" Asset: {trade['asset']} {trade['direction']}")
print(f" Entry: {trade['entry_price']:.5f}")
print(f" Amount: ${trade['amount']:.2f}")
print(f" Score: {trade.get('strategy_score', 'N/A')}")
print("="*60)
def do_scan(self, arg):
"""Scan all preferred assets for trading opportunities."""
print("\nπ Scanning markets...")
opportunities = self.bot.scan_markets()
if not opportunities:
print("\nπ No opportunities found")
return
print("\n" + "="*60)
print(" MARKET OPPORTUNITIES")
print("="*60)
for opp in opportunities:
score_emoji = "π’" if opp['score'] >= 70 else "π‘" if opp['score'] >= 50 else "π΄"
print(f"\n{score_emoji} {opp['asset']}")
print(f" Score: {opp['score']:.1f}")
print(f" Direction: {opp['direction']}")
print(f" Probability: {opp['probability']:.1f}%")
print(f" AI: {opp['ai_recommendation']}")
print("="*60)
def do_report(self, arg):
"""
Generate performance report.
Usage: report [daily|weekly]
"""
report_type = arg.strip().lower() if arg else 'daily'
if report_type not in ['daily', 'weekly']:
print("β Usage: report [daily|weekly]")
return
print(f"\nπ Generating {report_type} report...")
report_text = self.bot.get_report_text(report_type)
print(report_text)
def do_psychology(self, arg):
"""Show detailed psychology analysis."""
print("\nπ§ Analyzing psychology...")
analysis = self.bot.get_psychology_analysis()
print("\n" + "="*60)
print(" PSYCHOLOGY ANALYSIS")
print("="*60)
# Discipline
discipline = analysis['discipline_score']
print(f"\nπ DISCIPLINE SCORE: {discipline['score']:.0f}/100 ({discipline['grade']})")
for factor, value in discipline['factors'].items():
print(f" {factor}: {value:.0f}")
# Overtrading
ot = analysis['overtrading']
print(f"\nβ±οΈ OVERTRADING:")
print(f" Trades last hour: {ot['trades_last_hour']}")
print(f" Daily trades: {ot['daily_trades']}/{ot['max_daily_trades']}")
print(f" Status: {'β οΈ OVERTRADING' if ot['is_overtrading'] else 'β
OK'}")
# Revenge trading
rt = analysis['revenge_trading']
print(f"\nπ€ REVENGE TRADING:")
print(f" Detected: {'β οΈ YES' if rt['detected'] else 'β
NO'}")
if rt['detected']:
print(f" Instances: {rt['instances']}")
# Emotional state
es = analysis.get('emotional_clusters', {})
print(f"\nπ EMOTIONAL CLUSTERS:")
print(f" Detected: {'β οΈ YES' if es.get('detected') else 'β
NO'}")
# Warnings
if analysis['warnings']:
print(f"\nβ οΈ WARNINGS:")
for w in analysis['warnings']:
print(f" {w}")
# Recommendations
if analysis['recommendations']:
print(f"\nπ‘ RECOMMENDATIONS:")
for r in analysis['recommendations']:
print(f" {r}")
print("="*60)
def do_train(self, arg):
"""Train or retrain the AI model."""
print("\nπ§ Training AI model...")
result = self.bot.train_ai()
if result['success']:
metrics = result['metrics']
print(f"\nβ
Model trained successfully!")
print(f" Accuracy: {metrics['accuracy']*100:.1f}%")
print(f" Precision: {metrics['precision']*100:.1f}%")
print(f" Recall: {metrics['recall']*100:.1f}%")
print(f" F1 Score: {metrics['f1_score']*100:.1f}%")
print(f" Training samples: {metrics['training_samples']}")
else:
print(f"\nβ Training failed: {result.get('message')}")
def do_resume(self, arg):
"""Resume trading after pause."""
result = self.bot.resume()
if result['success']:
print(f"\nβ
{result['message']}")
if result.get('previous_pause_reason'):
print(f" Previous reason: {result['previous_pause_reason']}")
else:
print(f"\nβ {result.get('message')}")
def do_mode(self, arg):
"""
Change operating mode.
Usage: mode <simulation|manual_assist>
"""
if not arg:
print(f"\nπ Current mode: {self.bot.mode}")
print(" Use: mode <simulation|manual_assist>")
return
mode = arg.strip().lower()
if mode == 'manual_assist':
mode = 'manual_assist'
result = self.bot.set_mode(mode)
if result['success']:
print(f"\nβ
Mode changed to: {result['mode']}")
else:
print(f"\nβ {result.get('error')}")
def do_assets(self, arg):
"""
Set preferred assets.
Usage: assets <asset1> <asset2> ...
Example: assets EUR/USD GBP/USD
"""
if not arg:
print(f"\nπ Current assets: {', '.join(self.bot.preferred_assets)}")
print(f"\n Available: {', '.join(DEFAULT_ASSETS)}")
return
assets = arg.upper().split()
valid_assets = [a for a in assets if a in DEFAULT_ASSETS]
if valid_assets:
self.bot.preferred_assets = valid_assets
print(f"\nβ
Assets set to: {', '.join(valid_assets)}")
else:
print(f"\nβ No valid assets. Available: {', '.join(DEFAULT_ASSETS)}")
def do_timeframe(self, arg):
"""
Set preferred timeframe.
Usage: timeframe <1m|5m|15m>
"""
if not arg:
print(f"\nπ Current timeframe: {self.bot.preferred_timeframe}")
return
tf = arg.strip().lower()
if tf in SUPPORTED_TIMEFRAMES:
self.bot.preferred_timeframe = tf
print(f"\nβ
Timeframe set to: {tf}")
else:
print(f"\nβ Invalid timeframe. Use: {', '.join(SUPPORTED_TIMEFRAMES)}")
def do_help(self, arg):
"""Show help for commands."""
if arg:
# Show help for specific command
super().do_help(arg)
else:
print("""
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AVAILABLE COMMANDS β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
β ANALYSIS β
β analyze [asset] [direction] - Analyze a trading setup β
β suggest [asset] - Get AI trade suggestion β
β scan - Scan markets for opportunitiesβ
β β
β TRADING β
β trade <asset> <CALL|PUT> - Execute a simulated trade β
β close <trade_id> [price] - Close an open trade β
β open - Show open trades β
β β
β REPORTS β
β status - Show bot status β
β report [daily|weekly] - Generate performance report β
β psychology - Show psychology analysis β
β β
β AI β
β train - Train/retrain AI model β
β β
β SETTINGS β
β mode [simulation|manual] - Change operating mode β
β assets [asset1 asset2...] - Set preferred assets β
β timeframe [1m|5m|15m] - Set preferred timeframe β
β resume - Resume trading after pause β
β β
β OTHER β
β help [command] - Show help β
β quit - Exit the program β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
def do_quit(self, arg):
"""Exit the program."""
print("\nπ Goodbye! Remember: Learning and discipline come first!")
return True
def do_exit(self, arg):
"""Exit the program."""
return self.do_quit(arg)
def default(self, line):
"""Handle unknown commands."""
print(f"β Unknown command: {line}")
print(" Type 'help' for available commands")
def emptyline(self):
"""Do nothing on empty line."""
pass
def main():
"""Main entry point for CLI."""
try:
cli = MarketSenseCLI()
cli.cmdloop()
except KeyboardInterrupt:
print("\n\nπ Goodbye!")
sys.exit(0)
if __name__ == '__main__':
main()