Skip to content

Commit 528be54

Browse files
committed
new
Signed-off-by: TIANHE <TIANHE@GMAIL.COM>
1 parent 32a426d commit 528be54

File tree

3 files changed

+57
-26
lines changed

3 files changed

+57
-26
lines changed

backend_api_python/app/routes/strategy.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -816,9 +816,6 @@ def get_strategy_notifications():
816816
user_strategy_ids = [r.get('id') for r in rows if r.get('id')]
817817
cur.close()
818818

819-
if not user_strategy_ids:
820-
return jsonify({'code': 1, 'msg': 'success', 'data': {'items': []}})
821-
822819
where = []
823820
args = []
824821

@@ -830,9 +827,15 @@ def get_strategy_notifications():
830827
else:
831828
return jsonify({'code': 1, 'msg': 'success', 'data': {'items': []}})
832829
else:
833-
placeholders = ",".join(["?"] * len(user_strategy_ids))
834-
where.append(f"strategy_id IN ({placeholders})")
835-
args.extend(user_strategy_ids)
830+
if user_strategy_ids:
831+
placeholders = ",".join(["?"] * len(user_strategy_ids))
832+
where.append(f"(strategy_id IN ({placeholders}) OR (strategy_id IS NULL AND user_id = ?))")
833+
args.extend(user_strategy_ids)
834+
args.append(user_id)
835+
else:
836+
# Only portfolio monitor notifications (strategy_id is NULL)
837+
where.append("strategy_id IS NULL AND user_id = ?")
838+
args.append(user_id)
836839

837840
if since_id:
838841
where.append("id > ?")
@@ -889,15 +892,18 @@ def mark_notification_read():
889892
if not notification_id:
890893
return jsonify({'code': 0, 'msg': 'Missing id'}), 400
891894

892-
# Only update notifications for user's strategies
895+
# Update notifications for user's strategies OR portfolio monitor notifications
893896
with get_db_connection() as db:
894897
cur = db.cursor()
895898
cur.execute(
896899
"""
897900
UPDATE qd_strategy_notifications SET is_read = 1
898-
WHERE id = ? AND strategy_id IN (SELECT id FROM qd_strategies_trading WHERE user_id = ?)
901+
WHERE id = ? AND (
902+
strategy_id IN (SELECT id FROM qd_strategies_trading WHERE user_id = ?)
903+
OR (strategy_id IS NULL AND user_id = ?)
904+
)
899905
""",
900-
(int(notification_id), user_id)
906+
(int(notification_id), user_id, user_id)
901907
)
902908
db.commit()
903909
cur.close()
@@ -920,8 +926,9 @@ def mark_all_notifications_read():
920926
"""
921927
UPDATE qd_strategy_notifications SET is_read = 1
922928
WHERE strategy_id IN (SELECT id FROM qd_strategies_trading WHERE user_id = ?)
929+
OR (strategy_id IS NULL AND user_id = ?)
923930
""",
924-
(user_id,)
931+
(user_id, user_id)
925932
)
926933
db.commit()
927934
cur.close()
@@ -944,8 +951,9 @@ def clear_notifications():
944951
"""
945952
DELETE FROM qd_strategy_notifications
946953
WHERE strategy_id IN (SELECT id FROM qd_strategies_trading WHERE user_id = ?)
954+
OR (strategy_id IS NULL AND user_id = ?)
947955
""",
948-
(user_id,)
956+
(user_id, user_id)
949957
)
950958
db.commit()
951959
cur.close()

backend_api_python/app/services/portfolio_monitor.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -768,8 +768,9 @@ def _send_monitor_notification(
768768
cur.close()
769769
elif ch == 'telegram':
770770
chat_id = targets.get('telegram', '')
771+
token_override = targets.get('telegram_bot_token', '')
771772
if chat_id:
772-
notifier._notify_telegram(chat_id=chat_id, text=f"<b>{error_title}</b>\n\n{error_msg}", parse_mode="HTML")
773+
notifier._notify_telegram(chat_id=chat_id, text=f"<b>{error_title}</b>\n\n{error_msg}", token_override=token_override, parse_mode="HTML")
773774
elif ch == 'email':
774775
to_email = targets.get('email', '')
775776
if to_email:
@@ -815,11 +816,13 @@ def _send_monitor_notification(
815816

816817
elif ch == 'telegram':
817818
chat_id = targets.get('telegram', '')
819+
token_override = targets.get('telegram_bot_token', '')
818820
if chat_id:
819821
# Use Telegram-optimized format
820822
notifier._notify_telegram(
821823
chat_id=chat_id,
822824
text=telegram_report,
825+
token_override=token_override,
823826
parse_mode="HTML"
824827
)
825828

@@ -1099,8 +1102,9 @@ def _check_position_alerts():
10991102
cur.close()
11001103
elif ch == 'telegram':
11011104
chat_id = targets.get('telegram', '')
1105+
token_override = targets.get('telegram_bot_token', '')
11021106
if chat_id:
1103-
notifier._notify_telegram(chat_id=chat_id, text=alert_message, parse_mode="HTML")
1107+
notifier._notify_telegram(chat_id=chat_id, text=alert_message, token_override=token_override, parse_mode="HTML")
11041108
elif ch == 'email':
11051109
to_email = targets.get('email', '')
11061110
if to_email:

backend_api_python/app/services/trading_executor.py

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,29 +52,48 @@ def __init__(self):
5252
self._ensure_db_columns()
5353

5454
def _ensure_db_columns(self):
55-
"""确保必要的数据库字段存在"""
55+
"""确保必要的数据库字段存在(支持 SQLite 和 PostgreSQL)"""
5656
try:
57+
db_type = os.getenv('DB_TYPE', 'sqlite').lower()
5758
with get_db_connection() as db:
5859
cursor = db.cursor()
60+
col_names = set()
5961

60-
# SQLite 兼容:使用 PRAGMA table_info 检查列是否存在
61-
try:
62-
cursor.execute("PRAGMA table_info(qd_strategy_positions)")
63-
cols = cursor.fetchall() or []
64-
col_names = {c.get('name') for c in cols if isinstance(c, dict)}
65-
except Exception:
66-
col_names = set()
62+
if db_type == 'postgresql':
63+
# PostgreSQL: 使用 information_schema 查询列
64+
try:
65+
cursor.execute("""
66+
SELECT column_name FROM information_schema.columns
67+
WHERE table_name = 'qd_strategy_positions'
68+
""")
69+
cols = cursor.fetchall() or []
70+
col_names = {c.get('column_name') or c.get('COLUMN_NAME') for c in cols if isinstance(c, dict)}
71+
except Exception:
72+
col_names = set()
73+
else:
74+
# SQLite: 使用 PRAGMA table_info
75+
try:
76+
cursor.execute("PRAGMA table_info(qd_strategy_positions)")
77+
cols = cursor.fetchall() or []
78+
col_names = {c.get('name') for c in cols if isinstance(c, dict)}
79+
except Exception:
80+
col_names = set()
6781

6882
if 'highest_price' not in col_names:
69-
logger.info("Adding highest_price column to qd_strategy_positions (SQLite)...")
70-
# SQLite 不支持 AFTER 子句,类型用 REAL 即可
71-
cursor.execute("ALTER TABLE qd_strategy_positions ADD COLUMN highest_price REAL DEFAULT 0")
83+
logger.info(f"Adding highest_price column to qd_strategy_positions ({db_type})...")
84+
if db_type == 'postgresql':
85+
cursor.execute("ALTER TABLE qd_strategy_positions ADD COLUMN IF NOT EXISTS highest_price DOUBLE PRECISION DEFAULT 0")
86+
else:
87+
cursor.execute("ALTER TABLE qd_strategy_positions ADD COLUMN highest_price REAL DEFAULT 0")
7288
db.commit()
7389
logger.info("highest_price column added")
7490

7591
if 'lowest_price' not in col_names:
76-
logger.info("Adding lowest_price column to qd_strategy_positions (SQLite)...")
77-
cursor.execute("ALTER TABLE qd_strategy_positions ADD COLUMN lowest_price REAL DEFAULT 0")
92+
logger.info(f"Adding lowest_price column to qd_strategy_positions ({db_type})...")
93+
if db_type == 'postgresql':
94+
cursor.execute("ALTER TABLE qd_strategy_positions ADD COLUMN IF NOT EXISTS lowest_price DOUBLE PRECISION DEFAULT 0")
95+
else:
96+
cursor.execute("ALTER TABLE qd_strategy_positions ADD COLUMN lowest_price REAL DEFAULT 0")
7897
db.commit()
7998
logger.info("lowest_price column added")
8099

0 commit comments

Comments
 (0)