~/vimal-jain
FinTech AIJan 2026

AI-Assisted Swing Trading Watchlist & Alert Engine

An automated, event-driven market monitoring engine that evaluates dynamic stock watchlists using multi-timeframe technical indicators and grounded LLM sentiment analysis to dispatch deduplicated, evidence-backed alerts via Telegram and real-time SSE streams.

Problem Statement

Retail swing traders tracking dozens of equities struggle with cognitive fatigue, noisy price alerts, and disjointed analytical workflows. Traditional monitoring tools trigger brittle threshold alerts (e.g., crossing a static price or RSI level) without contextual awareness of broader market trends, multi-timeframe confirmation, or qualitative catalysts like high-impact earnings and regulatory announcements. Conversely, naive LLM integrations hallucinate market sentiment, breach external API rate ceilings, and spam users with redundant notifications during prolonged consolidations. Traders need an autonomous, resilient engine that continuously fuses quantitative technical indicators with grounded news sentiment, applying strict deduplication and stateful diffing to emit actionable, evidence-backed signals only when market conditions materially shift.

System Architecture & Data Flow

The system adopts an asynchronous, queue-driven architecture powered by BullMQ and Redis, isolating market data ingestion, parallel signal computation, and alert distribution behind strict concurrency controls and circuit breakers.

┌────────────────────────────────────────────────────────────────────────────────────────┐
│                                DYNAMIC SCHEDULER                                       │
│  MongoDB (WatchlistItem) ──▶ dynamicScheduler.ts ──▶ BullMQ Repeatable Jobs (analyze-*)│
└────────────────────────────────────────┬───────────────────────────────────────────────┘
                                         │ Enqueues per-ticker tasks
                                         ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                              REDIS / BULLMQ QUEUE LAYER                                │
│                     Queue: 'ticker-analysis' (Concurrency: 3)                          │
│        [Job: analyze-AAPL]        [Job: analyze-NVDA]        [Job: analyze-MSFT]       │
└────────────────────────────────────────┬───────────────────────────────────────────────┘
                                         │ Worker processes job (Market-Hours Guarded)
                                         ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                             MARKET DATA INGESTION ENGINE                               │
│  FinnhubProvider ──▶ RateLimiter (Token-Bucket: 55 req/min, Serialized Mutex Lock)      │
│  Promise.all() Parallel Fetch: Quotes, Daily & 30m Candles, News, Earnings, Insider    │
└────────────────────────────────────────┬───────────────────────────────────────────────┘
                                         │ Raw Market & News Data
                    ┌────────────────────┴────────────────────┐
                    ▼                                         ▼
┌──────────────────────────────────────┐  ┌──────────────────────────────────────────────┐
│     TECHNICAL INDICATORS ENGINE      │  │          LLM SENTIMENT ANALYZER              │
│  • RSI (14) & Split-Window Divergence│  │  • Ollama (llama3.1) / Gemini / Groq / OpenAI│
│  • EMA 20 / 50 Crossover Detection   │  │  • Multi-Provider Circuit Breaker (3 fails)  │
│  • MACD (12, 26, 9) Histogram Trend  │  │  • Prompt Grounding: Strict Zod JSON Schema  │
│  • Volume Spike (>1.5x 20-day SMA)   │  │  • Materiality: High (1.4x), Med, Low (0.6x) │
│  • 52W High/Low & Rel. Strength SPY  │  │  • Graceful Fallback to Neutral Signal       │
└───────────────────┬──────────────────┘  └──────────────────────┬───────────────────────┘
                    │ TASignal                                   │ NewsSignal
                    └────────────────────┬───────────────────────┘
                                         ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                         SIGNAL BLENDING & SCORING (score.ts)                           │
│  • Composite Score (-1.0 to +1.0) = (TA × 0.55 + News × NewsWeight) / TotalWeight      │
│  • Multi-timeframe confirmation: Daily & 30m agree (×1.20 conf) / conflict (×0.80 conf) │
│  • Deterministic Rating: Strong Buy, Buy, Hold, Sell, Strong Sell                      │
│  • 48h Earnings Risk Override: Prepends warning reason & elevates news materiality     │
└────────────────────────────────────────┬───────────────────────────────────────────────┘
                                         ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                          DIFFING & DEDUPLICATION (diff.ts)                             │
│  Evaluates Current vs. Previous Snapshot (MongoDB):                                    │
│  • Rating Transitions (e.g., Hold ➔ Buy)                                               │
│  • Material News Announcements | Sentiment Swings (|Δ| > 0.35)                         │
│  • RSI Boundary Crossings (30 / 70) | Golden / Death EMA Crosses                       │
└────────────────────────────────────────┬───────────────────────────────────────────────┘
                                         │ Alert-worthy event detected
                                         ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                      ALERT LOGIC & IDEMPOTENCY GUARD (AlertLog)                        │
│  • Checks AlertLog: Rejects duplicate ratings within a 4-hour quiet window             │
│  • Verifies Confidence >= MIN_ALERT_CONFIDENCE threshold                               │
└───────────────────┬─────────────────────────────────────────┬──────────────────────────┘
                    │ Verified Alert                          │ Every Analysis Cycle
                    ▼                                         ▼
┌──────────────────────────────────────┐  ┌──────────────────────────────────────────────┐
│      TELEGRAM ALERT DISPATCHER       │  │        REAL-TIME STREAMING & STORAGE         │
│  • Telegram Bot API Webhook Dispatch │  │  • Server-Sent Events (SSE) Broadcast        │
│  • HTML-Formatted Payload:           │  │  • Persist Cycle Document (Snapshot Schema)  │
│    - Rating Emojis & Confidence %    │  │  • Automated Paper Trading & P&L Updates     │
│    - Human-Readable Evidence Bullets │  │  • Signal Accuracy Tracker (24h resolution)  │
│    - Dynamic Reason & Disclaimer     │  │  • Web Push (VAPID) User Notifications       │
└──────────────────────────────────────┘  └──────────────────────────────────────────────┘

Core Features & Capabilities

•Hybrid Quantitative & Qualitative Signal Scoring: Synthesizes 14-period RSI, 20/50 Exponential Moving Averages, MACD momentum, volume anomalies, 52-week price proximity, and relative strength vs. SPY with natural language sentiment scored by LLMs.
•Multi-Timeframe Convergence Validation: Compares daily trend signals with 30-minute intraday momentum. Symmetrical alignment scales confidence upwards by 20%, whereas timeframe conflict dampens confidence by 20%.
•Context-Aware RSI Divergence Detection: Applies a split-window lookback algorithm over 20 candles comparing price extrema to oscillator extrema, flagging momentum exhaustion and early reversal setups.
•Dynamic Watchlist Orchestration: Symbols can be injected, updated, or removed via REST APIs at runtime; BullMQ dynamic schedulers synchronize recurring jobs in Redis without application restarts.
•Calendar-Aware Risk Mitigation: Scans SEC and corporate earnings calendars to intercept upcoming releases within a 48-hour window, automatically prioritizing warnings in the output payload to prevent blind breakouts.
•Signal Tracking & Paper Trading: Automatically initiates paper trade records upon qualifying strong signals, tracking unrealized/realized P&L alongside an automated 24-hour signal accuracy resolver.
•Multi-Channel Real-Time Delivery: Dispatches HTML-formatted alerts to Telegram channels, pushes mobile notifications via Web Push (VAPID), and streams live snapshots to the React dashboard via Server-Sent Events (SSE).

Technical Challenges & Engineering Solutions

•Preventing API Rate-Limit Throttling on Free Market Tiers: Finnhub caps free API consumption at 60 requests/minute. To avoid burst-induced 429 errors across concurrent BullMQ workers, the application implements a custom serialized token-bucket rate limiter with a mutex lock chain. Ingestion calls are metered to a conservative 55 requests/minute, complemented by an exponential backoff retry mechanism that fails fast on 4xx client errors to conserve token quota.
•Thundering-Herd Mitigation & Per-Ticker Concurrency: When syncing dozens of watchlist assets at boot or schedule refresh, firing simultaneous API and LLM calls risked saturating system sockets and LLM provider quotas. The dynamic scheduler introduces deterministic 4-second staggered delays between boot jobs, while BullMQ limits active worker concurrency to 3.
•Grounded LLM Sentiment Extraction & Deterministic Parsing: Zero-shot LLM evaluations frequently produce inconsistent conversational text or malformed markdown fences. The sentiment pipeline injects a strict system prompt demanding compact JSON, executes temperature-zero completions, extracts JSON tokens using regular expression boundaries, and enforces schema conformance via Zod.
•LLM Multi-Provider Circuit Breaker & Auto-Failover: To prevent pipeline paralysis during LLM downtime or token rate exhaustion, the provider layer employs a stateful circuit breaker. If a provider (e.g., local Ollama, Gemini, Groq, or OpenAI) encounters 3 consecutive failures, the breaker trips, automatically falling back down a prioritized provider chain with an automatic 5-minute cooldown recovery probe. If all LLM calls fail, the system defaults to a neutral news signal rather than aborting the technical analysis cycle.
•Alert Fatigue Prevention via Stateful Diffing & Idempotency Windows: To avoid bombarding users with repetitive notifications when an indicator hovers around a boundary, the engine compares current signals against previous MongoDB snapshots. Alerts require an active rating transition, a major sentiment swing (|Δ| > 0.35), or an EMA/RSI threshold breach. Furthermore, an idempotency check against AlertLog enforces a 4-hour quiet period on identical rating signals.

Impact & Verification Status

•Test Suite Verification: Verified by a full suite of 29 unit tests across 5 test modules running on Vitest (executing in <500ms), covering scoring math, signal diffing, technical indicator accuracy, crypto key security, and concurrent token-bucket rate limiting without race conditions.
•Operational Efficiency: Successfully isolates compute-heavy operations inside background BullMQ workers, keeping the Express HTTP API lightweight and responsive with non-blocking SSE updates.
•Multi-Platform Deployment: Production-ready configuration supported by containerized Docker Compose services (MongoDB 7 and Redis) and PM2 cluster orchestration.

Stack

TypeScriptNode.jsBullMQRedisMongoDBMongooseExpresstechnicalindicatorsZodPinoOllama@google/generative-aiOpenAIFinnhub APITelegram Bot APIServer-Sent Events (SSE)Web Push (VAPID)VitestReactViteZustandTradingView Lightweight Charts