Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions docs/routine-daily-digest-migration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Consolidate routine cycle notifications with the existing daily digest

The central `daily_digest_aggregator` already renders a single message from
private producer candidates across accounts. Its sender makes one Telegram
call per daily report. Sharing a bot with platform runtimes does not combine
their independent sends: cycle notifications and urgent attention pages are
separate from the scheduled central digest.

Binance [PR #378](https://github.com/QuantStrategyLab/BinancePlatform/pull/378)
adds opt-in candidates and intentionally does not enable production. The
Schwab and IBKR candidate producers and this repository's private-store reader
already exist. Reuse them; no additional notify repository, bot, server,
database or IAM changes are needed.

The proposed platform integration uses generic, per-target
`QSL_ROUTINE_NOTIFICATION_MODE=immediate|daily_digest`, default `immediate`.
Only verified healthy no-order cycle notices move into the daily report.
Risk blocks, pending/unknown orders, reconciliation and persistence problems,
and actual order activity remain immediate. Immediate alerts may also appear
as historical context in the daily report; a recap does not release a guard.

Both existing `v1` and `sections_v2` templates support `zh-CN` and `en`.
Language is configured separately from delivery mode. A typical routine
conclusion is `✅ 无需调仓` / `✅ No rebalance needed`; unknown fills remain
`成交数未知` / `fill counts are unknown`. Signals and tips authored as prose
retain their producer language; producers should use supported machine tokens
for bilingual rendering instead of expecting free text to be translated.

## Approval and rollout

1. Verify fresh candidates for the same business day, exact private target
identity and original archived report. Do not copy private rows to public
artifacts. Preserve unknown counts and report incomplete coverage.
2. Verify one complete central digest and actual delivery, then verify urgent
alerts independently. Existing CI success or a successful storage preflight
cannot substitute for delivery.
3. Obtain owner approval for the consumer deployment and one target's mode
change. Keep other targets on their current notification paths. Reverting
the mode to `immediate` restores the original notification decision.

The latest inspected public natural-run receipt had five stale candidates and
an unknown global fill count. It does not qualify as replacement coverage.
Inspect producer dates and the existing window before enabling suppression;
do not remove freshness or evidence checks to make a digest appear healthy.

中文:现有日报已经能把多个账户放进一条消息。消息仍分开发送,是平台周期通知、
风控即时通知与中央日报各自发送,尚未切换正常周期的通知方式。
本草稿复用既有存储与中英文模板;生产部署及开关变更需要负责人批准。
12 changes: 11 additions & 1 deletion python/scripts/daily_digest_notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,15 @@ def _render_observation_block(entry: DigestRunEntry, locale: DigestLocale) -> li
tip_text = str(tip).strip()
if tip_text:
lines.append(f"- {_t(locale, 'tip_prefix')}: {tip_text}")
# Rich observations must not hide unknown order/fill evidence that is
# visible in the thin-row renderer. This is presentation only.
for label, value, status in (
("fills_label", entry.fill_count, entry.fill_count_status),
("orders_label", entry.order_count, entry.order_count_status),
("cycles_label", entry.cycle_count, entry.cycle_count_status),
):
if status == "unknown" or value is None:
lines.append(_format_count_part(locale, label_key=label, value=value, status=status))
conclusion = _default_conclusion(entry, locale)
if conclusion:
lines.append(conclusion)
Expand Down Expand Up @@ -1104,9 +1113,10 @@ def render_daily_digest(payload: DailyDigestInput) -> str:
else:
lines.append(_t(locale, "daily_digest_heartbeat_title"))
lines.append(f"{_t(locale, 'date_label')}: {payload.business_day}")
if known_fills is None:
lines.append(_t(locale, "heartbeat_fills_unknown"))
if not rich:
if known_fills is None:
lines.append(_t(locale, "heartbeat_fills_unknown"))
lines.append(_t(locale, "ran_section"))
elif known_fills == 0:
lines.append(_t(locale, "heartbeat_no_fill_verified"))
Expand Down
48 changes: 27 additions & 21 deletions python/tests/test_daily_digest_notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def test_rich_rebalance_block_ibkr_style(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
fill_count=1,
order_count=1,
equity=569.16,
Expand All @@ -208,7 +208,7 @@ def test_rich_rebalance_block_ibkr_style(self):
)
)
self.assertIn("收盘日报", text)
self.assertIn("[ibkr U16608560] ⏳ 【待确认】", text)
self.assertIn("[ibkr U00000001] ⏳ 【待确认】", text)
self.assertIn("纳斯达克增长收益", text)
self.assertIn("USD 569.16", text)
self.assertIn("TQQQ: $312.40 / 4股", text)
Expand All @@ -220,7 +220,7 @@ def test_no_order_reason_renders(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
equity=572.93,
holdings=(
daily_digest_notify.DigestHolding(
Expand All @@ -236,7 +236,7 @@ def test_no_order_reason_renders(self):
business_day="2026-10-08", locale="zh", runs=runs
)
)
self.assertIn("[ibkr U16608560] ⚠️ 【未下单】", text)
self.assertIn("[ibkr U00000001] ⚠️ 【未下单】", text)
self.assertIn("低于最小订单金额:TQQQ", text)

def test_english_observation_labels(self):
Expand Down Expand Up @@ -428,9 +428,11 @@ def test_single_schwab_omits_window_and_channel(self):
expected = (
"📡 量化哨兵 · 心跳\n"
"业务日: 2026-10-09\n"
"今日有运行,成交数未知(证据未覆盖)。\n"
"[schwab live] 💓 【心跳检测】\n"
"🧭 策略: 半导体趋势收益\n"
"💰 账户总权益: USD 989.34\n"
"成交 未知\n"
"✅ 无需调仓\n"
"平台: schwab"
)
Expand All @@ -456,7 +458,7 @@ def test_multi_platform_observation_blocks_separated(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
fill_count=0,
equity=569.16,
holdings=(
Expand Down Expand Up @@ -487,23 +489,25 @@ def test_multi_platform_observation_blocks_separated(self):
self.assertIn("💰 账户总权益: USD 989.34", text)
self.assertIn("💰 账户总权益: USD 569.16", text)
self.assertIn("[schwab live] 💓 【心跳检测】", text)
self.assertIn("[ibkr U16608560] 💓 【心跳检测】", text)
self.assertIn("[ibkr U00000001] 💓 【心跳检测】", text)
# Blank line between observation blocks.
schwab_idx = text.index("平台: schwab")
ibkr_idx = text.index("[ibkr U16608560]")
ibkr_idx = text.index("[ibkr U00000001]")
between = text[schwab_idx:ibkr_idx]
self.assertIn("\n\n", between)
# Exact multi-platform shape for zh locale — every block has [account] tag.
expected = (
"📡 量化哨兵 · 心跳\n"
"业务日: 2026-10-09\n"
"今日有运行,成交数未知(证据未覆盖)。\n"
"[schwab live] 💓 【心跳检测】\n"
"🧭 策略: 半导体趋势收益\n"
"💰 账户总权益: USD 989.34\n"
"成交 未知\n"
"✅ 无需调仓\n"
"平台: schwab\n"
"\n"
"[ibkr U16608560] 💓 【心跳检测】\n"
"[ibkr U00000001] 💓 【心跳检测】\n"
"🧭 策略: 纳斯达克增长收益\n"
"💰 账户总权益: USD 569.16\n"
"💼 持仓\n"
Expand All @@ -517,32 +521,32 @@ def test_account_block_tag_preference_order(self):
hint_wins = daily_digest_notify.DigestRunEntry(
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
account_hint="U16608560",
account_hint="U00000001",
account_scope="live",
opaque_account_uid="aaaaaaaaaaaaaaaa",
target_id="ibkr-primary",
)
self.assertEqual(
daily_digest_notify.account_block_tag(hint_wins), "ibkr U16608560"
daily_digest_notify.account_block_tag(hint_wins), "ibkr U00000001"
)
# Lowercase broker hint normalizes to U######.
lower_hint = daily_digest_notify.DigestRunEntry(
platform_id="ibkr",
strategy_profile="soxl_soxx_trend_income",
account_hint="u15998061",
account_hint="u00000002",
account_scope="live",
)
self.assertEqual(
daily_digest_notify.account_block_tag(lower_hint), "ibkr U15998061"
daily_digest_notify.account_block_tag(lower_hint), "ibkr U00000002"
)
# Scope embedding live-u###### → broker id without needing account_hint.
embedded = daily_digest_notify.DigestRunEntry(
platform_id="ibkr",
strategy_profile="soxl_soxx_trend_income",
account_scope="live-u15998061",
account_scope="live-u00000002",
)
self.assertEqual(
daily_digest_notify.account_block_tag(embedded), "ibkr U15998061"
daily_digest_notify.account_block_tag(embedded), "ibkr U00000002"
)
# Hex-only hint is rejected; platform+scope wins.
hex_hint = daily_digest_notify.DigestRunEntry(
Expand Down Expand Up @@ -613,7 +617,7 @@ def test_trade_success_observation_block_zh(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
fill_count=1,
order_count=1,
equity=569.16, # fixture (not live)
Expand All @@ -640,7 +644,7 @@ def test_trade_success_observation_block_zh(self):
expected = (
"📡 量化哨兵 · 收盘日报\n"
"业务日: 2026-10-09\n"
"[ibkr U16608560] 🔔 【调仓指令】\n"
"[ibkr U00000001] 🔔 【调仓指令】\n"
"🧭 策略: 纳斯达克增长收益\n"
"💰 账户总权益: USD 569.16\n"
"💼 持仓\n"
Expand Down Expand Up @@ -707,7 +711,7 @@ def test_multi_heartbeat_plus_fills_uses_digest_title(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
fill_count=1,
order_count=1,
equity=569.16, # fixture
Expand All @@ -731,13 +735,15 @@ def test_multi_heartbeat_plus_fills_uses_digest_title(self):
expected = (
"📡 量化哨兵 · 收盘日报\n"
"业务日: 2026-10-09\n"
"今日有运行,成交数未知(证据未覆盖)。\n"
"[schwab live] 💓 【心跳检测】\n"
"🧭 策略: 半导体趋势收益\n"
"💰 账户总权益: USD 989.34\n"
"成交 未知\n"
"✅ 无需调仓\n"
"平台: schwab\n"
"\n"
"[ibkr U16608560] 🔔 【调仓指令】\n"
"[ibkr U00000001] 🔔 【调仓指令】\n"
"🧭 策略: 纳斯达克增长收益\n"
"💰 账户总权益: USD 569.16\n"
"💼 持仓\n"
Expand Down Expand Up @@ -795,7 +801,7 @@ def test_machine_token_signal_and_conclusion_localized_zh(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
equity=582.12,
signal_summary="no_action",
rebalance_kind="no_order",
Expand All @@ -811,7 +817,7 @@ def test_machine_token_signal_and_conclusion_localized_zh(self):
business_day="2026-10-09", locale="zh", runs=runs
)
)
self.assertIn("[ibkr U16608560] ⚠️ 【未下单】", text)
self.assertIn("[ibkr U00000001] ⚠️ 【未下单】", text)
self.assertIn("- 🎯 信号: 无需操作", text)
self.assertNotIn("no_action", text)
self.assertNotIn("\nno_order\n", text)
Expand All @@ -822,7 +828,7 @@ def test_machine_token_signal_and_conclusion_localized_zh(self):
platform_id="ibkr",
strategy_profile="tqqq_growth_income",
strategy_label="纳斯达克增长收益",
account_hint="U16608560",
account_hint="U00000001",
equity=572.93,
signal_summary="no_action",
rebalance_kind="no_order",
Expand Down
58 changes: 58 additions & 0 deletions python/tests/test_routine_daily_digest_contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Offline proof that two producer observations use one bilingual digest send."""

import json
import os
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from io import StringIO
from pathlib import Path
from unittest import mock

SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
if str(SCRIPTS) not in sys.path:
sys.path.insert(0, str(SCRIPTS))

import send_daily_digest_telegram as sender # noqa: E402


class RoutineDailyDigestContractTests(unittest.TestCase):
def test_one_send_contains_both_accounts_in_zh_cn_and_en(self):
for locale, conclusion, unknown in (
("zh-CN", "无需调仓", "未知"),
("en", "No rebalance needed", "unknown"),
):
with self.subTest(locale=locale), tempfile.TemporaryDirectory() as tmp:
candidates = Path(tmp) / "synthetic-candidates.json"
candidates.write_text(json.dumps({"runs": [
{
"platform_id": platform, "strategy_profile": "demo_strategy",
"opaque_account_uid": "demo-" + platform,
"target_id": platform + "/demo-target", "account_hint": platform + "-demo",
"business_day": "2026-10-12", "actually_ran": True,
"fill_count": None, "order_count": 0, "cycle_count": 1,
"field_status": {"fill_count": "counts_unknown"},
"rebalance_kind": "no_rebalance", "rebalance_conclusion": "no_rebalance",
"signal_summary": "no_action",
}
for platform in ("schwab", "ibkr")
]}))
with mock.patch.dict(os.environ, {
"TELEGRAM_TOKEN": "synthetic-token", "GLOBAL_TELEGRAM_CHAT_ID": "synthetic-chat",
}, clear=True), mock.patch.object(sender, "send_telegram_message", return_value=True) as send, redirect_stdout(StringIO()):
code = sender.main([
"--no-github", "--business-day", "2026-10-12", "--locale", locale,
"--candidates", str(candidates),
])
self.assertEqual(code, 0)
send.assert_called_once()
text = send.call_args.kwargs["text"]
self.assertIn("schwab", text)
self.assertIn("ibkr", text)
self.assertEqual(text.count(conclusion), 2)
self.assertIn(unknown, text)


if __name__ == "__main__":
unittest.main()