-
Notifications
You must be signed in to change notification settings - Fork 493
Expand file tree
/
Copy pathtrading_bot.py
More file actions
579 lines (489 loc) · 25.2 KB
/
trading_bot.py
File metadata and controls
579 lines (489 loc) · 25.2 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
"""
Modular Trading Bot - Supports multiple exchanges
"""
import os
import time
import asyncio
import traceback
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional
from exchanges import ExchangeFactory
from helpers import TradingLogger
from helpers.lark_bot import LarkBot
from helpers.telegram_bot import TelegramBot
@dataclass
class TradingConfig:
"""Configuration class for trading parameters."""
ticker: str
contract_id: str
quantity: Decimal
take_profit: Decimal
tick_size: Decimal
direction: str
max_orders: int
wait_time: int
exchange: str
grid_step: Decimal
stop_price: Decimal
pause_price: Decimal
boost_mode: bool
@property
def close_order_side(self) -> str:
"""Get the close order side based on bot direction."""
return 'buy' if self.direction == "sell" else 'sell'
@dataclass
class OrderMonitor:
"""Thread-safe order monitoring state."""
order_id: Optional[str] = None
filled: bool = False
filled_price: Optional[Decimal] = None
filled_qty: Decimal = 0.0
def reset(self):
"""Reset the monitor state."""
self.order_id = None
self.filled = False
self.filled_price = None
self.filled_qty = 0.0
class TradingBot:
"""Modular Trading Bot - Main trading logic supporting multiple exchanges."""
def __init__(self, config: TradingConfig):
self.config = config
self.logger = TradingLogger(config.exchange, config.ticker, log_to_console=True)
# Create exchange client
try:
self.exchange_client = ExchangeFactory.create_exchange(
config.exchange,
config
)
except ValueError as e:
raise ValueError(f"Failed to create exchange client: {e}")
# Trading state
self.active_close_orders = []
self.last_close_orders = 0
self.last_open_order_time = 0
self.last_log_time = 0
self.current_order_status = None
self.order_filled_event = asyncio.Event()
self.order_canceled_event = asyncio.Event()
self.shutdown_requested = False
self.loop = None
# Register order callback
self._setup_websocket_handlers()
async def graceful_shutdown(self, reason: str = "Unknown"):
"""Perform graceful shutdown of the trading bot."""
self.logger.log(f"Starting graceful shutdown: {reason}", "INFO")
self.shutdown_requested = True
try:
# Disconnect from exchange
await self.exchange_client.disconnect()
self.logger.log("Graceful shutdown completed", "INFO")
except Exception as e:
self.logger.log(f"Error during graceful shutdown: {e}", "ERROR")
def _setup_websocket_handlers(self):
"""Setup WebSocket handlers for order updates."""
def order_update_handler(message):
"""Handle order updates from WebSocket."""
try:
# Check if this is for our contract
if message.get('contract_id') != self.config.contract_id:
return
order_id = message.get('order_id')
status = message.get('status')
side = message.get('side', '')
order_type = message.get('order_type', '')
filled_size = Decimal(message.get('filled_size'))
if order_type == "OPEN":
self.current_order_status = status
if status == 'FILLED':
if order_type == "OPEN":
self.order_filled_amount = filled_size
# Ensure thread-safe interaction with asyncio event loop
if self.loop is not None:
self.loop.call_soon_threadsafe(self.order_filled_event.set)
else:
# Fallback (should not happen after run() starts)
self.order_filled_event.set()
self.logger.log(f"[{order_type}] [{order_id}] {status} "
f"{message.get('size')} @ {message.get('price')}", "INFO")
self.logger.log_transaction(order_id, side, message.get('size'), message.get('price'), status)
elif status == "CANCELED":
if order_type == "OPEN":
self.order_filled_amount = filled_size
if self.loop is not None:
self.loop.call_soon_threadsafe(self.order_canceled_event.set)
else:
self.order_canceled_event.set()
if self.order_filled_amount > 0:
self.logger.log_transaction(order_id, side, self.order_filled_amount, message.get('price'), status)
# PATCH
if self.config.exchange == "extended":
self.logger.log(f"[{order_type}] [{order_id}] {status} "
f"{Decimal(message.get('size')) - filled_size} @ {message.get('price')}", "INFO")
else:
self.logger.log(f"[{order_type}] [{order_id}] {status} "
f"{message.get('size')} @ {message.get('price')}", "INFO")
elif status == "PARTIALLY_FILLED":
self.logger.log(f"[{order_type}] [{order_id}] {status} "
f"{filled_size} @ {message.get('price')}", "INFO")
else:
self.logger.log(f"[{order_type}] [{order_id}] {status} "
f"{message.get('size')} @ {message.get('price')}", "INFO")
except Exception as e:
self.logger.log(f"Error handling order update: {e}", "ERROR")
self.logger.log(f"Traceback: {traceback.format_exc()}", "ERROR")
# Setup order update handler
self.exchange_client.setup_order_update_handler(order_update_handler)
def _calculate_wait_time(self) -> Decimal:
"""Calculate wait time between orders."""
cool_down_time = self.config.wait_time
if len(self.active_close_orders) < self.last_close_orders:
self.last_close_orders = len(self.active_close_orders)
return 0
self.last_close_orders = len(self.active_close_orders)
if len(self.active_close_orders) >= self.config.max_orders:
return 1
if len(self.active_close_orders) / self.config.max_orders >= 2/3:
cool_down_time = 2 * self.config.wait_time
elif len(self.active_close_orders) / self.config.max_orders >= 1/3:
cool_down_time = self.config.wait_time
elif len(self.active_close_orders) / self.config.max_orders >= 1/6:
cool_down_time = self.config.wait_time / 2
else:
cool_down_time = self.config.wait_time / 4
# if the program detects active_close_orders during startup, it is necessary to consider cooldown_time
if self.last_open_order_time == 0 and len(self.active_close_orders) > 0:
self.last_open_order_time = time.time()
if time.time() - self.last_open_order_time > cool_down_time:
return 0
else:
return 1
async def _place_and_monitor_open_order(self) -> bool:
"""Place an order and monitor its execution."""
try:
# Reset state before placing order
self.order_filled_event.clear()
self.current_order_status = 'OPEN'
self.order_filled_amount = 0.0
# Place the order
order_result = await self.exchange_client.place_open_order(
self.config.contract_id,
self.config.quantity,
self.config.direction
)
if not order_result.success:
return False
if order_result.status == 'FILLED':
return await self._handle_order_result(order_result)
elif not self.order_filled_event.is_set():
try:
await asyncio.wait_for(self.order_filled_event.wait(), timeout=10)
except asyncio.TimeoutError:
pass
# Handle order result
return await self._handle_order_result(order_result)
except Exception as e:
self.logger.log(f"Error placing order: {e}", "ERROR")
self.logger.log(f"Traceback: {traceback.format_exc()}", "ERROR")
return False
async def _handle_order_result(self, order_result) -> bool:
"""Handle the result of an order placement."""
order_id = order_result.order_id
filled_price = order_result.price
if self.order_filled_event.is_set() or order_result.status == 'FILLED':
if self.config.boost_mode:
close_order_result = await self.exchange_client.place_market_order(
self.config.contract_id,
self.config.quantity,
self.config.close_order_side
)
else:
self.last_open_order_time = time.time()
# Place close order
close_side = self.config.close_order_side
if close_side == 'sell':
close_price = filled_price * (1 + self.config.take_profit/100)
else:
close_price = filled_price * (1 - self.config.take_profit/100)
close_order_result = await self.exchange_client.place_close_order(
self.config.contract_id,
self.config.quantity,
close_price,
close_side
)
if self.config.exchange == "lighter":
await asyncio.sleep(1)
if not close_order_result.success:
self.logger.log(f"[CLOSE] Failed to place close order: {close_order_result.error_message}", "ERROR")
raise Exception(f"[CLOSE] Failed to place close order: {close_order_result.error_message}")
return True
else:
new_order_price = await self.exchange_client.get_order_price(self.config.direction)
def should_wait(direction: str, new_order_price: Decimal, order_result_price: Decimal) -> bool:
if direction == "buy":
return new_order_price <= order_result_price
elif direction == "sell":
return new_order_price >= order_result_price
return False
if self.config.exchange == "lighter":
current_order_status = self.exchange_client.current_order.status
else:
order_info = await self.exchange_client.get_order_info(order_id)
current_order_status = order_info.status
while (
should_wait(self.config.direction, new_order_price, order_result.price)
and current_order_status == "OPEN"
):
self.logger.log(f"[OPEN] [{order_id}] Waiting for order to be filled @ {order_result.price}", "INFO")
await asyncio.sleep(5)
if self.config.exchange == "lighter":
current_order_status = self.exchange_client.current_order.status
else:
order_info = await self.exchange_client.get_order_info(order_id)
if order_info is not None:
current_order_status = order_info.status
new_order_price = await self.exchange_client.get_order_price(self.config.direction)
self.order_canceled_event.clear()
# Cancel the order if it's still open
self.logger.log(f"[OPEN] [{order_id}] Cancelling order and placing a new order", "INFO")
if self.config.exchange == "lighter":
cancel_result = await self.exchange_client.cancel_order(order_id)
start_time = time.time()
while (time.time() - start_time < 10 and self.exchange_client.current_order.status != 'CANCELED' and
self.exchange_client.current_order.status != 'FILLED'):
await asyncio.sleep(0.1)
if self.exchange_client.current_order.status not in ['CANCELED', 'FILLED']:
raise Exception(f"[OPEN] Error cancelling order: {self.exchange_client.current_order.status}")
else:
self.order_filled_amount = self.exchange_client.current_order.filled_size
else:
try:
cancel_result = await self.exchange_client.cancel_order(order_id)
if not cancel_result.success:
self.order_canceled_event.set()
self.logger.log(f"[CLOSE] Failed to cancel order {order_id}: {cancel_result.error_message}", "WARNING")
else:
self.current_order_status = "CANCELED"
except Exception as e:
self.order_canceled_event.set()
self.logger.log(f"[CLOSE] Error canceling order {order_id}: {e}", "ERROR")
if self.config.exchange == "backpack" or self.config.exchange == "extended":
self.order_filled_amount = cancel_result.filled_size
else:
# Wait for cancel event or timeout
if not self.order_canceled_event.is_set():
try:
await asyncio.wait_for(self.order_canceled_event.wait(), timeout=5)
except asyncio.TimeoutError:
order_info = await self.exchange_client.get_order_info(order_id)
self.order_filled_amount = order_info.filled_size
if self.order_filled_amount > 0:
close_side = self.config.close_order_side
if self.config.boost_mode:
close_order_result = await self.exchange_client.place_close_order(
self.config.contract_id,
self.order_filled_amount,
filled_price,
close_side
)
else:
if close_side == 'sell':
close_price = filled_price * (1 + self.config.take_profit/100)
else:
close_price = filled_price * (1 - self.config.take_profit/100)
close_order_result = await self.exchange_client.place_close_order(
self.config.contract_id,
self.order_filled_amount,
close_price,
close_side
)
if self.config.exchange == "lighter":
await asyncio.sleep(1)
self.last_open_order_time = time.time()
if not close_order_result.success:
self.logger.log(f"[CLOSE] Failed to place close order: {close_order_result.error_message}", "ERROR")
return True
return False
async def _log_status_periodically(self):
"""Log status information periodically, including positions."""
if time.time() - self.last_log_time > 60 or self.last_log_time == 0:
print("--------------------------------")
try:
# Get active orders
active_orders = await self.exchange_client.get_active_orders(self.config.contract_id)
# Filter close orders
self.active_close_orders = []
for order in active_orders:
if order.side == self.config.close_order_side:
self.active_close_orders.append({
'id': order.order_id,
'price': order.price,
'size': order.size
})
# Get positions
position_amt = await self.exchange_client.get_account_positions()
position_amt = abs(position_amt)
# Calculate active closing amount
active_close_amount = sum(
Decimal(order.get('size', 0))
for order in self.active_close_orders
if isinstance(order, dict)
)
self.logger.log(f"Current Position: {position_amt} | Active closing amount: {active_close_amount} | "
f"Order quantity: {len(self.active_close_orders)}")
self.last_log_time = time.time()
# Check for position mismatch
if abs(position_amt - active_close_amount) > (2 * self.config.quantity):
error_message = f"\n\nERROR: [{self.config.exchange.upper()}_{self.config.ticker.upper()}] "
error_message += "Position mismatch detected\n"
error_message += "###### ERROR ###### ERROR ###### ERROR ###### ERROR #####\n"
error_message += "Please manually rebalance your position and take-profit orders\n"
error_message += "请手动平衡当前仓位和正在关闭的仓位\n"
error_message += f"current position: {position_amt} | active closing amount: {active_close_amount} | "f"Order quantity: {len(self.active_close_orders)}\n"
error_message += "###### ERROR ###### ERROR ###### ERROR ###### ERROR #####\n"
self.logger.log(error_message, "ERROR")
await self.send_notification(error_message.lstrip())
if not self.shutdown_requested:
self.shutdown_requested = True
mismatch_detected = True
else:
mismatch_detected = False
return mismatch_detected
except Exception as e:
self.logger.log(f"Error in periodic status check: {e}", "ERROR")
self.logger.log(f"Traceback: {traceback.format_exc()}", "ERROR")
print("--------------------------------")
async def _meet_grid_step_condition(self) -> bool:
if self.active_close_orders:
picker = min if self.config.direction == "buy" else max
next_close_order = picker(self.active_close_orders, key=lambda o: o["price"])
next_close_price = next_close_order["price"]
best_bid, best_ask = await self.exchange_client.fetch_bbo_prices(self.config.contract_id)
if best_bid <= 0 or best_ask <= 0 or best_bid >= best_ask:
raise ValueError("No bid/ask data available")
if self.config.direction == "buy":
new_order_close_price = best_ask * (1 + self.config.take_profit/100)
if next_close_price / new_order_close_price > 1 + self.config.grid_step/100:
return True
else:
return False
elif self.config.direction == "sell":
new_order_close_price = best_bid * (1 - self.config.take_profit/100)
if new_order_close_price / next_close_price > 1 + self.config.grid_step/100:
return True
else:
return False
else:
raise ValueError(f"Invalid direction: {self.config.direction}")
else:
return True
async def _check_price_condition(self) -> bool:
stop_trading = False
pause_trading = False
if self.config.pause_price == self.config.stop_price == -1:
return stop_trading, pause_trading
best_bid, best_ask = await self.exchange_client.fetch_bbo_prices(self.config.contract_id)
if best_bid <= 0 or best_ask <= 0 or best_bid >= best_ask:
raise ValueError("No bid/ask data available")
if self.config.stop_price != -1:
if self.config.direction == "buy":
if best_ask >= self.config.stop_price:
stop_trading = True
elif self.config.direction == "sell":
if best_bid <= self.config.stop_price:
stop_trading = True
if self.config.pause_price != -1:
if self.config.direction == "buy":
if best_ask >= self.config.pause_price:
pause_trading = True
elif self.config.direction == "sell":
if best_bid <= self.config.pause_price:
pause_trading = True
return stop_trading, pause_trading
async def send_notification(self, message: str):
lark_token = os.getenv("LARK_TOKEN")
if lark_token:
async with LarkBot(lark_token) as lark_bot:
await lark_bot.send_text(message)
telegram_token = os.getenv("TELEGRAM_BOT_TOKEN")
telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID")
if telegram_token and telegram_chat_id:
with TelegramBot(telegram_token, telegram_chat_id) as tg_bot:
tg_bot.send_text(message)
async def run(self):
"""Main trading loop."""
try:
self.config.contract_id, self.config.tick_size = await self.exchange_client.get_contract_attributes()
# Log current TradingConfig
self.logger.log("=== Trading Configuration ===", "INFO")
self.logger.log(f"Ticker: {self.config.ticker}", "INFO")
self.logger.log(f"Contract ID: {self.config.contract_id}", "INFO")
self.logger.log(f"Quantity: {self.config.quantity}", "INFO")
self.logger.log(f"Take Profit: {self.config.take_profit}%", "INFO")
self.logger.log(f"Direction: {self.config.direction}", "INFO")
self.logger.log(f"Max Orders: {self.config.max_orders}", "INFO")
self.logger.log(f"Wait Time: {self.config.wait_time}s", "INFO")
self.logger.log(f"Exchange: {self.config.exchange}", "INFO")
self.logger.log(f"Grid Step: {self.config.grid_step}%", "INFO")
self.logger.log(f"Stop Price: {self.config.stop_price}", "INFO")
self.logger.log(f"Pause Price: {self.config.pause_price}", "INFO")
self.logger.log(f"Boost Mode: {self.config.boost_mode}", "INFO")
self.logger.log("=============================", "INFO")
# Capture the running event loop for thread-safe callbacks
self.loop = asyncio.get_running_loop()
# Connect to exchange
await self.exchange_client.connect()
# wait for connection to establish
await asyncio.sleep(5)
# Main trading loop
while not self.shutdown_requested:
# Update active orders
active_orders = await self.exchange_client.get_active_orders(self.config.contract_id)
# Filter close orders
self.active_close_orders = []
for order in active_orders:
if order.side == self.config.close_order_side:
self.active_close_orders.append({
'id': order.order_id,
'price': order.price,
'size': order.size
})
# Periodic logging
mismatch_detected = await self._log_status_periodically()
stop_trading, pause_trading = await self._check_price_condition()
if stop_trading:
msg = f"\n\nWARNING: [{self.config.exchange.upper()}_{self.config.ticker.upper()}] \n"
msg += "Stopped trading due to stop price triggered\n"
msg += "价格已经达到停止交易价格,脚本将停止交易\n"
await self.send_notification(msg.lstrip())
await self.graceful_shutdown(msg)
continue
if pause_trading:
await asyncio.sleep(5)
continue
if not mismatch_detected:
wait_time = self._calculate_wait_time()
if wait_time > 0:
await asyncio.sleep(wait_time)
continue
else:
meet_grid_step_condition = await self._meet_grid_step_condition()
if not meet_grid_step_condition:
await asyncio.sleep(1)
continue
await self._place_and_monitor_open_order()
self.last_close_orders += 1
except KeyboardInterrupt:
self.logger.log("Bot stopped by user")
await self.graceful_shutdown("User interruption (Ctrl+C)")
except Exception as e:
self.logger.log(f"Critical error: {e}", "ERROR")
self.logger.log(f"Traceback: {traceback.format_exc()}", "ERROR")
await self.graceful_shutdown(f"Critical error: {e}")
raise
finally:
# Ensure all connections are closed even if graceful shutdown fails
try:
await self.exchange_client.disconnect()
except Exception as e:
self.logger.log(f"Error disconnecting from exchange: {e}", "ERROR")