-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
793 lines (638 loc) · 25.5 KB
/
Copy pathcli.py
File metadata and controls
793 lines (638 loc) · 25.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
"""
Binance Futures Trading Bot — Interactive CLI.
Enhanced terminal UI with:
- Rich panels, tables, and spinners
- Questionary interactive prompts
- Color-coded output (green/red/yellow)
- Inline validation feedback
- Order confirmation before execution
- Session order history
- Settings menu
"""
import os
import sys
import time
import logging
from typing import Optional
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.prompt import Prompt, Confirm
from rich.columns import Columns
from rich import box
import questionary
from questionary import Style as QStyle
from bot.logging_config import setup_logging, get_logger, set_log_level
from bot.client import BinanceClient, BinanceAPIError
from bot.orders import OrderManager
from bot.models import OrderRequest, OrderSide, OrderType, SymbolInfo
from bot.validators import (
validate_symbol,
validate_quantity,
validate_price,
parse_float,
)
# ─── Console & Styling ──────────────────────────────────────────────────────
console = Console()
# Questionary custom style
PROMPT_STYLE = QStyle([
("qmark", "fg:ansicyan bold"),
("question", "fg:ansiwhite bold"),
("answer", "fg:ansigreen bold"),
("pointer", "fg:ansicyan bold"),
("highlighted", "fg:ansicyan bold"),
("selected", "fg:ansigreen"),
("separator", "fg:ansibrightblack"),
("instruction", "fg:ansibrightblack"),
("text", "fg:ansiwhite"),
])
# Popular trading symbols for suggestions
POPULAR_SYMBOLS = ["BTCUSDT", "ETHUSDT", "BNBUSDT", "SOLUSDT", "XRPUSDT", "DOGEUSDT"]
# ─── UI Components ───────────────────────────────────────────────────────────
def clear_screen():
"""Clear the terminal screen."""
os.system("cls" if os.name == "nt" else "clear")
def show_banner():
"""Display the bot banner/header."""
banner = Text()
banner.append("╔════════════════════════════════════════════╗\n", style="cyan")
banner.append("║ ║\n", style="cyan")
banner.append("║ ", style="cyan")
banner.append("BINANCE FUTURES TRADING BOT", style="bold white")
banner.append(" ║\n", style="cyan")
banner.append("║ ", style="cyan")
banner.append("Testnet Mode 🔬", style="yellow")
banner.append(" ║\n", style="cyan")
banner.append("║ ║\n", style="cyan")
banner.append("╚════════════════════════════════════════════╝", style="cyan")
console.print(banner)
console.print()
def show_success(message: str):
"""Display a success message."""
console.print(f" ✅ {message}", style="green")
def show_error(message: str):
"""Display an error message."""
console.print(f" ❌ {message}", style="red")
def show_warning(message: str):
"""Display a warning message."""
console.print(f" ⚠️ {message}", style="yellow")
def show_info(message: str):
"""Display an info message."""
console.print(f" ℹ️ {message}", style="bright_blue")
def show_divider():
"""Display a horizontal divider."""
console.print("═" * 50, style="dim cyan")
def show_order_result(response):
"""
Display a formatted order result panel.
Args:
response: OrderResponse from the API.
"""
# Determine status color
status_color = "green" if response.status in ("FILLED", "NEW") else "yellow"
if response.status in ("REJECTED", "EXPIRED", "CANCELED"):
status_color = "red"
# Build the result table
table = Table(
show_header=False,
box=None,
padding=(0, 2),
expand=True,
)
table.add_column("Key", style="bright_black", width=16)
table.add_column("Value", style="white")
table.add_row("Order ID", f"[bold]{response.order_id}[/bold]")
table.add_row("Symbol", f"[bold cyan]{response.symbol}[/bold cyan]")
table.add_row(
"Side",
f"[bold {'green' if response.side == 'BUY' else 'red'}]{response.side}[/bold {'green' if response.side == 'BUY' else 'red'}]"
)
table.add_row("Type", response.order_type)
table.add_row("Status", f"[bold {status_color}]{response.status}[/bold {status_color}]")
table.add_row("Quantity", f"{response.orig_qty}")
table.add_row("Executed", f"{response.executed_qty}")
if response.avg_price > 0:
table.add_row("Avg Price", f"${response.avg_price:,.2f}")
if response.commission > 0:
table.add_row("Commission", f"{response.commission}")
if response.time_in_force:
table.add_row("Time in Force", response.time_in_force)
# Wrap in panel
title = "✅ ORDER PLACED SUCCESSFULLY" if response.status != "REJECTED" else "❌ ORDER REJECTED"
title_style = "bold green" if response.status != "REJECTED" else "bold red"
panel = Panel(
table,
title=f"[{title_style}]{title}[/{title_style}]",
border_style="green" if response.status != "REJECTED" else "red",
box=box.DOUBLE,
padding=(1, 2),
)
console.print(panel)
# ─── Main Menu ───────────────────────────────────────────────────────────────
def main_menu() -> str:
"""
Display the main menu and return the user's choice.
Returns:
Selected action string.
"""
console.print()
choices = [
questionary.Choice("📈 Place Market Order", value="market"),
questionary.Choice("📊 Place Limit Order", value="limit"),
questionary.Choice("📋 View Order History", value="history"),
questionary.Choice("💰 Check Account Balance", value="balance"),
questionary.Choice("⚙️ Settings", value="settings"),
questionary.Choice("🚪 Exit", value="exit"),
]
result = questionary.select(
"Select an action:",
choices=choices,
style=PROMPT_STYLE,
instruction="(use arrow keys)",
).ask()
return result or "exit"
# ─── Order Placement Flow ───────────────────────────────────────────────────
def prompt_symbol(manager: OrderManager) -> Optional[str]:
"""
Prompt user for a trading symbol with validation.
Args:
manager: OrderManager for exchange info access.
Returns:
Validated symbol string or None if cancelled.
"""
console.print()
show_info(f"Popular symbols: {', '.join(POPULAR_SYMBOLS)}")
console.print()
while True:
symbol = questionary.text(
"Enter trading symbol (e.g., BTCUSDT):",
style=PROMPT_STYLE,
).ask()
if symbol is None: # User pressed Ctrl+C
return None
symbol = symbol.upper().strip()
if not symbol:
show_error("Symbol cannot be empty. Try again.")
continue
# Validate against exchange info
exchange_info = manager.client.get_exchange_info()
valid, msg = validate_symbol(symbol, exchange_info)
if valid:
show_success(msg)
return symbol
else:
show_error(msg)
def prompt_side() -> Optional[OrderSide]:
"""
Prompt user for order side (BUY/SELL).
Returns:
OrderSide or None if cancelled.
"""
console.print()
choices = [
questionary.Choice("BUY (Long) 📈", value="BUY"),
questionary.Choice("SELL (Short) 📉", value="SELL"),
]
result = questionary.select(
"Select order side:",
choices=choices,
style=PROMPT_STYLE,
).ask()
if result is None:
return None
return OrderSide(result)
def prompt_quantity(symbol: str, manager: OrderManager) -> Optional[float]:
"""
Prompt user for order quantity with validation.
Args:
symbol: Trading pair for validation context.
manager: OrderManager for symbol info access.
Returns:
Validated quantity or None if cancelled.
"""
# Get symbol info for hints
symbol_data = manager.client.get_symbol_info(symbol)
symbol_info = None
if symbol_data:
symbol_info = SymbolInfo.from_exchange_info(symbol_data)
base = symbol_info.base_asset or symbol.replace("USDT", "")
console.print()
show_info(
f"Lot size for {symbol}: "
f"min={symbol_info.min_qty}, "
f"max={symbol_info.max_qty}, "
f"step={symbol_info.step_size}"
)
console.print()
while True:
qty_str = questionary.text(
f"Enter quantity (in {symbol_info.base_asset if symbol_info else 'base asset'}):",
style=PROMPT_STYLE,
).ask()
if qty_str is None:
return None
success, qty, error = parse_float(qty_str)
if not success:
show_error(f"Invalid: {error}")
continue
valid, msg = validate_quantity(qty, symbol_info)
if valid:
show_success(msg)
return qty
else:
show_error(f"Invalid: {msg}")
def prompt_price(symbol: str, manager: OrderManager) -> Optional[float]:
"""
Prompt user for limit order price with current price reference.
Args:
symbol: Trading pair for price context.
manager: OrderManager for current price.
Returns:
Validated price or None if cancelled.
"""
# Show current market price as reference
current_price = manager.get_current_price(symbol)
if current_price:
console.print()
show_info(f"Current market price for {symbol}: ${current_price:,.2f}")
# Get symbol info for tick size
symbol_data = manager.client.get_symbol_info(symbol)
symbol_info = None
if symbol_data:
symbol_info = SymbolInfo.from_exchange_info(symbol_data)
console.print()
while True:
price_str = questionary.text(
"Enter limit price (e.g., 45000.50):",
style=PROMPT_STYLE,
).ask()
if price_str is None:
return None
success, price, error = parse_float(price_str)
if not success:
show_error(f"Invalid: Price must be a number (e.g., 45000.50)")
continue
valid, msg = validate_price(price, "LIMIT", symbol_info)
if valid:
show_success(msg)
return price
else:
show_error(f"Invalid: {msg}")
def confirm_order(order: OrderRequest) -> bool:
"""
Show order confirmation panel and ask for user confirmation.
Args:
order: OrderRequest to confirm.
Returns:
True if user confirms, False otherwise.
"""
console.print()
# Build confirmation table
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column("Field", style="bright_black", width=14)
table.add_column("Value", style="bold white")
table.add_row("Symbol", f"[bold cyan]{order.symbol}[/bold cyan]")
side_color = "green" if order.side == OrderSide.BUY else "red"
table.add_row("Side", f"[bold {side_color}]{order.side}[/bold {side_color}]")
table.add_row("Type", str(order.order_type))
table.add_row("Quantity", str(order.quantity))
if order.price is not None:
table.add_row("Price", f"${order.price:,.2f}")
panel = Panel(
table,
title="[bold yellow]⚠️ CONFIRM ORDER[/bold yellow]",
border_style="yellow",
box=box.ROUNDED,
padding=(1, 2),
)
console.print(panel)
return Confirm.ask(" Confirm order?", default=False)
def place_order_flow(manager: OrderManager, order_type: OrderType):
"""
Complete order placement flow: prompt → validate → confirm → execute.
Args:
manager: OrderManager instance.
order_type: MARKET or LIMIT.
"""
console.print()
type_label = "Market" if order_type == OrderType.MARKET else "Limit"
console.print(
Panel(
f"[bold]Place {type_label} Order[/bold]",
border_style="cyan",
box=box.ROUNDED,
)
)
# Step 1: Symbol
symbol = prompt_symbol(manager)
if symbol is None:
show_warning("Order cancelled.")
return
# Step 2: Side
side = prompt_side()
if side is None:
show_warning("Order cancelled.")
return
# Step 3: Quantity
quantity = prompt_quantity(symbol, manager)
if quantity is None:
show_warning("Order cancelled.")
return
# Step 4: Price (LIMIT only)
price = None
if order_type == OrderType.LIMIT:
price = prompt_price(symbol, manager)
if price is None:
show_warning("Order cancelled.")
return
# Build order request
order = OrderRequest(
symbol=symbol,
side=side,
order_type=order_type,
quantity=quantity,
price=price,
)
# Step 5: Confirmation
if not confirm_order(order):
show_warning("Order cancelled by user.")
return
# Step 6: Execute with spinner
console.print()
try:
with console.status("[bold cyan]⏳ Placing order...[/bold cyan]", spinner="dots"):
response = manager.place_order(order)
console.print()
show_order_result(response)
except ValueError as e:
console.print()
show_error(f"Validation Error: {e}")
except BinanceAPIError as e:
console.print()
show_error(f"Binance API Error [{e.code}]: {e.message}")
# Provide helpful hints for common errors
if e.code == -1121:
show_info("Hint: Check that the symbol is valid on Binance Futures.")
elif e.code == -2019:
show_info("Hint: Insufficient margin. Check your account balance.")
elif e.code == -1111:
show_info("Hint: Quantity precision is too high. Try fewer decimal places.")
elif e.code == -4003:
show_info("Hint: Quantity is too small. Check minimum lot size.")
except Exception as e:
console.print()
show_error(f"Unexpected error: {e}")
get_logger().exception("Unexpected error during order placement")
# ─── Order History ───────────────────────────────────────────────────────────
def view_order_history(manager: OrderManager):
"""Display order history from the current session and from Binance."""
console.print()
console.print(
Panel("[bold]Order History[/bold]", border_style="cyan", box=box.ROUNDED)
)
# Show session history first
session_history = manager.get_session_history()
if session_history:
console.print()
console.print(" [bold cyan]Session Orders:[/bold cyan]")
console.print()
table = Table(
box=box.SIMPLE_HEAVY,
border_style="dim",
padding=(0, 1),
)
table.add_column("#", style="dim", width=4)
table.add_column("Time", style="bright_black", width=20)
table.add_column("Symbol", style="cyan", width=10)
table.add_column("Side", width=6)
table.add_column("Type", width=8)
table.add_column("Qty", width=10)
table.add_column("Status", width=12)
table.add_column("Order ID", width=14)
for i, entry in enumerate(session_history, 1):
req = entry["request"]
res = entry["response"]
side_style = "green" if req["side"] == "BUY" else "red"
status_style = "green" if res["status"] == "FILLED" else "yellow"
table.add_row(
str(i),
entry["timestamp"][:19],
req["symbol"],
f"[{side_style}]{req['side']}[/{side_style}]",
req["type"],
str(req["quantity"]),
f"[{status_style}]{res['status']}[/{status_style}]",
str(res["order_id"]),
)
console.print(table)
else:
console.print()
show_info("No orders placed in this session yet.")
# Optionally fetch from Binance
console.print()
fetch = Confirm.ask(
" Fetch order history from Binance?", default=False
)
if fetch:
symbol = questionary.text(
"Enter symbol to query (e.g., BTCUSDT):",
style=PROMPT_STYLE,
).ask()
if symbol:
with console.status("[bold cyan]Fetching orders...[/bold cyan]", spinner="dots"):
orders = manager.get_order_history(symbol.upper().strip())
if orders:
console.print()
table = Table(
title=f"[bold]Orders for {symbol.upper()}[/bold]",
box=box.SIMPLE_HEAVY,
border_style="dim",
padding=(0, 1),
)
table.add_column("Order ID", style="dim", width=14)
table.add_column("Side", width=6)
table.add_column("Type", width=8)
table.add_column("Qty", width=10)
table.add_column("Executed", width=10)
table.add_column("Avg Price", width=14)
table.add_column("Status", width=14)
for o in orders[-20:]: # Show last 20
side_style = "green" if o.side == "BUY" else "red"
status_style = "green" if o.status == "FILLED" else "yellow"
if o.status in ("REJECTED", "EXPIRED", "CANCELED"):
status_style = "red"
table.add_row(
str(o.order_id),
f"[{side_style}]{o.side}[/{side_style}]",
o.order_type,
str(o.orig_qty),
str(o.executed_qty),
f"${o.avg_price:,.2f}" if o.avg_price > 0 else "-",
f"[{status_style}]{o.status}[/{status_style}]",
)
console.print(table)
else:
show_info(f"No orders found for {symbol.upper()}")
# ─── Account Balance ─────────────────────────────────────────────────────────
def view_balance(manager: OrderManager):
"""Display account balances."""
console.print()
console.print(
Panel("[bold]Account Balance[/bold]", border_style="cyan", box=box.ROUNDED)
)
with console.status("[bold cyan]Fetching balance...[/bold cyan]", spinner="dots"):
balances = manager.get_account_balance()
if not balances:
console.print()
show_info("No balances found or failed to fetch account data.")
return
console.print()
table = Table(
box=box.SIMPLE_HEAVY,
border_style="dim",
padding=(0, 1),
)
table.add_column("Asset", style="bold cyan", width=10)
table.add_column("Balance", width=18, justify="right")
table.add_column("Available", width=18, justify="right")
table.add_column("Unrealized PnL", width=18, justify="right")
for b in balances:
pnl_style = "green" if b["unrealized_pnl"] >= 0 else "red"
table.add_row(
b["asset"],
f"{b['balance']:,.4f}",
f"{b['available']:,.4f}",
f"[{pnl_style}]{b['unrealized_pnl']:,.4f}[/{pnl_style}]",
)
console.print(table)
# ─── Settings ────────────────────────────────────────────────────────────────
def settings_menu(manager: OrderManager):
"""Display and modify bot settings."""
console.print()
console.print(
Panel("[bold]Settings[/bold]", border_style="cyan", box=box.ROUNDED)
)
while True:
console.print()
choices = [
questionary.Choice("📊 View Current Configuration", value="view"),
questionary.Choice("📝 Change Logging Level", value="log_level"),
questionary.Choice("🔙 Back to Main Menu", value="back"),
]
action = questionary.select(
"Settings:",
choices=choices,
style=PROMPT_STYLE,
).ask()
if action is None or action == "back":
break
elif action == "view":
console.print()
table = Table(show_header=False, box=box.ROUNDED, border_style="dim", padding=(0, 2))
table.add_column("Setting", style="bright_black", width=20)
table.add_column("Value", style="white")
mode = "🔬 Testnet" if manager.client.use_testnet else "🔴 LIVE"
table.add_row("Mode", mode)
table.add_row("Base URL", manager.client.base_url)
table.add_row(
"API Key",
f"****{manager.client.api_key[-4:]}" if len(manager.client.api_key) > 4 else "****",
)
table.add_row("Log Level", logging.getLevelName(get_logger().handlers[0].level if get_logger().handlers else logging.INFO))
symbols_loaded = len(manager.client._symbols_cache)
table.add_row("Symbols Loaded", str(symbols_loaded))
table.add_row("Session Orders", str(len(manager.get_session_history())))
console.print(Panel(table, title="[bold]Current Configuration[/bold]", border_style="cyan"))
elif action == "log_level":
console.print()
level_choices = [
questionary.Choice("DEBUG — Verbose (all details)", value="DEBUG"),
questionary.Choice("INFO — Standard (recommended)", value="INFO"),
questionary.Choice("WARNING — Errors & warnings only", value="WARNING"),
]
level = questionary.select(
"Select logging level:",
choices=level_choices,
style=PROMPT_STYLE,
).ask()
if level:
log_level = getattr(logging, level)
set_log_level(log_level)
show_success(f"Logging level set to {level}")
# ─── Main Application ───────────────────────────────────────────────────────
def main():
"""Main entry point for the trading bot CLI."""
# Setup logging
logger = setup_logging()
logger.info("Starting Binance Futures Trading Bot")
# Show banner
clear_screen()
show_banner()
# Initialize client
try:
with console.status("[bold cyan]Connecting to Binance...[/bold cyan]", spinner="dots"):
client = BinanceClient(use_testnet=True)
manager = OrderManager(client)
# Pre-fetch exchange info
exchange_info = client.get_exchange_info()
show_success(f"Connected to Binance Testnet ({len(client._symbols_cache)} symbols loaded)")
except ValueError as e:
show_error(str(e))
show_info("Create a .env file with your API credentials. See .env.example")
sys.exit(1)
except Exception as e:
show_error(f"Failed to connect: {e}")
logger.exception("Failed to initialize client")
sys.exit(1)
# Main loop
try:
while True:
action = main_menu()
if action == "market":
place_order_flow(manager, OrderType.MARKET)
console.print()
input(" Press Enter to continue...")
clear_screen()
show_banner()
elif action == "limit":
place_order_flow(manager, OrderType.LIMIT)
console.print()
input(" Press Enter to continue...")
clear_screen()
show_banner()
elif action == "history":
view_order_history(manager)
console.print()
input(" Press Enter to continue...")
clear_screen()
show_banner()
elif action == "balance":
view_balance(manager)
console.print()
input(" Press Enter to continue...")
clear_screen()
show_banner()
elif action == "settings":
settings_menu(manager)
clear_screen()
show_banner()
elif action == "exit":
console.print()
if Confirm.ask(" Are you sure you want to exit?", default=False):
console.print()
console.print(" 👋 Goodbye! Happy trading!", style="bold cyan")
console.print()
logger.info("Bot shut down by user")
client.close()
break
else:
clear_screen()
show_banner()
except KeyboardInterrupt:
console.print()
console.print("\n 👋 Interrupted. Shutting down...", style="bold yellow")
logger.info("Bot interrupted by user (Ctrl+C)")
client.close()
if __name__ == "__main__":
main()