Repository navigation
Expand file tree
/
Copy pathweb_server.py
More file actions
1181 lines (1029 loc) · 46.4 KB
/
Copy pathweb_server.py
File metadata and controls
1181 lines (1029 loc) · 46.4 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
# -*- coding: utf-8 -*-
"""
Web服务模块,提供RESTful API接口与前端交互
"""
import os
import time
import json
import threading
import sqlite3
from datetime import datetime
from flask import Flask, request, jsonify, send_from_directory, make_response, Response, stream_with_context
from flask_cors import CORS
import pandas as pd
import Methods as Methods
import config
from logger import get_logger
from data_manager import get_data_manager
from indicator_calculator import get_indicator_calculator
from position_manager import get_position_manager
from trading_executor import get_trading_executor
from strategy import get_trading_strategy
import utils
# 获取logger
logger = get_logger("web_server")
webpage_dir = 'web1.0'
# 创建Flask应用
app = Flask(__name__, static_folder=webpage_dir, static_url_path='')
# 允许跨域请求
CORS(app)
# 获取各个模块的实例
data_manager = get_data_manager()
indicator_calculator = get_indicator_calculator()
position_manager = get_position_manager()
trading_executor = get_trading_executor()
trading_strategy = get_trading_strategy()
# 实时推送的数据
realtime_data = {
'positions': {},
'latest_prices': {},
'trading_signals': {},
'account_info': {},
'positions_all': [] # Add new field for all positions data
}
# 实时推送线程
push_thread = None
stop_push_flag = False
@app.route('/')
def index():
"""Serve the index.html file"""
return send_from_directory(os.path.join(os.path.dirname(__file__), webpage_dir), 'index.html')
@app.route('/<path:filename>')
def serve_static(filename):
"""Serve static files from the 'web' directory"""
return send_from_directory(os.path.join(os.path.dirname(__file__), webpage_dir), filename)
@app.route('/api/connection/status', methods=['GET'])
def connection_status():
"""返回API连接状态"""
try:
# 检查 qmt_trader 的连接状态
is_connected = False
if hasattr(position_manager, 'qmt_trader') and position_manager.qmt_trader:
if hasattr(position_manager.qmt_trader, 'xt_trader') and position_manager.qmt_trader.xt_trader:
if hasattr(position_manager.qmt_trader.xt_trader, 'is_connected'):
is_connected = position_manager.qmt_trader.xt_trader.is_connected()
else:
# 尝试其他检查方式
is_connected = True # 假设已连接,实际应根据具体情况修改
return jsonify({
'status': 'success',
'connected': bool(is_connected), # 确保返回布尔值
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
logger.error(f"检查API连接状态时出错: {str(e)}")
return jsonify({
'status': 'error',
'connected': False,
'message': f"检查API连接状态时出错: {str(e)}",
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
@app.route('/api/status', methods=['GET'])
def get_status():
"""获取系统状态"""
try:
# 从 position_manager 获取账户信息
account_info = position_manager.get_account_info() or {}
# 如果没有账户信息,使用默认值
if not account_info:
account_info = {
'account_id': '--',
'account_type': '--',
'available': 0.0,
'frozen_cash': 0.0,
'market_value': 0.0,
'total_asset': 0.0,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
# 格式化为前端期望的结构
account_data = {
'id': account_info.get('account_id', '--'),
'availableBalance': account_info.get('available', 0.0),
'maxHoldingValue': account_info.get('market_value', 0.0),
'totalAssets': account_info.get('total_asset', 0.0),
'timestamp': account_info.get('timestamp', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
}
# 监控状态 - 使用独立的配置标志,不再依赖线程状态判断
is_monitoring = config.ENABLE_MONITORING
# 添加额外日志用于调试
logger.debug(f"当前状态: UI监控={is_monitoring}, 自动交易={config.ENABLE_AUTO_TRADING}, 持仓监控={config.ENABLE_POSITION_MONITOR}")
# 获取全局设置状态 - 明确区分自动交易和监控状态
system_settings = {
'isMonitoring': is_monitoring, # 监控状态
'enableAutoTrading': config.ENABLE_AUTO_TRADING, # 自动交易状态
'positionMonitorRunning': config.ENABLE_POSITION_MONITOR, # 增加持仓监控状态
'allowBuy': getattr(config, 'ENABLE_ALLOW_BUY', True),
'allowSell': getattr(config, 'ENABLE_ALLOW_SELL', True),
'simulationMode': getattr(config, 'ENABLE_SIMULATION_MODE', False)
}
return jsonify({
'status': 'success',
'isMonitoring': is_monitoring, # 顶层也返回监控状态
'account': account_data,
'settings': system_settings,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
logger.error(f"获取系统状态时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"获取系统状态时出错: {str(e)}"
}), 500
@app.route('/api/positions', methods=['GET'])
def get_positions():
"""获取持仓信息"""
try:
positions = trading_executor.get_stock_positions()
positions_df = pd.DataFrame(positions)
# 计算持仓指标
metrics = utils.calculate_position_metrics(positions_df)
# 更新实时数据
for pos in positions:
stock_code = pos['stock_code']
realtime_data['positions'][stock_code] = pos
# 获取所有持仓数据
positions_all_df = position_manager.get_all_positions_with_all_fields()
realtime_data['positions_all'] = positions_all_df.to_dict('records')
response = make_response(jsonify({
'status': 'success',
'data': {
'positions': positions,
'metrics': metrics,
'positions_all': realtime_data['positions_all']
}
}))
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
logger.error(f"获取持仓信息时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"获取持仓信息时出错: {str(e)}"
}), 500
@app.route('/api/trade-records', methods=['GET'])
def get_trade_records():
"""获取交易记录"""
try:
# 从交易执行器获取交易记录
trades_df = trading_executor.get_trades()
# 如果没有交易记录,返回空列表
if trades_df.empty:
return jsonify({'status': 'success', 'data': []})
# 确保包含股票名称字段,如果没有则尝试获取
if 'stock_name' not in trades_df.columns or trades_df['stock_name'].isnull().any():
data_manager = get_data_manager()
def get_name(code):
try:
return data_manager.get_stock_name(code)
except:
return code
trades_df['stock_name'] = trades_df['stock_code'].apply(get_name)
# Format 'trade_time' to 'YYYY-MM-DD'
if 'trade_time' in trades_df.columns:
trades_df['trade_time'] = pd.to_datetime(trades_df['trade_time']).dt.strftime('%Y-%m-%d %H:%M:%S')
# Replace NaN with None (which will become null in JSON)
trades_df = trades_df.replace({pd.NA: None, float('nan'): None})
# 将 DataFrame 转换为 JSON 格式
trade_records = trades_df.to_dict(orient='records')
response = make_response(jsonify({
'status': 'success',
'data': trade_records
}))
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
logger.error(f"获取交易记录时出错: {str(e)}")
return jsonify({'status': 'error', 'message': f"获取交易记录时出错: {str(e)}"}), 500
# 配置管理API
@app.route('/api/config', methods=['GET'])
def get_config():
"""获取系统配置"""
try:
# 从config模块获取配置项
config_data = {
"singleBuyAmount": config.POSITION_UNIT,
"firstProfitSell": config.INITIAL_TAKE_PROFIT_RATIO * 100,
"firstProfitSellEnabled": config.ENABLE_DYNAMIC_STOP_PROFIT,
"stockGainSellPencent": config.INITIAL_TAKE_PROFIT_RATIO_PERCENTAGE * 100,
"allowBuy": getattr(config, 'ENABLE_ALLOW_BUY', True),
"allowSell": getattr(config, 'ENABLE_ALLOW_SELL', True),
"stopLossBuy": abs(config.BUY_GRID_LEVELS[1] - 1) * 100,
"stopLossBuyEnabled": True,
"stockStopLoss": abs(config.STOP_LOSS_RATIO) * 100,
"StopLossEnabled": True,
"singleStockMaxPosition": config.MAX_POSITION_VALUE,
"totalMaxPosition": config.MAX_TOTAL_POSITION_RATIO * 1000000,
"connectPort": config.WEB_SERVER_PORT,
"totalAccounts": "127.0.0.1",
"globalAllowBuySell": config.ENABLE_AUTO_TRADING,
"simulationMode": getattr(config, 'ENABLE_SIMULATION_MODE', False),
# 卖出策略配置
"sellStrategyEnabled": getattr(config, 'ENABLE_SELL_STRATEGY', True),
"sellRule1Rise": getattr(config, 'SELL_RULE1_RISE_THRESHOLD', 0.03) * 100,
"sellRule1Drawdown": getattr(config, 'SELL_RULE1_DRAWDOWN_THRESHOLD', 0.02) * 100,
"sellRule2Rise": getattr(config, 'SELL_RULE2_RISE_THRESHOLD', 0.05) * 100,
"sellRule2Drawdown": getattr(config, 'SELL_RULE2_DRAWDOWN_THRESHOLD', 0.03) * 100,
"sellRule3Gain": getattr(config, 'SELL_RULE3_GAIN_THRESHOLD', 0.06) * 100,
"sellRule3Drawdown": getattr(config, 'SELL_RULE3_DRAWDOWN_THRESHOLD', 0.03) * 100,
"sellRule4Gain": getattr(config, 'SELL_RULE4_GAIN_THRESHOLD', 0.08) * 100,
"sellRule4Drawdown": getattr(config, 'SELL_RULE4_DRAWDOWN_THRESHOLD', 0.04) * 100,
"sellRule5Enabled": getattr(config, 'SELL_RULE5_ENABLE', True),
"sellRule6Seal": getattr(config, 'SELL_RULE6_SEAL_THRESHOLD', 5000000),
"sellRule7Timeout": getattr(config, 'SELL_RULE7_CANCEL_TIMEOUT', 2),
"sellRule8Drawdown": getattr(config, 'SELL_RULE8_MAX_DRAWDOWN', 0.05) * 100
}
# 获取参数范围
param_ranges = {k: {'min': v['min'], 'max': v['max']} for k, v in config.CONFIG_PARAM_RANGES.items()}
# 添加卖出策略参数范围
if hasattr(config, 'SELL_STRATEGY_PARAM_RANGES'):
sell_ranges = {k: {'min': v['min'], 'max': v['max']} for k, v in config.SELL_STRATEGY_PARAM_RANGES.items()}
param_ranges.update(sell_ranges)
return jsonify({
'status': 'success',
'data': config_data,
'ranges': param_ranges
})
except Exception as e:
logger.error(f"获取配置时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"获取配置时出错: {str(e)}"
}), 500
@app.route('/api/config/save', methods=['POST'])
def save_config():
"""保存系统配置"""
try:
config_data = request.json
# 参数校验
validation_errors = []
for param_name, value in config_data.items():
# 检查类型,跳过布尔值和字符串
if isinstance(value, bool) or isinstance(value, str):
continue
# 校验参数
is_valid, error_msg = c
8BD0
onfig.validate_config_param(param_name, value)
if not is_valid:
validation_errors.append(error_msg)
# 如果有验证错误,返回错误信息
if validation_errors:
return jsonify({
'status': 'error',
'message': '参数校验失败',
'errors': validation_errors
}), 400
# 更新配置
# 注意:这里只是临时更新运行时配置,不会修改配置文件
# 在实际应用中,您可能需要将配置写入配置文件
# 更新主要参数
if "singleBuyAmount" in config_data:
config.POSITION_UNIT = float(config_data["singleBuyAmount"])
if "firstProfitSell" in config_data:
config.INITIAL_TAKE_PROFIT_RATIO = float(config_data["firstProfitSell"]) / 100
if "firstProfitSellEnabled" in config_data:
config.ENABLE_DYNAMIC_STOP_PROFIT = bool(config_data["firstProfitSellEnabled"])
if "stockGainSellPencent" in config_data:
config.INITIAL_TAKE_PROFIT_RATIO_PERCENTAGE = float(config_data["stockGainSellPencent"]) / 100
if "stopLossBuy" in config_data:
# 更新第二个网格级别
ratio = 1 - float(config_data["stopLossBuy"]) / 100
config.BUY_GRID_LEVELS[1] = ratio
if "stockStopLoss" in config_data:
config.STOP_LOSS_RATIO = -float(config_data["stockStopLoss"]) / 100
if "singleStockMaxPosition" in config_data:
config.MAX_POSITION_VALUE = float(config_data["singleStockMaxPosition"])
if "totalMaxPosition" in config_data:
config.MAX_TOTAL_POSITION_RATIO = float(config_data["totalMaxPosition"]) / 1000000
# 开关类参数
if "allowBuy" in config_data:
setattr(config, 'ENABLE_ALLOW_BUY', bool(config_data["allowBuy"]))
if "allowSell" in config_data:
setattr(config, 'ENABLE_ALLOW_SELL', bool(config_data["allowSell"]))
if "globalAllowBuySell" in config_data:
old_auto_trading = config.ENABLE_AUTO_TRADING
config.ENABLE_AUTO_TRADING = bool(config_data["globalAllowBuySell"])
logger.info(f"自动交易总开关: {old_auto_trading} -> {config.ENABLE_AUTO_TRADING}")
# 卖出策略配置更新
if "sellStrategyEnabled" in config_data:
setattr(config, 'ENABLE_SELL_STRATEGY', bool(config_data["sellStrategyEnabled"]))
if "sellRule1Rise" in config_data:
setattr(config, 'SELL_RULE1_RISE_THRESHOLD', float(config_data["sellRule1Rise"]) / 100)
if "sellRule1Drawdown" in config_data:
setattr(config, 'SELL_RULE1_DRAWDOWN_THRESHOLD', float(config_data["sellRule1Drawdown"]) / 100)
if "sellRule2Rise" in config_data:
setattr(config, 'SELL_RULE2_RISE_THRESHOLD', float(config_data["sellRule2Rise"]) / 100)
if "sellRule2Drawdown" in config_data:
setattr(config, 'SELL_RULE2_DRAWDOWN_THRESHOLD', float(config_data["sellRule2Drawdown"]) / 100)
if "sellRule3Gain" in config_data:
setattr(config, 'SELL_RULE3_GAIN_THRESHOLD', float(config_data["sellRule3Gain"]) / 100)
if "sellRule3Drawdown" in config_data:
setattr(config, 'SELL_RULE3_DRAWDOWN_THRESHOLD', float(config_data["sellRule3Drawdown"]) / 100)
if "sellRule4Gain" in config_data:
setattr(config, 'SELL_RULE4_GAIN_THRESHOLD', float(config_data["sellRule4Gain"]) / 100)
if "sellRule4Drawdown" in config_data:
setattr(config, 'SELL_RULE4_DRAWDOWN_THRESHOLD', float(config_data["sellRule4Drawdown"]) / 100)
if "sellRule5Enabled" in config_data:
setattr(config, 'SELL_RULE5_ENABLE', bool(config_data["sellRule5Enabled"]))
if "sellRule6Seal" in config_data:
setattr(config, 'SELL_RULE6_SEAL_THRESHOLD', int(config_data["sellRule6Seal"]))
if "sellRule7Timeout" in config_data:
setattr(config, 'SELL_RULE7_CANCEL_TIMEOUT', int(config_data["sellRule7Timeout"]))
if "sellRule8Drawdown" in config_data:
setattr(config, 'SELL_RULE8_MAX_DRAWDOWN', float(config_data["sellRule8Drawdown"]) / 100)
# 在处理保存配置的API中添加
if "simulationMode" in config_data:
old_simulation_mode = getattr(config, 'ENABLE_SIMULATION_MODE', False)
new_simulation_mode = bool(config_data["simulationMode"])
# 如果模式发生变化
if old_simulation_mode != new_simulation_mode:
setattr(config, 'ENABLE_SIMULATION_MODE', new_simulation_mode)
# 模式变化时重新初始化内存数据库
position_manager = get_position_manager()
# 创建新的内存连接
position_manager.memory_conn = sqlite3.connect(":memory:", check_same_thread=False)
position_manager._create_memory_table()
position_manager._sync_db_to_memory() # 从SQLite重新加载数据
# 添加这部分代码-切换模式时只重置了内存数据库,但没有更新trading_executor的模拟账户状态
# trading_executor = get_trading_executor()
# if new_simulation_mode:
# trading_executor.init_simulation_account() # 初始化模拟账户
logger.warning(f"交易模式切换: {'模拟交易' if new_simulation_mode else '实盘交易'}")
logger.info(f"配置已更新: {config_data}")
return jsonify({
'status': 'success',
'message': '配置已保存并应用',
'isMonitoring': config.ENABLE_MONITORING, # 返回不变的监控状态
'autoTradingEnabled': config.ENABLE_AUTO_TRADING
})
except Exception as e:
logger.error(f"保存配置时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"保存配置失败: {str(e)}"
}), 500
@app.route('/api/monitor/start', methods=['POST'])
def start_monitor():
"""启动监控 - 仅控制前端数据刷新"""
try:
old_state = config.ENABLE_MONITORING
config.ENABLE_MONITORING = True
logger.info(f"UI监控状态变更: {old_state} -> {config.ENABLE_MONITORING} (通过API)")
return jsonify({
'status': 'success',
'message': '监控已启动',
'isMonitoring': config.ENABLE_MONITORING,
'autoTradingEnabled': config.ENABLE_AUTO_TRADING # 返回不变的自动交易状态
})
except Exception as e:
logger.error(f"启动监控时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"启动监控失败: {str(e)}"
}), 500
@app.route('/api/monitor/stop', methods=['POST'])
def stop_monitor():
"""停止监控"""
try:
old_state = config.ENABLE_MONITORING
# 确保变量类型一致,统一使用布尔值
config.ENABLE_MONITORING = False
# 如果状态没有发生变化,发出警告日志
if old_state == config.ENABLE_MONITORING:
logger.warning(f"UI监控状态未变化: {old_state} -> {config.ENABLE_MONITORING} (通过API)")
else:
logger.info(f"UI监控状态变更: {old_state} -> {config.ENABLE_MONITORING} (通过API)")
return jsonify({
'status': 'success',
'message': '监控已停止',
'isMonitoring': config.ENABLE_MONITORING, # 明确返回新状态
'autoTradingEnabled': config.ENABLE_AUTO_TRADING # 同时返回自动交易状态
})
except Exception as e:
logger.error(f"停止监控时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"停止监控失败: {str(e)}"
}), 500
@app.route('/api/data_sources/status', methods=['GET'])
def get_data_sources_status():
"""获取数据源状态"""
try:
# 添加更详细的错误处理
try:
from realtime_data_manager import get_realtime_data_manager
manager = get_realtime_data_manager()
except ImportError as e:
logger.error(f"导入realtime_data_manager失败: {str(e)}")
return jsonify({
'status': 'error',
'message': f"数据管理器模块导入失败: {str(e)}"
}), 500
except Exception as e:
logger.error(f"初始化数据管理器失败: {str(e)}")
return jsonify({
'status': 'error',
'message': f"数据管理器初始化失败: {str(e)}"
}), 500
status = manager.get_source_status()
return jsonify({
'status': 'success',
'data': status,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
logger.error(f"获取数据源状态时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"获取数据源状态失败: {str(e)}"
}), 500
@app.route('/api/data_sources/switch', methods=['POST'])
def switch_data_source():
"""手动切换数据源"""
try:
data = request.json
if not data:
return jsonify({
'status': 'error',
'message': '请求数据不能为空'
}), 400
source_name = data.get('source_name')
if not source_name:
return jsonify({
'status': 'error',
'message': '缺少source_name参数'
}), 400
# 数据源名称映射
source_mapping = {
'MootdxSource': 'Mootdx',
'XtQuantSource': 'XtQuant',
'Mootdx': 'Mootdx',
'XtQuant': 'XtQuant'
}
actual_source_name = source_mapping.get(source_name, source_name)
try:
from realtime_data_manager import get_realtime_data_manager
manager = get_realtime_data_manager()
except Exception as e:
return jsonify({
'status': 'error',
'message': f'数据管理器初始化失败: {str(e)}'
}), 500
# 使用新的切换方法
if manager.switch_to_source(actual_source_name):
return jsonify({
'status': 'success',
'message': f"已切换到数据源: {actual_source_name}",
'current_source': actual_source_name
})
else:
return jsonify({
'status': 'error',
'message': f"无法切换到数据源: {actual_source_name},请检查数据源名称是否正确"
}), 400
except Exception as e:
logger.error(f"切换数据源时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"切换数据源失败: {str(e)}"
}), 500
@app.route('/api/realtime/quote/<stock_code>', methods=['GET'])
def get_realtime_quote(stock_code):
"""获取单只股票的实时行情"""
try:
# 直接从实时数据管理器获取数据
from realtime_data_manager import get_realtime_data_manager
manager = get_realtime_data_manager()
start_time = time.time()
data = manager.get_realtime_data(stock_code)
end_time = time.time()
if data:
data['response_time_ms'] = round((end_time - start_time) * 1000, 2)
return jsonify({
'status': 'success',
'data': data,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
else:
return jsonify({
'status': 'error',
'message': f'无法获取{stock_code}的实时数据'
}), 404
except Exception as e:
logger.error(f"获取实时行情时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f'获取实时行情失败: {str(e)}'
}), 500
@app.route('/api/realtime/test/<stock_code>', methods=['GET'])
def test_all_sources(stock_code):
"""测试所有数据源获取指定股票数据"""
try:
from realtime_data_manager import get_realtime_data_manager
manager = get_realtime_data_manager()
results = {}
# 测试每个数据源
for source in manager.data_sources:
start_time = time.time()
try:
data = source.get_data(stock_code)
end_time = time.time()
if data:
results[source.name] = {
'success': True,
'data': data,
'response_time_ms': round((end_time - start_time) * 1000, 2),
'error_count': source.error_count,
'is_healthy': source.is_healthy
}
else:
results[source.name] = {
'success': False,
'error': '无数据返回',
'response_time_ms': round((end_time - start_time) * 1000, 2),
'error_count': source.error_count,
'is_healthy': source.is_healthy
}
except Exception as e:
end_time = time.time()
results[source.name] = {
'success': False,
'error': str(e),
'response_time_ms': round((end_time - start_time) * 1000, 2),
'error_count': source.error_count,
'is_healthy': source.is_healthy
}
return jsonify({
'status': 'success',
'stock_code': stock_code,
'results': results,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
logger.error(f"测试所有数据源时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f'测试失败: {str(e)}'
}), 500
@app.route('/api/debug/status', methods=['GET'])
def debug_status():
"""返回详细的系统状态,用于调试"""
try:
return jsonify({
'status': 'success',
'system_status': {
'ENABLE_MONITORING': config.ENABLE_MONITORING,
'ENABLE_AUTO_TRADING': config.ENABLE_AUTO_TRADING,
'ENABLE_POSITION_MONITOR': config.ENABLE_POSITION_MONITOR,
'ENABLE_ALLOW_BUY': getattr(config, 'ENABLE_ALLOW_BUY', True),
'ENABLE_ALLOW_SELL': getattr(config, 'ENABLE_ALLOW_SELL', True),
'ENABLE_SIMULATION_MODE': getattr(config, 'ENABLE_SIMULATION_MODE', False),
},
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
logger.error(f"获取调试状态时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"获取调试状态失败: {str(e)}"
}), 500
# @app.route('/api/debug/db-test', methods=['GET'])
# def test_database():
# """测试数据库连接"""
# try:
# cursor = data_manager.conn.cursor()
# cursor.execute("SELECT COUNT(*) FROM trade_records")
# count = cursor.fetchone()[0]
# return jsonify({
# 'status': 'success',
# 'message': '数据库连接正常',
# 'trade_records_count': count
# })
# except Exception as e:
# return jsonify({
# 'status': 'error',
# 'message': f"数据库连接错误: {str(e)}"
# }), 500
@app.route('/api/logs/clear', methods=['POST'])
def clear_logs():
"""清空当天日志"""
try:
# 获取当天日期
today = datetime.now().strftime('%Y-%m-%d')
# 执行清空当天日志的操作
cursor = data_manager.conn.cursor()
# 修改SQL,添加日期过滤条件
cursor.execute("DELETE FROM trade_records WHERE DATE(trade_time) = ?", (today,))
affected_rows = cursor.rowcount
data_manager.conn.commit()
logger.info(f"已清除当天({today})的交易记录,共{affected_rows}条")
return jsonify({
'status': 'success',
'message': f'已清除当天交易记录,共{affected_rows}条'
})
except Exception as e:
logger.error(f"清空当天日志时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"清空当天日志失败: {str(e)}"
}), 500
# @app.route('/api/data/clear_current', methods=['POST'])
# def clear_current_data():
# try:
# # 修改:清空内存数据库中的持仓数据,而非SQLite
# cursor = position_manager.memory_conn.cursor()
# cursor.execute("DELETE FROM positions")
# position_manager.memory_conn.commit()
# # 重置缓存
# position_manager.positions_cache = None
# position_manager.last_position_update_time = 0
# logger.info("内存数据库中的持仓数据已清空")
# return jsonify({
# 'status': 'success',
# 'message': '当前数据已清空'
# })
# except Exception as e:
# logger.error(f"清空当前数据时出错: {str(e)}")
# return jsonify({
# 'status': 'error',
# 'message': f"清空当前数据失败: {str(e)}"
# }), 500
@app.route('/api/data/clear_buysell', methods=['POST'])
def clear_buysell_data():
"""清空买入/卖出数据"""
try:
# 清空交易记录
cursor = data_manager.conn.cursor()
cursor.execute("DELETE FROM trade_records")
data_manager.conn.commit()
return jsonify({
'status': 'success',
'message': '买入/卖出数据已清空'
})
except Exception as e:
logger.error(f"清空买入/卖出数据时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"清空买入/卖出数据失败: {str(e)}"
}), 500
@app.route('/api/data/import', methods=['POST'])
def import_data():
"""导入保存数据"""
try:
# 这里需要实现导入数据的逻辑
# 由于没有具体实现,返回成功消息
return jsonify({
'status': 'success',
'message': '数据导入成功'
})
except Exception as e:
logger.error(f"导入数据时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"导入数据失败: {str(e)}"
}), 500
@app.route('/api/holdings/init', methods=['POST'])
def init_holdings():
"""初始化持仓数据"""
try:
# 获取配置数据
if request.is_json:
config_data = request.json
# 校验并保存配置
# 这里重复使用save_config的代码
validation_errors = []
for param_name, value in config_data.items():
# 检查类型,跳过布尔值和字符串
if isinstance(value, bool) or isinstance(value, str):
continue
# 校验参数
is_valid, error_msg = config.validate_config_param(param_name, value)
if not is_valid:
validation_errors.append(error_msg)
# 如果有验证错误,返回错误信息
if validation_errors:
return jsonify({
'status': 'error',
'message': '参数校验失败,无法初始化持仓',
'errors': validation_errors
}), 400
# 应用配置
# 更新主要参数
if "singleBuyAmount" in config_data:
config.POSITION_UNIT = float(config_data["singleBuyAmount"])
if "firstProfitSell" in config_data:
config.INITIAL_TAKE_PROFIT_RATIO = float(config_data["firstProfitSell"]) / 100
if "firstProfitSellEnabled" in config_data:
config.ENABLE_DYNAMIC_STOP_PROFIT = bool(config_data["firstProfitSellEnabled"])
if "stockGainSellPencent" in config_data:
config.INITIAL_TAKE_PROFIT_RATIO_PERCENTAGE = float(config_data["stockGainSellPencent"]) / 100
if "stopLossBuy" in config_data:
# 更新第二个网格级别
ratio = 1 - float(config_data["stopLossBuy"]) / 100
config.BUY_GRID_LEVELS[1] = ratio
if "stockStopLoss" in config_data:
config.STOP_LOSS_RATIO = -float(config_data["stockStopLoss"]) / 100
if "singleStockMaxPosition" in config_data:
config.MAX_POSITION_VALUE = float(config_data["singleStockMaxPosition"])
if "totalMaxPosition" in config_data:
config.MAX_TOTAL_POSITION_RATIO = float(config_data["totalMaxPosition"]) / 1000000
# 开关类参数
if "allowBuy" in config_data:
setattr(config, 'ENABLE_ALLOW_BUY', bool(config_data["allowBuy"]))
if "allowSell" in config_data:
setattr(config, 'ENABLE_ALLOW_SELL', bool(config_data["allowSell"]))
if "globalAllowBuySell" in config_data:
config.ENABLE_AUTO_TRADING = bool(config_data["globalAllowBuySell"])
if "simulationMode" in config_data:
setattr(config, 'ENABLE_SIMULATION_MODE', bool(config_data["simulationMode"]))
# 初始化持仓数据
# 这里需要实现初始化持仓的逻辑
# 可以通过查询交易接口获取实际持仓
# 假设我们直接从交易执行器获取持仓
positions = trading_executor.get_stock_positions()
# 清空已有持仓数据
# cursor = data_manager.conn.cursor()
# cursor.execute("DELETE FROM positions")
# data_manager.conn.commit()
# 导入最新持仓
for pos in positions:
# 假设position_manager有一个update_position方法
position_manager.update_position(
stock_code=pos['stock_code'],
volume=pos['volume'],
cost_price=pos['cost_price'],
current_price=pos['current_price']
)
return jsonify({
'status': 'success',
'message': '持仓数据初始化成功',
'count': len(positions)
})
except Exception as e:
logger.error(f"初始化持仓数据时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"初始化持仓数据失败: {str(e)}"
}), 500
@app.route('/api/stock_pool/list', methods=['GET'])
def get_stock_pool():
"""获取备选池股票列表"""
try:
# 读取备选池股票文件
file_path = config.STOCK2BUY_FILE
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
stock_pool = json.load(f)
else:
# 如果文件不存在,使用默认股票池
stock_pool = config.STOCK_POOL
return jsonify({
'status': 'success',
'data': stock_pool
})
except Exception as e:
logger.error(f"获取备选池股票列表时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"获取备选池股票列表失败: {str(e)}"
}), 500
@app.route('/api/actions/execute_buy', methods=['POST'])
def execute_buy():
"""执行买入操作"""
try:
buy_data = request.json
strategy = buy_data.get('strategy', 'random_pool')
quantity = int(buy_data.get('quantity', 0))
stocks = buy_data.get('stocks', [])
if quantity <= 0:
return jsonify({
'status': 'error',
'message': '买入数量必须大于0'
}), 400
if not stocks:
return jsonify({
'status': 'error',
'message': '未提供股票列表'
}), 400
# 根据当前交易模式调整股票代码格式
is_simulation = getattr(config, 'ENABLE_SIMULATION_MODE', False)
formatted_stocks = []
for stock in stocks:
# 移除已有的后缀(如果有)
if stock.endswith(('.SH', '.SZ', '.sh', '.sz')):
stock_code = stock.split('.')[0]
else:
stock_code = stock
# 根据交易模式决定是否添加后缀
if is_simulation:
# 模拟交易模式:使用Methods.add_xt_suffix添加市场后缀
formatted_stock = Methods.add_xt_suffix(stock_code)
else:
# 实盘交易模式:使用无后缀格式
formatted_stock = stock_code
formatted_stocks.append(formatted_stock)
# 使用修改后的股票列表
logger.info(f"交易模式: {'模拟' if is_simulation else '实盘'}, 股票代码格式化: {stocks} -> {formatted_stocks}")
# 根据策略选择股票
selected_stocks = []
if strategy == 'random_pool':
# 随机选择指定数量的股票
import random
if quantity <= len(formatted_stocks):
selected_stocks = random.sample(formatted_stocks, quantity)
else:
selected_stocks = formatted_stocks
elif strategy == 'custom_stock':
# 使用用户提供的股票列表
selected_stocks = formatted_stocks[:quantity] # 取指定数量
# 执行买入
success_count = 0
for stock_code in selected_stocks:
# 计算买入金额
amount = config.POSITION_UNIT
# 执行买入
order_id = trading_strategy.manual_buy(
stock_code=stock_code,
amount=amount
)
if order_id:
success_count += 1
return jsonify({
'status': 'success',
'message': f'成功发送{success_count}个买入指令',
'success_count': success_count,
'total_count': len(selected_stocks)
})
except Exception as e:
logger.error(f"执行买入操作时出错: {str(e)}")
return jsonify({
'status': 'error',
'message': f"执行买入操作失败: {str(e)}"
}), 500
@app.route('/api/holdings/update', methods=['POST'])
def update_holding_params():
"""更新持仓参数"""
try:
data = request.json
stock_code = data.get('stock_code')
profit_triggered = data.get('profit_triggered')
highest_price = data.get('highest_price')
stop_loss_price = data.get('stop_loss_price')
if not stock_code:
return jsonify({
'status': 'error',
'message': '股票代码不能为空'
}), 400
# 获取当前持仓
position = position_manager.get_position(stock_code)
if not position: