-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
1082 lines (871 loc) · 34.2 KB
/
Copy pathapp.py
File metadata and controls
1082 lines (871 loc) · 34.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
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
"""
Futu AI Trading System - Flask后端API
配合 CoreUI 前端使用
"""
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import os
from pathlib import Path
import sqlite3
import json
from datetime import datetime
import pandas as pd
import logging
from config.settings import Settings
from data.futu_client import FutuClient
from data.news_collector import NewsCollector
from core.account_tracker import AccountTracker
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = Flask(__name__, static_folder='static', static_url_path='')
CORS(app)
# 初始化账户追踪器
account_tracker = AccountTracker()
# ==================== 工具函数 ====================
def read_env():
"""读取.env文件"""
env_path = Path('.env')
if not env_path.exists():
return {}
env_vars = {}
with open(env_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
env_vars[key.strip()] = value.strip()
return env_vars
def write_env(env_vars):
"""写入.env文件"""
with open('.env', 'w', encoding='utf-8') as f:
for key, value in env_vars.items():
f.write(f"{key}={value}\n")
def get_portfolio_data():
"""获取投资组合数据 - 使用FutuClient获取真实/模拟账户数据"""
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
def fetch_data():
client = FutuClient(Settings)
# 获取账户信息
account_info = client.get_account_info()
if not account_info:
client.close()
raise Exception("Failed to get account info from FutuClient")
# 转换为DataFrame格式 (兼容旧的API接口)
account_df = pd.DataFrame([{
'id': 1,
'cash': account_info.get('cash', 0),
'total_assets': account_info.get('total_assets', 0),
'updated_at': datetime.now().isoformat()
}])
# 获取持仓信息
portfolio = client.get_portfolio_status()
positions_list = []
for stock_code, pos in portfolio.items():
positions_list.append({
'stock_code': stock_code,
'quantity': pos.get('quantity', 0),
'avg_price': pos.get('avg_price', 0),
'current_price': pos.get('current_price', 0),
'market_value': pos.get('market_value', 0),
'cost_value': pos.get('cost_value', 0),
'pnl': pos.get('pnl', 0),
'pnl_ratio': pos.get('pnl_ratio', 0),
'updated_at': datetime.now().isoformat()
})
positions_df = pd.DataFrame(positions_list) if positions_list else pd.DataFrame()
client.close()
return positions_df, account_df
try:
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(fetch_data)
return future.result(timeout=5) # 5秒超时
except (FutureTimeoutError, TimeoutError) as e:
print(f"Portfolio data fetch timeout: {e}")
import traceback
traceback.print_exc()
raise TimeoutError("FutuClient request timeout")
except Exception as e:
print(f"Error getting portfolio data: {e}")
import traceback
traceback.print_exc()
raise
def get_recent_news(limit=20):
"""获取最近新闻"""
try:
db_path = Path('news.db')
if not db_path.exists():
return []
conn = sqlite3.connect(db_path)
query = f"""
SELECT title, published, source, link
FROM news
ORDER BY published DESC
LIMIT {limit}
"""
cursor = conn.cursor()
cursor.execute(query)
news = []
for row in cursor.fetchall():
news.append({
'title': row[0],
'published': row[1],
'source': row[2],
'link': row[3]
})
conn.close()
return news
except Exception as e:
print(f"Error getting news: {e}")
return []
def read_log_file(log_name, lines=50):
"""读取日志文件"""
try:
log_path = Path(f'logs/{log_name}.log')
if not log_path.exists():
return []
with open(log_path, 'r', encoding='utf-8') as f:
all_lines = f.readlines()
recent_lines = all_lines[-lines:]
return [line.strip() for line in recent_lines]
except Exception as e:
return [f"读取日志失败: {e}"]
# ==================== 前端静态文件 ====================
@app.route('/')
def index():
"""主页 - Alpha Arena"""
return send_from_directory('static', 'alpha_arena.html')
@app.route('/dashboard')
def dashboard():
"""管理控制台"""
return send_from_directory('static', 'dashboard.html')
@app.route('/coreui')
def coreui():
"""传统 CoreUI 界面(保留)"""
return send_from_directory('static', 'index.html')
@app.route('/<path:path>')
def static_files(path):
"""静态文件"""
return send_from_directory('static', path)
# ==================== API路由 ====================
@app.route('/api/system/status')
def system_status():
"""获取系统状态"""
import subprocess
status = {
'main_system_running': False,
'ollama_online': False,
'futu_connected': False,
'last_analysis': 'N/A',
'timestamp': datetime.now().isoformat()
}
# 检查主程序 (main.py)
try:
result = subprocess.run(['pgrep', '-f', 'python main.py'],
capture_output=True, text=True)
if result.stdout.strip():
status['main_system_running'] = True
except:
pass
# 检查Ollama
try:
import requests
from config.settings import Settings
response = requests.get(f'{Settings.OLLAMA_HOST}/api/tags', timeout=2)
if response.status_code == 200:
status['ollama_online'] = True
except:
pass
# 检查Futu OpenD
try:
from data.futu_client import FutuClient
from config.settings import Settings
client = FutuClient(
host=Settings.FUTU_IP,
port=Settings.FUTU_PORT,
trading_mode=Settings.TRADING_MODE
)
account = client.get_account_info()
if account:
status['futu_connected'] = True
except:
pass
# 获取最后分析时间
try:
log_path = Path('logs/ai_analyzer.log')
if log_path.exists():
with open(log_path, 'r') as f:
lines = f.readlines()
if lines:
last_line = lines[-1]
if len(last_line) > 20:
status['last_analysis'] = last_line[:19]
except:
pass
return jsonify(status)
@app.route('/api/config')
def get_config():
"""获取配置"""
env_vars = read_env()
config = {
# 基础配置
'trading_mode': env_vars.get('TRADING_MODE', 'SIMULATION'),
# AI模式配置
'ai_mode': env_vars.get('AI_MODE', 'local'),
# 本地模型配置
'model_preset': env_vars.get('MODEL_PRESET', 'balanced'),
'ollama_model': env_vars.get('OLLAMA_MODEL', ''),
'ollama_host': env_vars.get('OLLAMA_HOST', 'http://localhost:11434'),
# API模式配置
'api_provider': env_vars.get('API_PROVIDER', 'openai'),
'api_key': env_vars.get('API_KEY', ''), # 前端会脱敏显示
'api_model': env_vars.get('API_MODEL', ''),
'api_base_url': env_vars.get('API_BASE_URL', ''),
# Futu连接配置
'futu_ip': env_vars.get('FUTU_IP', '127.0.0.1'),
'futu_port': int(env_vars.get('FUTU_PORT', 11111)),
# futu_trade_pwd 不返回到前端
# 交易参数
'max_position_size': float(env_vars.get('MAX_POSITION_SIZE', 0.15)),
'initial_position': float(env_vars.get('INITIAL_POSITION', 0.10)),
'stop_loss': float(env_vars.get('STOP_LOSS', 0.20)),
# AI分析阈值
'min_financial_score': float(env_vars.get('MIN_FINANCIAL_SCORE', 5.0)),
'min_sentiment_score': float(env_vars.get('MIN_SENTIMENT_SCORE', 2.0)),
'max_risk_score': float(env_vars.get('MAX_RISK_SCORE', 6.0)),
# 邮件通知配置
'notification_email': env_vars.get('NOTIFICATION_EMAIL', ''),
'smtp_user': env_vars.get('SMTP_USER', ''),
'smtp_server': env_vars.get('SMTP_SERVER', 'smtp.gmail.com'),
'smtp_port': int(env_vars.get('SMTP_PORT', 587)),
# smtp_password 不返回到前端
# 监控股票列表
'watchlist': [s.strip() for s in env_vars.get('WATCHLIST', '').split(',') if s.strip()],
# 模型配置(供参考)
'model_configs': Settings.MODEL_CONFIGS,
'api_provider_configs': Settings.API_PROVIDER_CONFIGS
}
return jsonify(config)
@app.route('/api/config', methods=['POST'])
def update_config():
"""更新配置"""
try:
data = request.json
env_vars = read_env()
# 基础配置
env_vars['TRADING_MODE'] = data.get('trading_mode', 'SIMULATION')
# AI模式配置
env_vars['AI_MODE'] = data.get('ai_mode', 'local')
# 本地模型配置
env_vars['MODEL_PRESET'] = data.get('model_preset', 'balanced')
env_vars['OLLAMA_HOST'] = data.get('ollama_host', 'http://localhost:11434')
# 根据模型预设自动设置模型(本地模式)
if data.get('ai_mode', 'local') == 'local':
model_preset = data.get('model_preset', 'balanced')
if model_preset in Settings.MODEL_CONFIGS:
env_vars['OLLAMA_MODEL'] = Settings.MODEL_CONFIGS[model_preset]['model']
# API模式配置
env_vars['API_PROVIDER'] = data.get('api_provider', 'openai')
if 'api_key' in data and data['api_key']:
env_vars['API_KEY'] = data['api_key']
env_vars['API_MODEL'] = data.get('api_model', '')
env_vars['API_BASE_URL'] = data.get('api_base_url', '')
# Futu连接配置
env_vars['FUTU_IP'] = data.get('futu_ip', '127.0.0.1')
env_vars['FUTU_PORT'] = str(data.get('futu_port', 11111))
if 'futu_trade_pwd' in data and data['futu_trade_pwd']:
env_vars['FUTU_TRADE_PWD'] = data['futu_trade_pwd']
# 交易参数
env_vars['MAX_POSITION_SIZE'] = str(data.get('max_position_size', 0.15))
env_vars['INITIAL_POSITION'] = str(data.get('initial_position', 0.10))
env_vars['STOP_LOSS'] = str(data.get('stop_loss', 0.20))
# AI分析阈值
env_vars['MIN_FINANCIAL_SCORE'] = str(data.get('min_financial_score', 5.0))
env_vars['MIN_SENTIMENT_SCORE'] = str(data.get('min_sentiment_score', 2.0))
env_vars['MAX_RISK_SCORE'] = str(data.get('max_risk_score', 6.0))
# 邮件通知配置
env_vars['NOTIFICATION_EMAIL'] = data.get('notification_email', '')
env_vars['SMTP_USER'] = data.get('smtp_user', '')
env_vars['SMTP_SERVER'] = data.get('smtp_server', 'smtp.gmail.com')
env_vars['SMTP_PORT'] = str(data.get('smtp_port', 587))
if 'smtp_password' in data and data['smtp_password']:
env_vars['SMTP_PASSWORD'] = data['smtp_password']
# 监控股票列表
env_vars['WATCHLIST'] = ','.join(data.get('watchlist', []))
write_env(env_vars)
return jsonify({'success': True, 'message': '配置已保存,重启系统后生效'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 400
@app.route('/api/portfolio/overview')
def portfolio_overview():
"""获取投资组合概览"""
try:
positions_df, account_df = get_portfolio_data()
if account_df is None or account_df.empty:
return jsonify({
'success': False,
'error': 'No account data available'
}), 500
account = account_df.iloc[0].to_dict()
positions = []
total_pnl = 0
if positions_df is not None and not positions_df.empty:
positions = positions_df.to_dict('records')
total_pnl = positions_df['pnl'].sum()
total_assets = account['total_assets']
cash = account['cash']
market_value = total_assets - cash
# 记录账户快照(用于历史曲线)
try:
account_tracker.record_snapshot(
account_info={'total_assets': total_assets, 'cash': cash},
portfolio={pos['stock_code']: pos for pos in positions}
)
except Exception as e:
logger.warning(f"Failed to record account snapshot: {e}")
return jsonify({
'success': True,
'account': account,
'positions': positions,
'summary': {
'total_assets': total_assets,
'cash': cash,
'market_value': market_value,
'total_pnl': total_pnl,
'position_ratio': (market_value / total_assets * 100) if total_assets > 0 else 0
}
})
except TimeoutError as e:
logger.error(f"Portfolio overview timeout: {e}")
return jsonify({
'success': False,
'error': 'Request timeout - Futu API not responding'
}), 504
except Exception as e:
logger.error(f"Portfolio overview error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/portfolio/history')
def portfolio_history():
"""获取账户价值历史数据(用于图表)"""
try:
period = request.args.get('period', '24H') # 24H, 72H, 7D, 30D, ALL
# 获取聚合后的历史数据
history = account_tracker.get_aggregated_history(period)
return jsonify({
'success': True,
'period': period,
'data': history,
'count': len(history)
})
except Exception as e:
logger.error(f"Portfolio history error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/news')
def get_news():
"""获取新闻"""
limit = request.args.get('limit', 20, type=int)
news = get_recent_news(limit)
return jsonify(news)
@app.route('/api/news/refresh', methods=['POST'])
def refresh_news():
"""刷新新闻"""
try:
news_collector = NewsCollector()
count = news_collector.fetch_latest_news(hours_back=24)
return jsonify({'success': True, 'count': count})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/logs/<log_name>')
def get_logs(log_name):
"""获取日志"""
lines = request.args.get('lines', 50, type=int)
log_content = read_log_file(log_name, lines)
return jsonify(log_content)
@app.route('/api/quotes/watchlist')
def get_watchlist_quotes():
"""获取监控列表实时行情"""
try:
# 从.env文件读取最新的watchlist(确保同步Dashboard的修改)
env_vars = read_env()
watchlist_str = env_vars.get('WATCHLIST', '00700,09988,01299,03690')
watchlist = [s.strip() for s in watchlist_str.split(',') if s.strip()]
# 获取实时行情(带超时保护)
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
def fetch_quotes():
client = FutuClient(Settings)
quotes = client.get_stock_quotes(watchlist)
client.close()
return quotes
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(fetch_quotes)
quotes = future.result(timeout=5) # 5秒超时
return jsonify({
'success': True,
'quotes': quotes
})
except (FutureTimeoutError, TimeoutError) as e:
logger.error(f"Watchlist API timeout: {e}")
return jsonify({
'success': False,
'error': 'Request timeout - Futu API not responding'
}), 504
except Exception as e:
logger.error(f"Watchlist API error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/analysis/stock/<stock_code>', methods=['POST'])
def analyze_stock(stock_code):
"""分析股票"""
# TODO: 实现股票分析
return jsonify({
'success': False,
'message': '功能开发中'
})
@app.route('/api/data/clean-news', methods=['POST'])
def clean_news():
"""清理旧新闻"""
try:
news_collector = NewsCollector()
deleted = news_collector.clean_old_news(days_to_keep=30)
return jsonify({'success': True, 'deleted': deleted})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/charts/positions')
def positions_chart():
"""获取持仓图表数据"""
positions_df, _ = get_portfolio_data()
if positions_df is None or positions_df.empty:
return jsonify({
'labels': [],
'values': []
})
return jsonify({
'labels': positions_df['stock_code'].tolist(),
'values': positions_df['market_value'].tolist()
})
@app.route('/api/orders')
def get_orders():
"""获取订单列表"""
try:
client = FutuClient(Settings)
orders = client.get_order_list()
client.close()
return jsonify({
'success': True,
'orders': orders
})
except Exception as e:
print(f"Error getting orders: {e}")
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e),
'orders': []
}), 500
@app.route('/api/orders/place', methods=['POST'])
def place_order():
"""下单接口 - 用于测试"""
try:
data = request.json
stock_code = data.get('stock_code')
quantity = data.get('quantity')
price = data.get('price', 0)
action = data.get('action', 'BUY') # BUY or SELL
order_type = data.get('order_type', 'MARKET') # MARKET or LIMIT
if not stock_code or not quantity:
return jsonify({
'success': False,
'error': 'stock_code and quantity are required'
}), 400
# 使用FutuClient下单
client = FutuClient(Settings)
success, message, fee_info = client.place_order(
stock_code=stock_code,
quantity=int(quantity),
price=float(price) if price else 0,
action=action.upper(),
order_type=order_type.upper(),
calculate_fees=True
)
client.close()
if success:
# 记录到日志
logger.info(f"Order placed: {action} {quantity} {stock_code} @ {price}, fees: {fee_info}")
return jsonify({
'success': True,
'message': message,
'fee_info': fee_info
})
else:
return jsonify({
'success': False,
'error': message
}), 400
except Exception as e:
logger.error(f"Error placing order: {e}")
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e)
}), 500
# ==================== 系统控制API ====================
@app.route('/api/system/start', methods=['POST'])
def start_main_system():
"""启动主交易系统"""
try:
import subprocess
import os
# 检查是否已经在运行
result = subprocess.run(['pgrep', '-f', 'python main.py'],
capture_output=True, text=True)
if result.stdout.strip():
return jsonify({'success': False, 'error': '主系统已在运行'})
# 启动主系统(后台运行)
project_dir = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(project_dir, 'logs', 'main.log')
subprocess.Popen(
['nohup', 'python', 'main.py'],
cwd=project_dir,
stdout=open(log_file, 'a'),
stderr=subprocess.STDOUT,
start_new_session=True
)
return jsonify({'success': True, 'message': '主系统启动中...'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/system/stop', methods=['POST'])
def stop_main_system():
"""停止主交易系统"""
try:
import subprocess
# 查找main.py进程
result = subprocess.run(['pgrep', '-f', 'python main.py'],
capture_output=True, text=True)
if not result.stdout.strip():
return jsonify({'success': False, 'error': '主系统未运行'})
# 停止进程
subprocess.run(['pkill', '-f', 'python main.py'])
return jsonify({'success': True, 'message': '主系统已停止'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/system/restart-flask', methods=['POST'])
def restart_flask():
"""重启Flask服务器"""
try:
import subprocess
import os
import signal
# 获取当前进程ID
pid = os.getpid()
# 启动新的Flask进程
project_dir = os.path.dirname(os.path.abspath(__file__))
subprocess.Popen(
['python', 'app.py'],
cwd=project_dir,
start_new_session=True
)
# 发送信号停止当前进程
def shutdown():
os.kill(pid, signal.SIGTERM)
# 3秒后关闭当前进程
import threading
t = threading.Timer(3.0, shutdown)
t.start()
return jsonify({'success': True, 'message': '服务器将在3秒后重启'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/system/test-ollama')
def test_ollama():
"""测试Ollama连接"""
try:
import requests
from config.settings import Settings
# 直接测试Ollama连接
response = requests.get(f"{Settings.OLLAMA_HOST}/api/tags", timeout=3)
if response.status_code == 200:
models = [m['name'] for m in response.json().get('models', [])]
return jsonify({
'success': True,
'models': models,
'host': Settings.OLLAMA_HOST
})
else:
return jsonify({'success': False, 'error': 'Ollama服务未响应'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/system/test-futu')
def test_futu():
"""测试Futu OpenD连接"""
try:
from data.futu_client import FutuClient
from config.settings import Settings
client = FutuClient()
# 获取账户信息
account = client.get_account_info()
if account:
return jsonify({
'success': True,
'account_info': f"{account.get('account_type', 'N/A')} - {account.get('account_id', 'N/A')}"
})
else:
return jsonify({'success': False, 'error': '无法获取账户信息'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/system/test-api')
def test_api():
"""测试API连接"""
try:
from core.api_adapters import APIAdapterFactory
from config.settings import Settings
# 从环境变量或请求参数获取配置
env_vars = read_env()
provider = env_vars.get('API_PROVIDER', 'openai')
api_key = env_vars.get('API_KEY', '')
api_model = env_vars.get('API_MODEL', '')
api_base_url = env_vars.get('API_BASE_URL', '')
if not api_key:
return jsonify({'success': False, 'error': 'API_KEY未配置'})
# 获取提供商配置
provider_config = Settings.API_PROVIDER_CONFIGS.get(provider, {})
if not api_model:
api_model = provider_config.get('default_model', 'gpt-4')
if not api_base_url:
api_base_url = provider_config.get('default_base_url', '')
# 创建适配器并测试
adapter = APIAdapterFactory.create_adapter(
provider=provider,
api_key=api_key,
base_url=api_base_url,
model=api_model
)
if adapter.test_connection():
return jsonify({
'success': True,
'provider': provider_config.get('name', provider),
'model': api_model,
'message': 'API连接测试成功'
})
else:
return jsonify({'success': False, 'error': 'API连接测试失败'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/system/refresh-news', methods=['POST'])
def manual_refresh_news():
"""手动刷新新闻"""
try:
from data.news_collector import NewsCollector
collector = NewsCollector()
new_count = collector.fetch_latest_news(hours_back=1)
return jsonify({
'success': True,
'new_count': new_count,
'message': f'成功抓取{new_count}条新闻'
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
# ==================== 富途API数据浏览器端点 ====================
@app.route('/futu_data_explorer')
def futu_data_explorer():
"""富途API数据浏览器页面"""
return send_from_directory('static', 'futu_data_explorer.html')
@app.route('/api/futu/market_snapshot', methods=['GET'])
def get_market_snapshot():
"""获取市场快照"""
try:
client = FutuClient(Settings)
stock_codes = request.args.get('codes', '00700,09988,01299').split(',')
data = {}
for code in stock_codes:
quotes = client.get_stock_quotes([code])
if quotes and code in quotes:
data[code] = quotes[code]
client.close()
return jsonify({'success': True, 'data': data})
except Exception as e:
logger.error(f"获取市场快照失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/kline', methods=['GET'])
def get_kline():
"""获取K线数据"""
try:
from datetime import datetime, timedelta
client = FutuClient(Settings)
stock_code = request.args.get('code', '00700')
ktype = request.args.get('ktype', 'K_DAY')
# 自动计算日期范围(最近3个月)
end_date = datetime.now().strftime('%Y-%m-%d')
start_date = (datetime.now() - timedelta(days=90)).strftime('%Y-%m-%d')
kline_data = client.get_history_kline(
stock_code=stock_code,
start=start_date,
end=end_date,
ktype=ktype,
max_count=100
)
client.close()
return jsonify({'success': True, 'data': kline_data})
except Exception as e:
logger.error(f"获取K线数据失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/order_book', methods=['GET'])
def get_order_book():
"""获取买卖盘口数据"""
try:
client = FutuClient(Settings)
stock_codes = request.args.get('codes', '00700,09988').split(',')
# get_order_book接受List[str]
order_book_data = client.get_order_book(stock_codes)
client.close()
return jsonify({'success': True, 'data': order_book_data or {}})
except Exception as e:
logger.error(f"获取盘口数据失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/financial', methods=['GET'])
def get_financial():
"""获取财务数据"""
try:
client = FutuClient(Settings)
stock_codes = request.args.get('codes', '00700,09988').split(',')
data = {}
for code in stock_codes:
financial = client.get_financial_reports(code)
if financial:
data[code] = financial
client.close()
return jsonify({'success': True, 'data': data})
except Exception as e:
logger.error(f"获取财务数据失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/basic_info', methods=['GET'])
def get_basic_info():
"""获取股票基本信息"""
try:
client = FutuClient(Settings)
stock_codes = request.args.get('codes', '00700,09988').split(',')
# get_stock_basicinfo接受List[str]
basic_info_data = client.get_stock_basicinfo(stock_codes)
client.close()
return jsonify({'success': True, 'data': basic_info_data or {}})
except Exception as e:
logger.error(f"获取基本信息失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/account_info', methods=['GET'])
def get_account_info_api():
"""获取账户信息"""
try:
client = FutuClient(Settings)
account_info = client.get_account_info()
client.close()
return jsonify({'success': True, 'data': account_info})
except Exception as e:
logger.error(f"获取账户信息失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/positions', methods=['GET'])
def get_positions_api():
"""获取持仓信息"""
try:
client = FutuClient(Settings)
positions = client.get_portfolio_status()
client.close()
return jsonify({'success': True, 'data': positions})
except Exception as e:
logger.error(f"获取持仓信息失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/orders', methods=['GET'])
def get_orders_api():
"""获取订单列表"""
try:
client = FutuClient(Settings)
# 这里需要添加订单查询功能,目前返回空列表
# TODO: 实现订单查询功能
orders = []
client.close()
return jsonify({'success': True, 'data': orders})
except Exception as e:
logger.error(f"获取订单列表失败: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/futu/deals', methods=['GET'])
def get_deals_api():
"""获取成交记录"""
try:
client = FutuClient(Settings)
# 这里需要添加成交记录查询功能,目前返回空列表
# TODO: 实现成交记录查询功能
deals = []