-
Notifications
You must be signed in to change notification settings - Fork 415
Expand file tree
/
Copy pathsmart_monitor_db.py
More file actions
645 lines (541 loc) · 22.5 KB
/
smart_monitor_db.py
File metadata and controls
645 lines (541 loc) · 22.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
"""
智能盯盘 - 数据库模块
记录AI决策、交易记录、监控配置等
"""
import sqlite3
import logging
from typing import Dict, List, Optional
from datetime import datetime
import json
class SmartMonitorDB:
"""智能盯盘数据库"""
def __init__(self, db_file: str = 'smart_monitor.db'):
"""
初始化数据库
Args:
db_file: 数据库文件路径
"""
self.db_file = db_file
self.logger = logging.getLogger(__name__)
self._init_database()
def _init_database(self):
"""初始化数据库表结构"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
# 1. 监控任务表
cursor.execute('''
CREATE TABLE IF NOT EXISTS monitor_tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_name TEXT NOT NULL,
stock_code TEXT NOT NULL,
stock_name TEXT,
enabled INTEGER DEFAULT 1,
check_interval INTEGER DEFAULT 300,
auto_trade INTEGER DEFAULT 0,
position_size_pct REAL DEFAULT 20,
stop_loss_pct REAL DEFAULT 5,
take_profit_pct REAL DEFAULT 10,
qmt_account_id TEXT,
notify_email TEXT,
notify_webhook TEXT,
has_position INTEGER DEFAULT 0,
position_cost REAL DEFAULT 0,
position_quantity INTEGER DEFAULT 0,
position_date TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(stock_code)
)
''')
# 添加持仓相关字段(如果表已存在但缺少这些字段)
try:
cursor.execute("ALTER TABLE monitor_tasks ADD COLUMN has_position INTEGER DEFAULT 0")
except sqlite3.OperationalError:
pass
try:
cursor.execute("ALTER TABLE monitor_tasks ADD COLUMN position_cost REAL DEFAULT 0")
except sqlite3.OperationalError:
pass
try:
cursor.execute("ALTER TABLE monitor_tasks ADD COLUMN position_quantity INTEGER DEFAULT 0")
except sqlite3.OperationalError:
pass
try:
cursor.execute("ALTER TABLE monitor_tasks ADD COLUMN position_date TEXT")
except sqlite3.OperationalError:
pass
# 添加交易时段监控字段
try:
cursor.execute("ALTER TABLE monitor_tasks ADD COLUMN trading_hours_only INTEGER DEFAULT 1")
except sqlite3.OperationalError:
pass
# 2. AI决策记录表
cursor.execute('''
CREATE TABLE IF NOT EXISTS ai_decisions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stock_code TEXT NOT NULL,
stock_name TEXT,
decision_time TEXT NOT NULL,
trading_session TEXT,
action TEXT NOT NULL,
confidence INTEGER,
reasoning TEXT,
position_size_pct REAL,
stop_loss_pct REAL,
take_profit_pct REAL,
risk_level TEXT,
key_price_levels TEXT,
market_data TEXT,
account_info TEXT,
executed INTEGER DEFAULT 0,
execution_result TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
''')
# 3. 交易记录表
cursor.execute('''
CREATE TABLE IF NOT EXISTS trade_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stock_code TEXT NOT NULL,
stock_name TEXT,
trade_type TEXT NOT NULL,
quantity INTEGER,
price REAL,
amount REAL,
order_id TEXT,
order_status TEXT,
ai_decision_id INTEGER,
trade_time TEXT NOT NULL,
commission REAL DEFAULT 0,
tax REAL DEFAULT 0,
profit_loss REAL DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(ai_decision_id) REFERENCES ai_decisions(id)
)
''')
# 4. 持仓监控表
cursor.execute('''
CREATE TABLE IF NOT EXISTS position_monitor (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stock_code TEXT NOT NULL,
stock_name TEXT,
quantity INTEGER,
cost_price REAL,
current_price REAL,
profit_loss REAL,
profit_loss_pct REAL,
holding_days INTEGER,
buy_date TEXT,
stop_loss_price REAL,
take_profit_price REAL,
last_check_time TEXT,
status TEXT DEFAULT 'holding',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(stock_code)
)
''')
# 5. 通知记录表
cursor.execute('''
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stock_code TEXT,
notify_type TEXT NOT NULL,
notify_target TEXT,
subject TEXT,
content TEXT,
status TEXT DEFAULT 'pending',
error_msg TEXT,
sent_at TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
''')
# 6. 系统日志表
cursor.execute('''
CREATE TABLE IF NOT EXISTS system_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
log_level TEXT,
module TEXT,
message TEXT,
details TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
self.logger.info(f"数据库初始化完成: {self.db_file}")
# ========== 监控任务管理 ==========
def add_monitor_task(self, task_data: Dict) -> int:
"""添加监控任务"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO monitor_tasks
(task_name, stock_code, stock_name, enabled, check_interval,
auto_trade, trading_hours_only, position_size_pct, stop_loss_pct, take_profit_pct,
qmt_account_id, notify_email, notify_webhook,
has_position, position_cost, position_quantity, position_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
task_data.get('task_name'),
task_data.get('stock_code'),
task_data.get('stock_name'),
task_data.get('enabled', 1),
task_data.get('check_interval', 300),
task_data.get('auto_trade', 0),
task_data.get('trading_hours_only', 1),
task_data.get('position_size_pct', 20),
task_data.get('stop_loss_pct', 5),
task_data.get('take_profit_pct', 10),
task_data.get('qmt_account_id'),
task_data.get('notify_email'),
task_data.get('notify_webhook'),
task_data.get('has_position', 0),
task_data.get('position_cost', 0),
task_data.get('position_quantity', 0),
task_data.get('position_date')
))
task_id = cursor.lastrowid
conn.commit()
conn.close()
position_info = f"(持仓: {task_data.get('position_quantity')}股 @ {task_data.get('position_cost')}元)" if task_data.get('has_position') else ""
self.logger.info(f"添加监控任务: {task_data.get('stock_code')} - {task_data.get('task_name')} {position_info}")
return task_id
def get_monitor_tasks(self, enabled_only: bool = True) -> List[Dict]:
"""获取监控任务列表"""
conn = sqlite3.connect(self.db_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
if enabled_only:
cursor.execute('SELECT * FROM monitor_tasks WHERE enabled = 1 ORDER BY id DESC')
else:
cursor.execute('SELECT * FROM monitor_tasks ORDER BY id DESC')
rows = cursor.fetchall()
conn.close()
return [dict(row) for row in rows]
def update_monitor_task(self, task_id: int, updates: Dict):
"""更新监控任务"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
set_clause = ', '.join([f"{k} = ?" for k in updates.keys()])
values = list(updates.values()) + [task_id]
cursor.execute(f'''
UPDATE monitor_tasks
SET {set_clause}, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
''', values)
conn.commit()
conn.close()
def update_monitor_task(self, stock_code: str, task_data: Dict):
"""更新监控任务"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
# 构建更新语句
update_fields = []
values = []
if 'task_name' in task_data:
update_fields.append('task_name = ?')
values.append(task_data['task_name'])
if 'check_interval' in task_data:
update_fields.append('check_interval = ?')
values.append(task_data['check_interval'])
if 'auto_trade' in task_data:
update_fields.append('auto_trade = ?')
values.append(task_data['auto_trade'])
if 'trading_hours_only' in task_data:
update_fields.append('trading_hours_only = ?')
values.append(task_data['trading_hours_only'])
if 'position_size_pct' in task_data:
update_fields.append('position_size_pct = ?')
values.append(task_data['position_size_pct'])
if 'has_position' in task_data:
update_fields.append('has_position = ?')
values.append(task_data['has_position'])
if 'position_cost' in task_data:
update_fields.append('position_cost = ?')
values.append(task_data['position_cost'])
if 'position_quantity' in task_data:
update_fields.append('position_quantity = ?')
values.append(task_data['position_quantity'])
if 'position_date' in task_data:
update_fields.append('position_date = ?')
values.append(task_data['position_date'])
if 'notify_email' in task_data:
update_fields.append('notify_email = ?')
values.append(task_data['notify_email'])
# 添加更新时间
update_fields.append('updated_at = CURRENT_TIMESTAMP')
# 添加WHERE条件
values.append(stock_code)
sql = f"UPDATE monitor_tasks SET {', '.join(update_fields)} WHERE stock_code = ?"
cursor.execute(sql, values)
conn.commit()
conn.close()
self.logger.info(f"更新监控任务: {stock_code}")
def delete_monitor_task(self, task_id: int):
"""删除监控任务"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('DELETE FROM monitor_tasks WHERE id = ?', (task_id,))
conn.commit()
conn.close()
# ========== AI决策记录 ==========
def save_ai_decision(self, decision_data: Dict) -> int:
"""保存AI决策"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO ai_decisions
(stock_code, stock_name, decision_time, trading_session,
action, confidence, reasoning, position_size_pct,
stop_loss_pct, take_profit_pct, risk_level,
key_price_levels, market_data, account_info)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
decision_data.get('stock_code'),
decision_data.get('stock_name'),
decision_data.get('decision_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
decision_data.get('trading_session'),
decision_data.get('action'),
decision_data.get('confidence'),
decision_data.get('reasoning'),
decision_data.get('position_size_pct'),
decision_data.get('stop_loss_pct'),
decision_data.get('take_profit_pct'),
decision_data.get('risk_level'),
json.dumps(decision_data.get('key_price_levels', {})),
json.dumps(decision_data.get('market_data', {})),
json.dumps(decision_data.get('account_info', {}))
))
decision_id = cursor.lastrowid
conn.commit()
conn.close()
return decision_id
def get_ai_decisions(self, stock_code: str = None, limit: int = 100) -> List[Dict]:
"""获取AI决策历史"""
conn = sqlite3.connect(self.db_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
if stock_code:
cursor.execute('''
SELECT * FROM ai_decisions
WHERE stock_code = ?
ORDER BY decision_time DESC
LIMIT ?
''', (stock_code, limit))
else:
cursor.execute('''
SELECT * FROM ai_decisions
ORDER BY decision_time DESC
LIMIT ?
''', (limit,))
rows = cursor.fetchall()
conn.close()
decisions = []
for row in rows:
d = dict(row)
# 解析JSON字段
d['key_price_levels'] = json.loads(d['key_price_levels']) if d['key_price_levels'] else {}
d['market_data'] = json.loads(d['market_data']) if d['market_data'] else {}
d['account_info'] = json.loads(d['account_info']) if d['account_info'] else {}
decisions.append(d)
return decisions
def update_decision_execution(self, decision_id: int, executed: bool, result: str):
"""更新决策执行状态"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
UPDATE ai_decisions
SET executed = ?, execution_result = ?
WHERE id = ?
''', (1 if executed else 0, result, decision_id))
conn.commit()
conn.close()
# ========== 交易记录 ==========
def save_trade_record(self, trade_data: Dict) -> int:
"""保存交易记录"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO trade_records
(stock_code, stock_name, trade_type, quantity, price, amount,
order_id, order_status, ai_decision_id, trade_time,
commission, tax, profit_loss)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
trade_data.get('stock_code'),
trade_data.get('stock_name'),
trade_data.get('trade_type'),
trade_data.get('quantity'),
trade_data.get('price'),
trade_data.get('amount'),
trade_data.get('order_id'),
trade_data.get('order_status'),
trade_data.get('ai_decision_id'),
trade_data.get('trade_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
trade_data.get('commission', 0),
trade_data.get('tax', 0),
trade_data.get('profit_loss', 0)
))
record_id = cursor.lastrowid
conn.commit()
conn.close()
return record_id
def get_trade_records(self, stock_code: str = None, limit: int = 100) -> List[Dict]:
"""获取交易记录"""
conn = sqlite3.connect(self.db_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
if stock_code:
cursor.execute('''
SELECT * FROM trade_records
WHERE stock_code = ?
ORDER BY trade_time DESC
LIMIT ?
''', (stock_code, limit))
else:
cursor.execute('''
SELECT * FROM trade_records
ORDER BY trade_time DESC
LIMIT ?
''', (limit,))
rows = cursor.fetchall()
conn.close()
return [dict(row) for row in rows]
# ========== 持仓监控 ==========
def save_position(self, position_data: Dict):
"""保存/更新持仓信息"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
# 检查是否已存在
cursor.execute('SELECT id FROM position_monitor WHERE stock_code = ?',
(position_data.get('stock_code'),))
existing = cursor.fetchone()
if existing:
# 更新
cursor.execute('''
UPDATE position_monitor
SET stock_name = ?, quantity = ?, cost_price = ?,
current_price = ?, profit_loss = ?, profit_loss_pct = ?,
holding_days = ?, stop_loss_price = ?, take_profit_price = ?,
last_check_time = ?, updated_at = CURRENT_TIMESTAMP
WHERE stock_code = ?
''', (
position_data.get('stock_name'),
position_data.get('quantity'),
position_data.get('cost_price'),
position_data.get('current_price'),
position_data.get('profit_loss'),
position_data.get('profit_loss_pct'),
position_data.get('holding_days'),
position_data.get('stop_loss_price'),
position_data.get('take_profit_price'),
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
position_data.get('stock_code')
))
else:
# 插入
cursor.execute('''
INSERT INTO position_monitor
(stock_code, stock_name, quantity, cost_price, current_price,
profit_loss, profit_loss_pct, holding_days, buy_date,
stop_loss_price, take_profit_price, last_check_time, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
position_data.get('stock_code'),
position_data.get('stock_name'),
position_data.get('quantity'),
position_data.get('cost_price'),
position_data.get('current_price'),
position_data.get('profit_loss'),
position_data.get('profit_loss_pct'),
position_data.get('holding_days'),
position_data.get('buy_date'),
position_data.get('stop_loss_price'),
position_data.get('take_profit_price'),
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'holding'
))
conn.commit()
conn.close()
def get_positions(self) -> List[Dict]:
"""获取所有持仓"""
conn = sqlite3.connect(self.db_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM position_monitor WHERE status = "holding" ORDER BY id DESC')
rows = cursor.fetchall()
conn.close()
return [dict(row) for row in rows]
def close_position(self, stock_code: str):
"""关闭持仓记录"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
UPDATE position_monitor
SET status = 'closed', updated_at = CURRENT_TIMESTAMP
WHERE stock_code = ?
''', (stock_code,))
conn.commit()
conn.close()
# ========== 通知记录 ==========
def save_notification(self, notify_data: Dict) -> int:
"""保存通知记录"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO notifications
(stock_code, notify_type, notify_target, subject, content, status)
VALUES (?, ?, ?, ?, ?, ?)
''', (
notify_data.get('stock_code'),
notify_data.get('notify_type'),
notify_data.get('notify_target'),
notify_data.get('subject'),
notify_data.get('content'),
notify_data.get('status', 'pending')
))
notify_id = cursor.lastrowid
conn.commit()
conn.close()
return notify_id
def update_notification_status(self, notify_id: int, status: str, error_msg: str = None):
"""更新通知状态"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
UPDATE notifications
SET status = ?, error_msg = ?, sent_at = CURRENT_TIMESTAMP
WHERE id = ?
''', (status, error_msg, notify_id))
conn.commit()
conn.close()
# ========== 系统日志 ==========
def log_system_event(self, level: str, module: str, message: str, details: str = None):
"""记录系统日志"""
conn = sqlite3.connect(self.db_file)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO system_logs (log_level, module, message, details)
VALUES (?, ?, ?, ?)
''', (level, module, message, details))
conn.commit()
conn.close()
if __name__ == '__main__':
# 测试数据库
logging.basicConfig(level=logging.INFO)
db = SmartMonitorDB('test_smart_monitor.db')
# 测试添加监控任务
task_id = db.add_monitor_task({
'task_name': '茅台盯盘',
'stock_code': '600519',
'stock_name': '贵州茅台',
'auto_trade': 1,
'notify_email': 'test@example.com'
})
print(f"创建监控任务 ID: {task_id}")
# 获取任务列表
tasks = db.get_monitor_tasks()
print(f"\n监控任务列表: {len(tasks)}个")
for task in tasks:
print(f" - {task['stock_code']} {task['stock_name']}")