Skip to content

Latest commit

 

History

History
456 lines (309 loc) · 36.2 KB

README.en.md

File metadata and controls

456 lines (309 loc) · 36.2 KB

Crypto Flash

News grading · On-demand queries · Daily roundups · Event tracking

This project continuously watches the Jin10 WebSocket feed plus CoinDesk, Decrypt, SEC, CFTC, and Federal Reserve RSS/Atom feeds. When a news item matches your keywords, Gemini grades and summarizes it, then the result is pushed to Telegram. You can also ask questions directly in Telegram, and the bot will use recent monitored flash news as background context.

CI Python Gemini Telegram

English | 繁體中文


Event impact
Turns a market signal into crypto and macro context

Daily digest
A roughly 30-second briefing of the day's important events

Query and tracking
Search recent news, track topics, review timelines, and ask Gemini questions

Project overview

This is a GitHub Actions-driven automation project for tracking and filtering Jin10 flash news, keeping only the items that matter most.

What it does

  • Connects directly to Jin10 WebSocket feeds
  • Polls configurable RSS/Atom sources every two minutes; the first fetch establishes a baseline without replaying old articles
  • Parses messages and removes noise with keyword filtering
  • Sends relevant items to Gemini for grading and summary
  • Pushes important updates to Telegram
  • Complete CPI percentage releases sharing the source, country, reference month, and publication minute are collected for three seconds from the first item, then delivered together with separate headline/core and YoY/MoM labels. Explicitly recognized Jin10 text and indicator cards are supported; other formats retain individual processing. Figures are rendered from source fields while Gemini still controls grading and relevance; no extra market-impact prose is generated. Identical values collapse and conflicting versions are labeled and retained, without claiming official verification. At most 32 groups and 16 items per group are buffered, with early processing at capacity. Late arrivals or restarts can still split a release; pending groups are in memory and inherit the queue's interruption risk. Unrelated news does not wait for the collection window.
  • Adds a Telegram Q&A mode with recent context memory
  • Monitors YouTube channel RSS feeds, summarizes new videos into an adaptive summary with external fact-checking, and pushes them to Telegram

Features

  • WebSocket monitor with auto-reconnect: src/jin10_monitor.py
  • Keyword filtering with built-in defaults and optional KEYWORDS_FILE
  • Gemini grading and summary logic: src/gemini.py
  • Telegram push messaging: src/tg.py
  • Telegram Q&A listener: src/telegram_assistant.py
  • YouTube video monitoring and summaries: src/yt_monitor.py
  • News queries and freshness: src/news_commands.py, with /news, /search, /important, /status, and /health
  • Daily roundups: src/daily_digest.py, with /digest queries and scheduled delivery at 08:15 UTC+8
  • Event tracking: src/event_tracking.py, with subscriptions, timelines, and unread updates
  • Historical news archive: src/news_archive.py, shared by roundups and event tracking
  • Background Gemini recovery, Telegram rate-limit retries, and a bounded news-processing queue
  • Shared recent-news context: data/recent_news.json
  • Scheduled execution via GitHub Actions: Jin10 every 6 hours and YouTube every 30 minutes

How it works

Gemini requests are limited to 120/day for YouTube and 600/day shared by flash analysis, Q&A and probes. Local counters reset at 00:00 UTC+8 and count failed/cancelled attempts and retries. Configure GEMINI_YOUTUBE_DAILY_REQUESTS / GEMINI_LIVE_DAILY_REQUESTS in .env or GitHub Actions Variables (0 pauses, -1 disables the local cap). These are request budgets, not token, currency or provider quota limits.

Transient failures use persisted exponential cooldowns starting at 30 seconds, capped at one hour, with jitter. Longer provider retry hints take precedence; explicit daily-quota errors pause until the next Pacific midnight or a later provider retry hint. The local budget still resets at Taiwan midnight. Calls return immediately during cooldown; monitor iterations or scheduled runs retry when eligible. Pending YouTube work remains saved.

Authentication/configuration errors block attempts until the key/model changes, or GEMINI_POLICY_REVISION changes after fixing external account settings. This does not reset daily consumption. Invalid requests block identical payloads only. Each workflow owns its data/gemini_youtube_usage.json or data/gemini_live_usage.json; corrupt/unwritable state stops calls. Other applications/machines are not counted. Forced termination or remote persistence failure can lose uncommitted counts; this is not a billing hard cap.

Jin10 WebSocket ─┐
RSS/Atom feeds ──┴→ Normalize → Bounded queue → Keyword matching
   ↓
Gemini available: grade and summarize; unavailable: keep ungraded record
   ↓
Save recent_news.json (default: 6 hours / 80 records)
Save news_archive.json (72 hours / 5,000 records)
   ↓
Summary available, relevant, and above the push threshold → Telegram push

recent_news.json → News queries, status, and AI Q&A context
news_archive.json → Daily roundups, timelines, and tracked updates

flash_service.py runs ingestion and Q&A together on one runner, sharing live context. Stop any old standalone Telegram Assistant workflow run before migration to avoid competing Telegram pollers.

The RSS/Atom source list is config/news_feeds.json and accepts HTTPS endpoints only. Run python src/feed_monitor.py to check that every source is currently reachable and parseable without changing seen state or sending Telegram messages. Seen IDs are stored in data/feed_seen.json, preventing workflow restarts from reprocessing the same articles. A newly added source is warmed on its first fetch; only later publications enter the shared queue.

Records are saved before the push threshold check and Telegram delivery, so a saved record does not prove delivery. Only CRITICAL and HIGH items are retained and pushed. MEDIUM and LOW items are discarded immediately after grading, before storage, and are never pushed; unclassified records are still retained. When the queue fills, the oldest pending item is dropped before processing and is not archived.

YouTube video monitor

yt_monitor.py reads the channels in config/yt_channels.json, checks their YouTube RSS feeds for new videos, and processes them in order:

YouTube RSS
   ↓
Parse videos by channel_id
   ↓
Deduplicate with data/yt_seen_ids.json
   ↓
Gemini watches the video and writes an adaptive summary with external fact-checking
   ↓
Push the summary and source link to Telegram

The first run for each channel warms up data/yt_seen_ids.json without notifying existing videos. Subsequent discoveries are all saved as pending. max_new_per_run limits attempts per channel, including retries; excess videos remain pending and are never marked seen merely for exceeding the limit. Failed summaries stay silent and pending until a later run successfully parses the video.

All feeds are saved before processing videos round-robin (A1, B1, C1, A2, B2, C2). data/yt_schedule.json records the next channel before each attempt so interrupted runs resume fairly; completed runs also rotate their starting channel. A 21-minute processing deadline leaves work pending for later runs. Discovery continues even if Telegram is unavailable. Videos that left RSS before ever being discovered cannot be recovered automatically; previously skipped legacy seen IDs are not replayed.

Example channel configuration:

[
  {
    "name": "Crypto Punk",
    "channel_id": "UCeeeGbipVKpz23A8_c3I3uA",
    "system_prompt": "以 HEIMDALL 的口吻說明",
    "max_new_per_run": 3
  }
]

name must be unique, and channel_id is the YouTube channel ID. system_prompt sets the channel focus. Video summaries target 200–300 Chinese characters with an opening takeaway sentence without a heading, three direct bullets without a separate list heading, and a bold problem-addressed heading. The final section identifies a specific reader difficulty and the explanation or method the video offers without overstating its scope. The title is bold, the channel is italic, and a compact watch-video link closes the message. The formatter separates bullets and normalizes excess blank lines. Google Search adds 80–120 characters under a single context and caveats heading, checking only 1–2 consequential claims with sources. These are generation targets, not truncation limits. Search failures do not add a status notice; the summary is delivered and research retries in the background for later delivery. Search adds API usage, latency, and plan-dependent charges.

data/yt_progress.json separately records notification, summary completion, research completion, generated content, and delivery receipts. A failed summary sends nothing, remains unread, and stays pending until parsing succeeds. Failed research preserves and delivers the successfully parsed summary; later runs send only the research supplement. Pending videos resume even after leaving RSS or when feed fetching fails. Oldest-attempted pending work runs first within the per-channel limit. Completed steps are reused.

Long reports are split into multiple Telegram messages with a saved cursor after each successful part. A crash between Telegram acceptance and durable local/remote persistence can still cause duplicates. Pending records are never pruned; the latest 300 completed records are retained (using YT_MAX_SEEN_IDS). Existing data/yt_seen_ids.json entries remain deduplicated without historical replay; old failures cannot be inferred or backfilled automatically. GitHub Actions persists both files.


Quick start

1. Clone or fork the repo

git clone https://github.com/Yili-code/Crypto-Flash.git
cd Crypto-Flash

2. Configure environment variables

Copy .env.example to .env and fill in the values:

TELEGRAM_BOT_TOKEN_01=""
TELEGRAM_BOT_TOKEN_02=""
TELEGRAM_CHAT_ID=""
GEMINI_API_KEY=""
GEMINI_MODEL="gemini-3.5-flash-lite"

Bot 01 handles Jin10 pushes, news commands, tracking, Q&A, and daily delivery; bot 02 handles YouTube. News queries, roundups, and tracking need no Gemini key, but require saved news data. TELEGRAM_CHAT_ID also restricts which chat the assistant accepts. Run the commands from the project root with Python 3.12; start the monitor and assistant in separate terminals.

3. Install dependencies

pip install -r requirements.txt

4. Run the monitor

python src/jin10_monitor.py

5. Run monitoring and Telegram Q&A together (instead of step 4)

python src/flash_service.py

In a Telegram group, you can mention the bot or use /ask; in private chat, you can send a question directly.

Q&A uses a mobile-friendly layout with four sections: conclusion, confirmed facts, market implications, and signals to watch. Headings stand alone, sections have blank lines, and short fact bullets place their source and full UTC+8 timestamp on a separate line. These are model output guidelines; actual length and formatting may vary.

News queries and daily roundups

Command Purpose
/digest Yesterday's roundup, ordered by CRITICAL and HIGH; up to 8 events
/digest today Today's roundup so far
/digest YYYY-MM-DD A selected date within the retained archive
/news, /news 10 Latest 5 or 10 records, with a maximum of 10
/search BTC Case-insensitive title/body search; multiple words match as a phrase
/important, /important 10 HIGH and CRITICAL news only
/status Record counts, tier distribution, and latest record timestamp
/health Persisted pipeline health, blocked AI scopes, and pending work
/help, /start Command category index
/help news Full news-query syntax
/help digest Full daily-roundup syntax
/help track Full event-tracking syntax
/help ask Full AI-analysis syntax

/help uses two-level command discovery: the first level lists categories only, and /help <category> expands the complete syntax for that category. Except for /ask, these commands work without a Gemini key and accept /command@bot_username in groups. The assistant must be running to answer them. News queries display source excerpts; daily roundups reuse previously generated AI summaries, with no new model calls or cross-event inference. Ungraded raw news is never substituted for a daily summary.

Like the Jin10 monitor, the assistant workflow starts every six hours and runs the service for 350 minutes, leaving time to persist tracking progress before the 360-minute job deadline. This provides near-continuous availability, with a gap between runs that scheduling delays can extend; it is not seamless 24/7 operation. Daily delivery is an independent workflow and does not require the assistant to be running.

daily_digest.yml is scheduled for 08:15 UTC+8, delivering the previous calendar day's roundup through bot 01. Dates use the news ingestion timestamp in UTC+8. The separate data/news_archive.json retains 72 hours, up to 5,000 records; the existing six-hour Q&A context stays unchanged. First use needs time to accumulate records. Empty or partial data is identified explicitly, and observed timestamps do not imply complete coverage.

Actions read the files available at checkout; updates in a running monitor are only visible after persistence. /status describes that data snapshot, not live connection health. The monitor stops after 350 minutes to leave time for persistence before its job deadline.

Successful delivery records the date in data/daily_digest_state.json; rerunning the same day skips delivery, and failed sends do not advance state. Corrupt state stops the job. A crash or persistence failure after sending can still cause a duplicate on retry, so inspect delivery logs before rerunning a failed job.

The digest body targets 150–220 characters and has a 250-character limit. If the body exceeds the limit, the repair prompt asks for at most two topics. Scheduled digests can retry one transient Gemini failure after a cooldown of up to 120 seconds. Retries count toward the daily request budget.

Scheduled execution requires merging the workflow into the default branch, and GitHub schedules may be delayed. Manual workflow dispatch is also available. Running python src/daily_digest.py locally sends yesterday's report.

Choosing a query

Need Command and data scope
Scan recent news /news, /search, /important: default six-hour context, up to 80 stored records
Review a day /digest: selected date within the 72-hour archive, using saved summaries
Review a topic /timeline phrase: 72-hour archive, no subscription required
Resume reading /track phrase, then /updates: unread developments collected after subscribing
Ask for analysis /ask question: defaults to 40 recent background titles or body openings; requires Gemini

These scopes help avoid mistaking an empty short-term search for an absence of events, while unread progress reduces repeated reading. All queries depend on collected data; /ask does not perform a live web search.

Event tracking and follow-ups

Command Purpose
/track spot ETF Track this case-insensitive phrase from the time it is added
/tracks List topics and unread counts
/timeline spot ETF Latest 8 matching records from the 72-hour archive, ordered by ingestion time
/updates Read new records across tracked topics, oldest first, up to 8 at a time
/updates spot ETF Read new records for one tracked topic
/untrack spot ETF Remove a subscription without deleting news

Matching uses the full phrase in titles, bodies, and saved summaries, without model calls or inferred causal links. Translations and synonyms are not expanded automatically. Timeline queries do not require a subscription or change reading progress. Output distinguishes saved summary excerpts from source excerpts.

Updates are on demand, not additional automatic alerts. Reading progress advances only after Telegram confirms delivery, and only for displayed records. Overflow stays unread for the next request. A record matching multiple topics is shown once in a combined query; a topic-specific query advances only that topic. Existing records remain available through /timeline, but are not unread when a new subscription is created. Re-adding a phrase does not reset progress.

Up to 12 topics of 40 characters each are supported. The configured TELEGRAM_CHAT_ID shares one topic list and progress state: members who can issue commands can manage it. Event commands are disabled without a configured chat. The assistant is the sole writer of data/event_tracking.json and commits it after each workflow run, so topic visibility follows repository visibility. Local installations may set EVENT_STATE_FILE to another path.

Set TELEGRAM_OWNER_USER_IDS to a comma-separated allowlist to restrict paid AI commands, health details, and shared tracking state. Read-only news search remains available to the configured chat. Processed Telegram update IDs are persisted to reduce duplicate replies after scheduled restarts; a crash between Telegram acceptance and saving the receipt can still duplicate a response.

The 72-hour/5,000-record archive and checkout snapshot still limit coverage. Old unread records can expire, and no new records does not prove there were no external developments. If a message arrives but state writing or persistence fails, a subsequent query can repeat it.

6. Run the YouTube monitor (optional)

python src/yt_monitor.py

Before running it, add the channels to config/yt_channels.json. The script processes all configured channels once and then exits, so it is intended to be used with a scheduler or GitHub Actions.


GitHub Actions deployment

The public monitoring and verification path uses five workflows:

Workflow Purpose
flash_monitor.yml Runs src/flash_service.py for live ingestion and Q&A on a schedule and pushes filtered news
yt_monitor.yml Runs src/yt_monitor.py to monitor YouTube videos and push summaries
ci.yml Runs ruff and pytest on push / PR; uses no secrets
daily_digest.yml Sends yesterday's roundup at 08:15 UTC+8 and persists the delivery date
economic_calendar.yml Sends a two-day economic calendar at 08:00 UTC+8 and persists delivery state

Set these in GitHub Settings → Secrets and variables → Actions:

Secret / Variable Description
GEMINI_API_KEY Gemini API key
TELEGRAM_BOT_TOKEN_01 Telegram bot token
TELEGRAM_BOT_TOKEN_02 Telegram bot token used by the YouTube monitor
TELEGRAM_CHAT_ID Target chat ID for pushes
TELEGRAM_OWNER_USER_IDS Optional comma-separated sender IDs allowed to use paid AI, health, and tracking commands
GEMINI_MODEL Optional; defaults to gemini-3.5-flash-lite

The Jin10 monitor workflow runs every 6 hours. yt_monitor.yml runs at minute 0 and minute 30 of every hour. Both workflows support manual workflow_dispatch.

Set GEMINI_MODEL as an Actions Variable and the other listed credentials/chat settings as Secrets. To use other environment options in Actions, add them to the relevant workflow step’s env; creating a repository variable alone does not pass it to the script.

State persistence

data/recent_news.json (recent flash-news context) and data/yt_seen_ids.json (already-pushed videos) have to survive between runs. Without them, the Q&A bot loses its context and the YouTube monitor warms up again, skipping the videos currently in the feed.

These files, along with data/news_archive.json, data/daily_digest_state.json, data/event_tracking.json, data/classification_backlog.json, and data/telegram_update_state.json, are committed back to the repository by .github/actions/persist-state at the end of each run:

  • Each file has exactly one writing workflow, so on a push race the writer replays its own copy on top of the current tip instead of clobbering another workflow's changes.
  • Nothing is committed when the content did not change. Commit messages carry [skip ci], and ci.yml ignores data/**.
  • The writing workflows need permissions: contents: write. If your repository is configured with a read-only GITHUB_TOKEN, switch Settings → Actions → General → Workflow permissions to Read and write permissions.

An earlier version kept these files in the GitHub Actions cache. Cache entries are evicted after 7 days of no use, are matched by key prefix (which silently restored the wrong entry), and cannot be inspected — hence the move to plain commits.

For private or always-on deployment, set CRYPTOFLASH_STATE_DIR to a durable mounted directory outside the repository. docker compose up -d flash uses the gitignored runtime-data/ mount. This removes new runtime data from source-control history and keeps the assistant alive continuously; it does not erase state already present in Git history. GitHub Actions keeps the repository-backed compatibility path because Actions runners have no durable local disk.


Configurable environment variables

Shared settings

Variable Default Purpose
TELEGRAM_BOT_TOKEN_01 empty Telegram Bot Token
TELEGRAM_CHAT_ID empty Push target / source chat guard for Q&A
TELEGRAM_OWNER_USER_IDS empty Optional sender-ID allowlist for paid AI, health, and shared tracking commands
TELEGRAM_MIN_SEND_INTERVAL 3.5 Minimum seconds between two pushes, to stay under Telegram's rate limit
TELEGRAM_MAX_RETRY_AFTER 30 Cap on the 429 backoff (Telegram sometimes asks for several minutes)
GEMINI_API_KEY empty Gemini API key
GEMINI_MODEL gemini-3.5-flash-lite Model to use
CRYPTOFLASH_STATE_DIR data Runtime-state root; always-on deployments should use a durable volume outside the repository
NEWS_CONTEXT_FILE data/recent_news.json Shared recent-news cache
CONTEXT_MAX_AGE_SEC 21600 Max age for background context

Monitor settings

Variable Default Purpose
MAX_TIER_TO_SEND HIGH Push threshold; may be narrowed to CRITICAL, while MEDIUM and LOW are always discarded
KEYWORDS_FILE empty Optional custom keyword file
WS_URLS wss://wss-flash-2.jin10.com/ Jin10 WebSocket endpoint
WS_IDLE_TIMEOUT 180 Reconnect if no traffic is seen
WS_RECONNECT_DELAY 5 Delay before reconnect
CONTEXT_MAX_ITEMS 80 Max recent items retained
OUTBOX_MAXSIZE 200 Pending-item queue size; the oldest is dropped when full so the receive loop never blocks
GEMINI_RECONNECT_DELAY 30 Background retry interval in seconds while Gemini is unavailable, clamped to at least 1 second
NEWS_ARCHIVE_FILE data/news_archive.json Daily report archive, retaining 72 hours and up to 5,000 records
DIGEST_STATE_FILE data/daily_digest_state.json Most recently delivered digest date, written by the digest script
CLASSIFICATION_BACKLOG_MAX_ITEMS 500 Maximum fresh Gemini classification retries retained
CLASSIFICATION_BACKLOG_MAX_AGE_SEC 3600 Retry freshness window; expired flashes remain ungraded and are never pushed late
MONITORING_FLUSH_INTERVAL 30 Seconds between batched metrics writes

If the Gemini startup check or a summary request fails, flash pushes pause and a background task checks the connection every 30 seconds until it recovers. The monitor keeps receiving news and saving matching items as context, without forwarding raw text. Matching items enter a bounded classification backlog with a default one-hour expiry. After recovery, the background task processes up to 25 fresh items per pass, newest first, then waits 30 seconds before the next pass. A missing API key also pauses pushes. This recovery task operates independently of the existing Jin10 WebSocket reconnect loop. An unset or blank GEMINI_MODEL uses the default model.

Q&A settings

Variable Default Purpose
CONTEXT_SNIPPET_LIMIT 40 Number of recent items included in the answer prompt
EVENT_STATE_FILE data/event_tracking.json Shared topic subscriptions and acknowledged reading progress
TELEGRAM_UPDATE_STATE_FILE data/telegram_update_state.json Last completed Telegram update receipt used across restarts

YouTube monitor settings

Variable Default Purpose
TELEGRAM_BOT_TOKEN_02 empty Telegram bot token used for YouTube summary pushes
YT_CHANNELS_CONFIG config/yt_channels.json Path to the YouTube channel configuration
YT_MAX_NEW_PER_RUN 3 Maximum pending video attempts per channel per run, including retries; excess work is retained
YT_SEEN_STATE_FILE data/yt_seen_ids.json Path to the processed-video state file
YT_PROGRESS_FILE data/yt_progress.json Notification, summary, research and delivery progress; custom paths also require updating workflow persistence
YT_SCHEDULE_FILE data/yt_schedule.json Next round-robin channel; custom paths require updating workflow persistence
YT_RUN_BUDGET_SECONDS 1260 Processing deadline; keep below the workflow's 24-minute external timeout
YT_MAX_SEEN_IDS 300 Maximum processed video IDs retained per channel

Development and testing

pip install -r requirements-dev.txt
pytest          # unit tests; never touches the network
ruff check .    # static checks

The suite covers Jin10 flash parsing and the binary WebSocket protocol, the outbox back-pressure behaviour, Telegram retry and throttling logic, YouTube RSS parsing and the dedup state machine, and Q&A question detection. It also covers news queries, digest dates and summary deduplication, digest delivery state, event unread progress and delivery acknowledgment, and Gemini recovery. No API keys are required and no network requests are made.


Contributing

To report a reproducible problem or propose a focused improvement, open an issue and read CONTRIBUTING.md. Parser fixtures, failure-path tests, documentation corrections, and permitted RSS/Atom feeds are useful starting points.

The project is released under the MIT License. Use, modification, and redistribution are allowed when the copyright and license notice are retained.


Important notes

  • This project is meant for technical learning, monitoring, and personal research.
  • The scraped content remains the property of Jin10.
  • Gemini-generated summaries are auxiliary analysis and not investment advice.
  • Final decisions should be based on official releases and current market conditions.

Disclaimer

AI-generated summaries and analysis are for reference only and do not constitute investment advice. Markets are risky; do your own research before making financial decisions.

If this project saved you time filtering market noise, consider giving it a star.

The Event Reminder covers today and tomorrow in Taiwan time, from today at 00:00 through the day after tomorrow at 00:00 (exclusive). It includes US CPI, non-farm payrolls, and FOMC decisions, projections, and press conferences.

Pre-event market briefing

The live flash_service.py checks CPI, non-farm payrolls, and FOMC events every 60 seconds and refreshes the two-day calendar every 15 minutes. A briefing becomes due one hour before release. Simultaneous events share one briefing; a late start catches up only before the release. Actions delays, runner gaps, model latency, and Telegram latency prevent an exact delivery-time guarantee.

The briefing includes all recorded successful flash deliveries from Taiwan midnight through generation time, using delivery dates rather than the ingestion dates used by /digest. It targets five minutes of reading (1,200–1,800 Chinese characters), delivered in four sections: today's news, its relationship to the indicator, conditional release scenarios, and what to watch afterward. It distinguishes reported facts, general mechanisms, and hypothetical outcomes without inventing consensus estimates, prior values, release results, or guaranteed market directions. Retried segments retain the original analysis and cutoff time.

Archived but undelivered news is excluded. Historical archives cannot establish delivery before this feature was enabled. Initial rollout, monitoring gaps, and unsaved records may leave gaps. No-news notices skip AI. Inputs over 300,000 characters, invalid AI output, invalid source IDs, and invalid lengths produce an explicit failure notice and retry every five minutes before release. There is no raw-news fallback. Requests use the existing live Gemini budget, including failed requests.

Only flash_monitor.yml writes data/delivered_flashes.json (72-hour delivery journal) and data/event_briefing_state.json (cached analysis and per-segment progress). Progress advances after Telegram confirms success. Delivery and local/GitHub persistence are not atomic: restarts can still duplicate messages if delivery succeeded before progress was persisted.

For an explicit calendar delivery check, set force=true on economic_calendar workflow_dispatch (or use --force). This resends today's two-day reminder; scheduled runs retain date-based deduplication.

Each event in the scheduled reminder has a Google Calendar button that opens a prefilled 15-minute slot at the release time. Choose a calendar and save the event to add it.

To preview the Google Calendar button in a separate Telegram test group, set TELEGRAM_TEST_CHAT_ID and run python src/economic_calendar.py --preview-calendar-button. Set TELEGRAM_TEST_BOT_TOKEN if the group uses a dedicated bot. The preview sends a labeled sample CPI event with a 15-minute calendar slot and leaves scheduled delivery state untouched.

Calendar week coverage is validated in America/New_York. If Forex Factory is unavailable, stale, or cannot cover the two Taiwan dates, the runtime queries TradingView's US calendar for that exact UTC interval. The fallback validates response status, schema, country, and timestamps before filtering CPI, nonfarm payrolls, and FOMC events. Federal Reserve monthly calendars supply explicit press-conference times; the Fed's meeting calendar identifies projection meetings, using the confirmed rate-decision timestamp. Failed or incomplete fallback data remains unavailable and never advances delivery state. Transport failures retain bounded retries; HTTP 429 waits at least 60 seconds and honors Retry-After up to a 180-second budget. Calendar-code pushes to main trigger a normal deduplicated delivery check, as do daily scheduled runs. These public endpoints have no availability guarantee; a provider outage can still cause an explicit failure.

Set briefing_preview=true on a manual flash_monitor run to request one five-minute preview. The request lasts two days and waits for a newly confirmed flash delivery, then uses the next real unreleased event in the two-day calendar. Messages are labeled as a manual preview, separate from scheduled reminders. The live workflow persists the request and segment progress across restarts and stops after successful delivery. No event is fabricated.

If a briefing draft fails format, length, or source validation, the model receives the specific validation error for at most one immediate correction. Two invalid drafts return to the five-minute backoff. Unavailable or deferred model calls do not cause immediate extra requests. Corrections count toward the live budget; diagnostics record validation reasons and character counts, not complete drafts.

Flash quality: omit optional impact sections together with their headings when empty. Use Traditional Chinese financial vocabulary while retaining abbreviations such as Fed and CPI. Require source-supported analysis and conditional wording for inference; use a factual summary alone when evidence is insufficient. Do not invent dates, data periods or price trends. Routine sentiment remarks are not HIGH merely because a Fed official made them. Clean empty headings before storage and reject empty or non-string summaries. All flashes show their source, including Jin10. Prompt constraints reduce unsupported inference but are not automated fact-checking.

Flash quality rules

The grading prompt caps routine speech previews without actual remarks or new policy information at MEDIUM. Briefings use natural Traditional Chinese and include an optional market-impact section only when the source supports a specific transmission mechanism, with conditional inferences. Missing economic values and market reactions must not be invented. Spacing and common financial vocabulary are normalized. Every flash shows its source, linked when an HTTPS source URL is available. Classification and analysis remain model judgments; offline tests are not a live model quality evaluation.

The Telegram menu lists one-tap commands: /news, /important, /digest, /tracks, /updates, /status, and /help. Parameterized commands remain available by typing them; see /help for syntax. The assistant refreshes the default menu at startup; a menu update failure does not stop the service.

The shared Telegram sender converts visible Chinese prose to Taiwan Traditional Chinese, including /news and /search excerpts and AI replies. English is not translated; HTML, URLs, and code/pre contents are preserved. Stored source data and topic matching remain unchanged, with no extra AI requests. Previously delivered messages are not edited.

Gemini 429 logs include the operation, model, retry hint, and quota metrics/limits, excluding raw error messages, prompts, and project identifiers.

Privileged and paid commands fail closed: an empty TELEGRAM_OWNER_USER_IDS denies access. Only allowlisted Telegram user IDs may use /ask, /digest, /health, and tracking management commands. Ordinary news queries retain the existing chat restriction.

YouTube supports an explicit GEMINI_SEARCH_MODEL for Google Search verification. Unset values preserve GEMINI_MODEL; video summarization stays on the main model. Configuration changes re-evaluate error state without resetting the daily request count. Gemini 3.5 Flash-Lite does not offer Search grounding on the free API tier; choose a supported model explicitly or enable billing.

A Gemini request returning 404 triggers a model availability check. Only a model lookup returning 404 creates a permanent configuration block; other outcomes use retry backoff. The YouTube workflow supports probe_search=true for one citation-validated grounding check without Telegram delivery, using its existing request ledger and single writer.

A model catalog entry does not guarantee generation access for new projects. An explicit provider response that a model is no longer available to new users blocks automatic retries until an authorized, usable configuration is provided. Catalog or pricing listings alone are not recovery evidence.

Heimdall keeps ordinary replies focused on content: news and tracking retain time, attribution, and key information while hiding internal tiers, displayed-result counts, timezone labels, and processing details. /status shows recent item count and the latest update. Digests warn briefly only when messages were actually omitted. Q&A length follows the question rather than forcing a multi-section template. Missing data, failures, and material uncertainty stay explicit; /health shows actionable issues; full technical diagnostics remain available from the command line.