-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.py
More file actions
1706 lines (1441 loc) · 72.5 KB
/
Copy pathmain.py
File metadata and controls
1706 lines (1441 loc) · 72.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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# main.py
import asyncio
from datetime import datetime, timedelta
import json
import logging
import sys
from typing import Any, Dict, List, Optional
from telegram.ext import (
Application,
CommandHandler,
CallbackQueryHandler,
MessageHandler,
filters
)
from telegram import (
BotCommand,
CallbackQuery,
Message,
Update,
InlineKeyboardButton,
InlineKeyboardMarkup
)
from telegram.ext import (
Application,
CommandHandler,
CallbackQueryHandler,
MessageHandler,
ContextTypes,
filters,
ConversationHandler
)
from telethon import TelegramClient, events
from channel_management import ChannelManagement
from config import Config
from exchange_execution import ExchangeManager, OrderParams, PositionSide
from message_processor import MessageProcessor
from database import Database
from main_menu import MainMenuManager
from settings import SettingsManager, StatisticsManager
from models import EntryZone, TakeProfitLevel
from trading_logic import TradingLogic, TradingSignal
from button_texts import ButtonText as BT # 导入按钮文本配置
class TradingBot:
def __init__(self, config: Config):
self.config = config
self.db = Database(config.DATABASE_NAME)
self.trading_logic = TradingLogic(config.OPENAI_API_KEY,config.OPENAI_API_BASE_URL)
self.exchange_manager = ExchangeManager(config)
self.exchanges = self.exchange_manager.exchanges
self.message_processor = MessageProcessor(
self.trading_logic,
self.db,
self.config
)
self.main_menu = MainMenuManager(self)
self.settings_manager = SettingsManager(self)
self.stats_manager = StatisticsManager(self)
# Initialize Telegram bot
self.application = Application.builder().token(config.TELEGRAM_TOKEN).build()
# Initialize Telethon client
self.client = TelegramClient(
config.SESSION_NAME,
config.API_ID,
config.API_HASH
)
# Initialize UI components
self.channel_management = ChannelManagement(self.db, self.config,self.client)
# Setup handlers
self.setup_handlers()
# Setup commands
asyncio.create_task(self.setup_commands())
async def handle_channel_message(self, event):
"""处理频道消息"""
try:
# 获取消息对象
message = getattr(event, 'message', None) or event.channel_post
if not message or not message.text:
logging.info(f"Invalid message text-IGNORE")
return
# 获取频道信息
chat = message.chat
if not chat:
logging.error("Could not get chat info")
return
channel_id = chat.id
# 检查频道是否被监控
channel_info = self.db.get_channel_info(channel_id)
if not channel_info or not channel_info['is_active']:
return
network_indicator = "🏮 测试网" if self.config.trading.use_testnet else "🔵 主网"
# 处理消息
signal = await self.message_processor.process_channel_message(
event=event,
client=self.client,
bot=self.application.bot
)
if signal:
if signal.is_valid():
# 执行信号
if self.config.trading.auto_trade_enabled:
result = await self.exchange_manager.execute_signal(signal)
if result.success:
await self.notify_owner(
f"{network_indicator} 自动交易执行成功\n\n"
f"交易对: {signal.symbol}\n"
f"方向: {'做多' if signal.action == 'OPEN_LONG' else '做空'}\n"
f"订单ID: {result.order_id}\n"
f"执行价格: {result.executed_price}\n"
f"数量: {result.executed_amount}"
)
else:
await self.notify_owner(
f"{network_indicator} 自动交易执行失败\n\n"
f"交易对: {signal.symbol}\n"
f"错误: {result.error_message}"
)
else:
# 发送信号通知
message_text = (
f"{network_indicator} 新交易信号\n\n"
f"来源: {chat.title}\n"
f"交易对: {signal.symbol}\n"
f"方向: {'做多' if signal.action == 'OPEN_LONG' else '做空'}\n"
)
if signal.entry_zones:
message_text += "\n入场区间:\n"
for zone in signal.entry_zones:
message_text += f"- ${zone.price} ({zone.percentage * 100}%)\n"
else:
message_text += f"\n入场价格: ${signal.entry_price}"
if signal.take_profit_levels:
message_text += "\n\n止盈目标:\n"
for tp in signal.take_profit_levels:
message_text += f"- ${tp.price} ({tp.percentage * 100}%)\n"
if signal.stop_loss:
message_text += f"\n止损: ${signal.stop_loss}"
keyboard = [
[
InlineKeyboardButton(
"✅ 执行交易",
callback_data=f"execute_{signal.symbol}_{signal.signal_id}"
),
InlineKeyboardButton(
"❌ 忽略",
callback_data=f"ignore_{signal.signal_id}"
)
],
[
InlineKeyboardButton(
"📊 查看分析",
callback_data=f"analysis_{signal.symbol}_{signal.signal_id}"
)
]
]
try:
await self.application.bot.send_message(
chat_id=self.config.OWNER_ID,
text=message_text,
reply_markup=InlineKeyboardMarkup(keyboard)
)
except Exception as e:
logging.error(f"Error sending notification: {e}")
await self.notify_owner(f"发送通知失败: {str(e)}")
except Exception as e:
error_msg = f"Error handling channel message: {e}"
logging.error(error_msg)
import traceback
logging.error(f"Full traceback:\n{traceback.format_exc()}")
try:
await self.notify_owner(f"❌ {error_msg}")
except:
pass
def setup_handlers(self):
"""设置所有消息处理器"""
# 命令处理器
commands = [
CommandHandler("start", self.start_command),
CommandHandler("help", self.help_command),
CommandHandler("stats", self.stats_command),
CommandHandler("balance", self.balance_command),
CommandHandler("positions", self.positions_command),
CommandHandler("channels", self._handle_channels_command), # 使用新的处理方法,
CommandHandler("settings", lambda update, context:
self.show_settings(update.message))
]
for handler in commands:
self.application.add_handler(handler)
# 添加频道管理处理器
for handler in self.channel_management.get_handlers():
self.application.add_handler(handler)
# 回调查询处理器
self.application.add_handler(CallbackQueryHandler(self.handle_callback_query))
# 错误处理器
self.application.add_error_handler(self.error_handler)
# 添加主菜单处理器
self.application.add_handler(CommandHandler("start", self.main_menu.setup_main_menu))
# self.application.add_handler(MessageHandler(
# filters.TEXT & ~filters.COMMAND,
# self.main_menu.handle_menu_selection
# ))
async def show_main_menu(self, message):
"""显示主菜单"""
# 添加测试网标识
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
keyboard = [
[
InlineKeyboardButton(BT.CHANNEL_MANAGEMENT, callback_data="channel_management"),
InlineKeyboardButton(BT.TRADE_MANAGEMENT, callback_data="trade_management")
],
[
InlineKeyboardButton(BT.POSITION_OVERVIEW, callback_data="positions"),
InlineKeyboardButton(BT.ACCOUNT_STATS, callback_data="account_stats")
],
[
InlineKeyboardButton(BT.SETTINGS, callback_data="settings"),
InlineKeyboardButton(BT.HELP, callback_data="help")
]
]
await message.edit_text(
f"{network_indicator} 交易机器人\n\n"
"请从下面的菜单中选择一个选项:",
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def show_trade_management(self, message):
"""显示交易管理菜单"""
keyboard = [
[
InlineKeyboardButton(BT.VIEW_POSITIONS, callback_data="view_positions"),
InlineKeyboardButton(BT.CLOSE_POSITION, callback_data="close_position")
],
[
InlineKeyboardButton(BT.MODIFY_TP_SL, callback_data="modify_tp_sl"),
InlineKeyboardButton(BT.ORDER_HISTORY, callback_data="order_history")
],
[
InlineKeyboardButton(BT.RISK_SETTINGS, callback_data="risk_settings"),
InlineKeyboardButton(BT.BACK_MAIN, callback_data="main_menu")
]
]
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
await message.edit_text(
f"{network_indicator} 交易管理\n\n"
"• 查看和管理持仓\n"
"• 修改订单和设置\n"
"• 查看交易历史",
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def show_settings(self, update: Update):
"""显示设置菜单"""
keyboard = [
[
InlineKeyboardButton(BT.RISK_SETTINGS, callback_data="risk_settings"),
InlineKeyboardButton(BT.AUTO_TRADE_SETTINGS, callback_data="auto_trade_settings")
],
[
InlineKeyboardButton(BT.NOTIFICATION_SETTINGS, callback_data="notification_settings"),
InlineKeyboardButton(BT.API_SETTINGS, callback_data="api_settings")
],
[InlineKeyboardButton(BT.BACK_MAIN, callback_data="main_menu")]
]
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
if isinstance(update, Message):
await update.reply_text(
f"{network_indicator} 机器人设置\n\n"
"• 配置风险参数\n"
"• 设置自动交易规则\n"
"• 管理通知设置\n"
"• 更新API配置",
reply_markup=InlineKeyboardMarkup(keyboard)
)
else:
await update.edit_text(
f"{network_indicator} 机器人设置\n\n"
"• 配置风险参数\n"
"• 设置自动交易规则\n"
"• 管理通知设置\n"
"• 更新API配置",
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def show_positions_menu(self, message):
"""显示持仓概览和管理选项"""
try:
positions = await self.exchange_manager.get_all_positions()
keyboard = []
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
position_text = f"{network_indicator} 当前持仓:\n\n"
for exchange, exchange_positions in positions.items():
active_positions = [p for p in exchange_positions if p['size'] != 0]
if not active_positions:
continue
position_text += f"📈 {exchange}:\n"
for pos in active_positions:
direction = BT.DIRECTION_LONG if pos['size'] > 0 else BT.DIRECTION_SHORT
position_text += (
f"{pos['symbol']}: {direction}\n"
f"数量: {abs(pos['size'])}\n"
f"入场价: {pos['entry_price']:.2f}\n"
f"未实现盈亏: {pos['unrealized_pnl']:.2f} USDT\n\n"
)
keyboard.append([
InlineKeyboardButton(
f"修改 {pos['symbol']}",
callback_data=f"modify_{exchange}_{pos['symbol']}"
),
InlineKeyboardButton(
f"平仓 {pos['symbol']}",
callback_data=f"close_{exchange}_{pos['symbol']}"
)
])
if not keyboard:
position_text += "暂无持仓"
keyboard.append([InlineKeyboardButton(BT.BACK_MAIN, callback_data="main_menu")])
await message.edit_text(
position_text,
reply_markup=InlineKeyboardMarkup(keyboard)
)
except Exception as e:
logging.error(f"Error showing positions menu: {e}")
await message.edit_text(
"获取持仓信息失败,请稍后重试。",
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton(BT.BACK_MAIN, callback_data="main_menu")
]])
)
async def handle_position_modification(self, query: CallbackQuery):
"""处理持仓修改"""
try:
_, exchange, symbol = query.data.split('_')
keyboard = [
[
InlineKeyboardButton(BT.MODIFY_TP, callback_data=f"modify_tp_{exchange}_{symbol}"),
InlineKeyboardButton(BT.MODIFY_SL, callback_data=f"modify_sl_{exchange}_{symbol}")
],
[InlineKeyboardButton(BT.BACK_MAIN, callback_data="positions")]
]
position = await self.exchanges[exchange.upper()].fetch_positions(symbol)
if not position:
await query.message.edit_text("未找到持仓信息")
return
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
text = (
f"{network_indicator} 修改持仓\n\n"
f"交易对: {symbol}\n"
f"当前价格: {position['entry_price']}\n"
f"持仓大小: {position['size']}\n"
"请选择要修改的选项:"
)
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(keyboard))
except Exception as e:
logging.error(f"Error in handle_position_modification: {e}")
await query.message.edit_text("修改持仓时发生错误")
async def handle_trade_execution(self, query: CallbackQuery):
"""处理交易执行"""
try:
# 解析回调数据
_, symbol, signal_id = query.data.split('_')
signal_info = self.db.get_signal_info(int(signal_id))
if not signal_info:
await query.answer("信号已过期或无效")
return
# 创建交易信号对象
signal = TradingSignal(
exchange=signal_info.get('exchange', 'BINANCE'),
symbol=signal_info.get('symbol', symbol),
action=signal_info.get('signal_type', 'OPEN_LONG'), # 默认做多
entry_price=signal_info.get('entry_price'),
position_size=signal_info.get('position_size', self.config.trading.default_position_size),
leverage=signal_info.get('leverage', self.config.trading.default_leverage),
margin_mode=signal_info.get('margin_mode', 'cross')
)
# 处理止损和止盈
if signal_info.get('stop_loss'):
signal.stop_loss = float(signal_info['stop_loss'])
if signal_info.get('take_profit_levels'):
signal.take_profit_levels = [
TakeProfitLevel(tp['price'], tp['percentage'])
for tp in signal_info['take_profit_levels']
]
if signal_info.get('entry_zones'):
signal.entry_zones = [
EntryZone(zone['price'], zone['percentage'])
for zone in signal_info['entry_zones']
]
# 执行交易
if signal.is_valid():
network_indicator = "🏮 测试网" if self.config.trading.use_testnet else "🔵 主网"
# 更新UI显示执行状态
await query.edit_message_text(
f"{network_indicator} 执行交易中...\n\n"
f"交易对: {signal.symbol}\n"
f"方向: {'做多' if signal.action == 'OPEN_LONG' else '做空'}\n"
f"杠杆: {signal.leverage}X",
reply_markup=None
)
# 执行交易
result = await self.exchange_manager.execute_signal(signal)
if result.success:
message = (
f"{network_indicator} 交易执行成功✅\n\n"
f"交易对: {signal.symbol}\n"
f"方向: {'做多' if signal.action == 'OPEN_LONG' else '做空'}\n"
f"订单ID: {result.order_id}\n"
f"执行价格: {result.executed_price}\n"
f"数量: {result.executed_amount}"
)
# 如果有止损止盈单
if result.extra_info and 'orders' in result.extra_info:
message += "\n\n附加订单:"
for order in result.extra_info['orders']:
order_type = order.get('type', '')
if 'stop_loss' in order_type.lower():
message += f"\n止损订单: {order.get('order_id')}"
elif 'take_profit' in order_type.lower():
message += f"\n止盈订单: {order.get('order_id')}"
else:
message = (
f"{network_indicator} 交易执行失败❌\n\n"
f"交易对: {signal.symbol}\n"
f"错误: {result.error_message}"
)
# 更新消息
await query.edit_message_text(
message,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton("返回", callback_data="main_menu")
]])
)
else:
await query.answer("无效的交易信号")
except Exception as e:
logging.error(f"Error executing trade: {e}")
import traceback
logging.error(f"Traceback:\n{traceback.format_exc()}")
await query.answer("执行交易时发生错误")
async def handle_position_close(self, query: CallbackQuery):
"""处理持仓平仓"""
try:
_, exchange, symbol = query.data.split('_')
keyboard = [
[
InlineKeyboardButton(BT.CONFIRM_CLOSE, callback_data=f"confirm_close_{exchange}_{symbol}"),
InlineKeyboardButton(BT.CANCEL, callback_data="positions")
]
]
position = await self.exchanges[exchange.upper()].fetch_positions(symbol)
if not position:
await query.message.edit_text("未找到持仓信息")
return
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
direction = BT.DIRECTION_LONG if position['size'] > 0 else BT.DIRECTION_SHORT
text = (
f"{network_indicator} 确认平仓\n\n"
f"交易对: {symbol}\n"
f"持仓方向: {direction}\n"
f"持仓大小: {abs(position['size'])}\n"
f"开仓价格: {position['entry_price']}\n"
f"未实现盈亏: {position['unrealized_pnl']:.2f} USDT\n\n"
"确认要平仓此持仓吗?"
)
await query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(keyboard))
except Exception as e:
logging.error(f"Error in handle_position_close: {e}")
await query.message.edit_text("处理平仓请求时发生错误")
async def handle_callback_query(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""处理所有回调查询"""
query = update.callback_query
data = query.data
try:
if data == "channel_management":
await self.channel_management.show_channel_management(query.message)
if data.startswith(("risk_", "auto_", "notification_", "api_")):
await self.settings_manager.handle_settings_callback(update, context)
elif data in ["detailed_stats", "export_stats"]:
await self.stats_manager.handle_stats_callback(update, context)
elif data == "trade_management":
await self.show_trade_management(query.message)
elif data == "positions":
await self.show_positions_menu(query.message)
elif data == "account_stats":
await self.show_account_stats(query.message)
elif data == "settings":
await self.show_settings(query.message)
elif data == "help":
await self.show_help(query.message)
elif data == "main_menu":
await self.show_main_menu(query.message)
elif data.startswith("execute_"):
await self.handle_trade_execution(query)
elif data.startswith("modify_"):
await self.handle_position_modification(query)
elif data.startswith("close_"):
await self.handle_position_close(query)
elif data.startswith("confirm_execute_"):
await self.execute_confirmed_trade(query)
elif data.startswith("confirm_close_"):
await self.execute_confirmed_close(query)
elif any(data.startswith(prefix) for prefix in ["add_", "remove_", "list_", "edit_", "view_", "manage_"]):
await self.channel_management.handle_callback_query(update, context)
else:
await query.answer("未知的操作")
except Exception as e:
logging.error(f"Error in handle_callback_query: {e}")
await query.answer("处理请求时发生错误")
async def execute_confirmed_trade(self, query: CallbackQuery):
"""执行已确认的交易"""
try:
_, signal_id = query.data.split('_')
signal_info = self.db.get_signal_info(int(signal_id))
if not signal_info:
await query.answer("信号已过期")
return
# 执行交易
result = await self.exchange_manager.execute_signal(TradingSignal(**signal_info))
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
if result.success:
message = (
f"{network_indicator} 交易执行成功\n\n"
f"交易对: {signal_info['symbol']}\n"
f"订单ID: {result.order_id}\n"
f"执行价格: {result.executed_price}\n"
f"执行数量: {result.executed_amount}"
)
await self.notify_trade_execution(signal_info, result)
else:
message = (
f"{network_indicator} 交易执行失败\n\n"
f"错误: {result.error_message}"
)
await self.notify_trade_error(signal_info, result.error_message)
await query.message.edit_text(
message,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton(BT.BACK_MAIN, callback_data="main_menu")
]])
)
except Exception as e:
logging.error(f"Error executing confirmed trade: {e}")
await query.answer("执行交易时发生错误")
async def execute_confirmed_close(self, query: CallbackQuery):
"""执行已确认的平仓"""
try:
_, exchange, symbol = query.data.split('_')
result = await self.exchange_manager.close_position(exchange, symbol)
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
if result.success:
message = (
f"{network_indicator} 平仓成功\n\n"
f"交易对: {symbol}\n"
f"订单ID: {result.order_id}\n"
f"执行价格: {result.executed_price}\n"
f"执行数量: {result.executed_amount}"
)
else:
message = (
f"{network_indicator} 平仓失败\n\n"
f"错误: {result.error_message}"
)
await query.message.edit_text(
message,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton(BT.BACK_MAIN, callback_data="main_menu")
]])
)
except Exception as e:
logging.error(f"Error executing confirmed close: {e}")
await query.answer("执行平仓时发生错误")
async def monitor_signals(self):
"""监控活动信号"""
while True:
try:
active_signals = self.db.get_active_signals()
for signal in active_signals:
# 检查信号状态
await self.check_signal_status(signal)
# 检查是否需要调整止损
if signal.get('dynamic_sl'):
await self.check_stop_loss_adjustment(signal)
# 检查是否达到多级止盈目标
if signal.get('take_profit_levels'):
await self.check_take_profit_levels(signal)
# 更新统计数据
await self.update_signal_statistics(signal)
except Exception as e:
logging.error(f"Error in signal monitoring: {e}")
await asyncio.sleep(1)
async def check_take_profit_levels(self, signal: Dict[str, Any]):
"""检查多级止盈目标"""
try:
exchange_client = self.exchanges.get(signal['exchange'].upper())
if not exchange_client:
return
# 获取当前价格
ticker = await exchange_client.get_market_info(signal['symbol'])
current_price = ticker.last_price
# logging.info(f"---signal---{signal}")
# 检查每个止盈级别
for i, tp_level in enumerate(signal['take_profit_levels']):
tp_level:TakeProfitLevel
if tp_level.is_hit:
continue
# 判断是否达到止盈价格
if (signal['signal_type'] == 'OPEN_LONG' and current_price >= tp_level.price) or \
(signal['signal_type'] == 'OPEN_SHORT' and current_price <= tp_level.price):
# 执行部分平仓
size = signal['position_size'] * tp_level.percentage
result = await exchange_client.create_order(
OrderParams(
symbol=signal['symbol'],
side='sell' if signal['signal_type'] == 'OPEN_LONG' else 'buy',
order_type='market',
amount=size,
extra_params={'reduceOnly': True}
)
)
if result.success:
# 更新止盈状态
tp_level.is_hit = True
tp_level.hit_time = datetime.now()
# 记录止盈触发
self.db.add_tp_hit(signal['id'], i+1, current_price, size)
# 通知用户
await self.notify_tp_hit(signal, tp_level, current_price)
except Exception as e:
logging.error(f"Error checking take profit levels: {e}")
async def monitor_risk_metrics(self):
"""监控风险指标"""
while True:
try:
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
# 获取账户概览
overview = await self.exchange_manager.get_account_overview()
# 检查风险指标
for exchange, data in overview.items():
if data['account_health'] in ['WARNING', 'CRITICAL']:
await self.notify_risk_warning(network_indicator, exchange, data)
# 更新风险统计
self.db.update_risk_metrics({
'exchange': exchange,
'margin_usage': data['margin_ratio'],
'total_exposure': data.get('total_exposure', 0),
'account_health': data['account_health']
})
except Exception as e:
logging.error(f"Error in risk monitoring: {e}")
await asyncio.sleep(300) # 5分钟检查一次
# main.py 中的 TradingBot 类
async def check_signal_status(self, signal: Dict[str, Any]):
"""检查信号状态"""
try:
orders = self.db.get_signal_orders(signal['id'])
# 修正 entry_zones 的处理
if signal.get('entry_zones'):
try:
entry_zones = json.loads(signal['entry_zones']) if isinstance(signal['entry_zones'], str) else signal['entry_zones']
# 使用字典访问而不是对象属性
filled_zones = sum(1 for zone in entry_zones if isinstance(zone, dict) and zone.get('status') == 'FILLED')
total_zones = len(entry_zones)
if filled_zones == total_zones:
await self.notify_full_entry(signal)
self.db.update_signal_status(signal['id'], 'ACTIVE')
except json.JSONDecodeError:
logging.error(f"Invalid entry_zones JSON: {signal['entry_zones']}")
else:
entry_order = next((o for o in orders if o['order_type'] == 'ENTRY'), None)
if entry_order and entry_order['status'] == 'FILLED':
await self.notify_entry_filled(signal)
self.db.update_signal_status(signal['id'], 'ACTIVE')
except Exception as e:
logging.error(f"Error checking signal status: {e}")
async def _check_take_profit_levels(self, exchange_name: str, position: dict):
"""修正止盈目标检查"""
try:
if position['size'] == 0:
return
signal_key = f"{exchange_name}_{position['symbol']}"
signal = self.active_signals.get(signal_key)
if not signal:
return
# 正确处理 take_profit_levels
try:
tp_levels = signal.get('take_profit_levels', [])
if isinstance(tp_levels, str):
tp_levels = json.loads(tp_levels)
current_price = position['mark_price']
for tp in tp_levels:
# 使用字典访问
if tp.get('is_hit'):
continue
price = float(tp['price'])
if signal['action'] == 'OPEN_LONG':
if current_price >= price:
await self._execute_take_profit(exchange_name, position, tp)
else: # OPEN_SHORT
if current_price <= price:
await self._execute_take_profit(exchange_name, position, tp)
except (json.JSONDecodeError, KeyError) as e:
logging.error(f"Error processing take profit levels: {e}")
except Exception as e:
logging.error(f"Error checking take profit levels: {e}")
async def notify_entry_filled(self, signal: Dict[str, Any]):
"""通知入场订单完成"""
try:
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
message = (
f"{network_indicator} 入场订单已完成\n\n"
f"交易对: {signal['symbol']}\n"
f"方向: {BT.DIRECTION_LONG if signal['action'] == 'OPEN_LONG' else BT.DIRECTION_SHORT}\n"
f"入场价格: {signal['entry_price']}\n"
f"数量: {signal['position_size']}\n"
f"杠杆: {signal['leverage']}x"
)
await self.notify_owner(message)
except Exception as e:
logging.error(f"Error sending entry notification: {e}")
async def notify_full_entry(self, signal: Dict[str, Any]):
"""通知区间入场完成"""
try:
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
message = (
f"{network_indicator} 区间入场已完成\n\n"
f"交易对: {signal['symbol']}\n"
f"方向: {BT.DIRECTION_LONG if signal['action'] == 'OPEN_LONG' else BT.DIRECTION_SHORT}\n\n"
"入场区间:\n"
)
for zone in signal['entry_zones']:
message += f"价格: {zone['price']} ({zone['percentage'] * 100}%)\n"
message += f"\n总数量: {signal['position_size']}\n"
message += f"杠杆: {signal['leverage']}x"
await self.notify_owner(message)
except Exception as e:
logging.error(f"Error sending full entry notification: {e}")
async def notify_tp_hit(self, signal: Dict[str, Any], tp_level: Dict[str, Any], price: float):
"""通知止盈触发"""
try:
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
message = (
f"{network_indicator} 止盈目标已达成\n\n"
f"交易对: {signal['symbol']}\n"
f"方向: {BT.DIRECTION_LONG if signal['action'] == 'OPEN_LONG' else BT.DIRECTION_SHORT}\n"
f"触发价格: {price}\n"
f"平仓比例: {tp_level['percentage'] * 100}%\n"
f"止盈级别: {tp_level['level']}/{len(signal['take_profit_levels'])}"
)
await self.notify_owner(message)
except Exception as e:
logging.error(f"Error sending TP hit notification: {e}")
async def notify_risk_warning(self, network_indicator: str, exchange: str, data: Dict[str, Any]):
"""发送风险警告"""
try:
message = (
f"{network_indicator} 风险警告!\n\n"
f"交易所: {exchange}\n"
f"账户状态: {data['account_health']}\n"
f"保证金使用率: {data['margin_ratio']:.2f}%\n"
f"可用保证金: {data['available_margin']:.2f} USDT\n"
f"未实现盈亏: {data['total_unrealized_pnl']:.2f} USDT"
)
await self.notify_owner(message)
except Exception as e:
logging.error(f"Error sending risk warning: {e}")
async def update_signal_statistics(self, signal: Dict[str, Any]):
"""更新信号统计数据"""
try:
exchange = self.exchanges.get(signal['exchange'].upper())
if not exchange:
return
position = await exchange.fetch_positions(signal['symbol'])
if not position:
return
# 更新统计数据
stats = {
'current_pnl': position['unrealized_pnl'],
'max_profit': position.get('max_profit', 0),
'max_drawdown': position.get('max_drawdown', 0),
'holding_time': (datetime.now() - signal['created_at']).total_seconds() / 3600,
'status': signal['status']
}
self.db.update_signal_statistics(signal['id'], stats)
except Exception as e:
logging.error(f"Error updating signal statistics: {e}")
async def generate_statistics(self) -> dict:
"""生成详细的交易统计"""
try:
trades = self.db.get_recent_trades(days=30)
# 计算各种统计数据
daily_pnl = sum(t['pnl'] for t in trades if t['close_time'].date() == datetime.now().date())
weekly_pnl = sum(t['pnl'] for t in trades if t['close_time'].date() >= (datetime.now() - timedelta(days=7)).date())
monthly_pnl = sum(t['pnl'] for t in trades if t['close_time'].date() >= (datetime.now() - timedelta(days=30)).date())
winning_trades = [t for t in trades if t['pnl'] > 0]
losing_trades = [t for t in trades if t['pnl'] < 0]
stats = {
'daily_pnl': daily_pnl,
'weekly_pnl': weekly_pnl,
'monthly_pnl': monthly_pnl,
'win_rate': len(winning_trades) / len(trades) * 100 if trades else 0,
'avg_win': sum(t['pnl'] for t in winning_trades) / len(winning_trades) if winning_trades else 0,
'avg_loss': sum(t['pnl'] for t in losing_trades) / len(losing_trades) if losing_trades else 0,
'total_trades': len(trades),
'winning_trades': len(winning_trades),
'losing_trades': len(losing_trades),
'is_testnet': self.config.trading.use_testnet
}
return stats
except Exception as e:
logging.error(f"Error generating statistics: {e}")
return {}
async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""处理 /start 命令"""
if not self.is_authorized(update.effective_user.id):
await update.message.reply_text(
"未经授权的访问。请联系管理员。"
)
return
network_indicator = BT.TESTNET_INDICATOR if self.config.trading.use_testnet else BT.MAINNET_INDICATOR
keyboard = [
[
InlineKeyboardButton(BT.CHANNEL_MANAGEMENT, callback_data="channel_management"),
InlineKeyboardButton(BT.TRADE_MANAGEMENT, callback_data="trade_management")
],
[
InlineKeyboardButton(BT.POSITION_OVERVIEW, callback_data="positions"),
InlineKeyboardButton(BT.ACCOUNT_STATS, callback_data="account_stats")
],
[
InlineKeyboardButton(BT.SETTINGS, callback_data="settings"),
InlineKeyboardButton(BT.HELP, callback_data="help")
]
]
await update.message.reply_text(
f"{network_indicator} 欢迎使用交易机器人!\n\n"
"请从下面的菜单中选择一个选项:",
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def setup_commands(self):
"""设置机器人命令"""
commands = [
BotCommand("start", "启动机器人并显示主菜单"),
BotCommand("help", "显示帮助信息"),
BotCommand("stats", "查看交易统计"),
BotCommand("balance", "查看账户余额"),
BotCommand("positions", "查看当前持仓"),
BotCommand("channels", "管理监控频道"),
BotCommand("settings", "机器人设置"),
BotCommand("cancel", "取消当前操作")
]
await self.application.bot.set_my_commands(commands)
async def start(self):
"""启动机器人"""
try:
# 初始化交易所连接
if not await self.exchange_manager.initialize():
logging.error("Failed to initialize exchanges")
return
# 启动 Telethon 客户端
await self.client.start(phone=self.config.PHONE_NUMBER)
# 注册 Telethon 事件处理器