# Architectural Blueprint — NSE Deep Research Engine (v1)

## 1. Core Objective
A server-side research engine that scans NSE equities daily, applies fundamental + technical filters, generates AI-written research notes for shortlisted stocks, and delivers two actionable briefs via Telegram: a **BTST list at ~3:10 PM IST** and a **Swing watchlist post-market (~7:00 PM IST)**. Every recommendation and its eventual outcome is stored in PostgreSQL so hit-rate and performance are measurable from day one. Phase 2 adds a Next.js dashboard on the same database.

## 2. System Scope and Boundaries

### In Scope (Phase 1)
- NSE cash-market equities only (F&O universe + Nifty 500 as the scan universe)
- Daily EOD + intraday price/volume data via Angel One SmartAPI (existing credentials)
- Delivery percentage from NSE Bhavcopy (daily download)
- Fundamentals snapshot per stock: quarterly results trend, TTM PE, ROE, debt/equity, promoter holding (NSE/exchange-published data)
- BTST scanner (runs 3:00 PM IST, Mon–Fri, skips NSE holidays)
- Swing scanner (runs 6:30 PM IST after bhavcopy, Mon–Fri)
- Claude API research layer: structured research note per shortlisted stock (max 5 BTST, max 8 swing per day)
- Telegram delivery (existing bot token, dedicated chat/channel)
- Outcome tracker: next-day evaluation of BTST calls; SL/target tracking for swing calls
- Paper mode only — no order placement

### Out of Scope (Phase 1)
- Any order execution / broker integration for trading
- Web frontend (Phase 2)
- BSE-only listed stocks
- Intraday scalping signals
- Options/F&O strategies (existing separate bot handles that)
- User accounts / multi-tenancy

## 3. Core System Components

| Component | Single Responsibility |
|---|---|
| **DataIngestor** | Fetch and persist prices/volumes (Angel One), bhavcopy delivery %, corporate announcements, NSE holiday calendar |
| **FundamentalsStore** | Fetch, normalize, and persist quarterly financials and key ratios per symbol; refresh weekly + on results day |
| **BtstScanner** | At 3:00 PM, score the universe on closing-strength criteria and emit ≤5 candidates with entry/SL/target |
| **SwingScanner** | Post-market, apply fundamentals filter then technical trigger; emit ≤8 candidates with entry zone/SL/target/horizon |
| **ResearchWriter** | For each candidate, call Claude API (with web search) to produce a structured research note (thesis, key numbers, risks) |
| **TelegramPublisher** | Format and send the BTST brief and Swing brief to the configured chat |
| **OutcomeTracker** | Evaluate open calls daily (BTST: next-day result; Swing: SL/target/expiry) and persist outcomes + running hit-rate |
| **Scheduler** | Cron-driven orchestration of the above with NSE-holiday awareness and failure alerts to Telegram |

## 4. High-Level Data Flow

```mermaid
flowchart LR
  A[Angel One SmartAPI] --> DI[DataIngestor]
  B[NSE Bhavcopy / Announcements] --> DI
  DI --> DB[(PostgreSQL)]
  F[Exchange fundamentals] --> FS[FundamentalsStore] --> DB
  DB --> BS[BtstScanner]
  DB --> SS[SwingScanner]
  BS --> RW[ResearchWriter]
  SS --> RW
  RW -->|Claude API + web search| RW
  RW --> DB
  RW --> TP[TelegramPublisher] --> TG[Telegram chat]
  DB --> OT[OutcomeTracker] --> DB
  OT --> TP
```

## 5. Key Integration Points
- **DataIngestor ↔ Angel One SmartAPI**: REST + existing TOTP login flow (reuse credentials via env vars; do NOT hardcode)
- **DataIngestor ↔ NSE**: daily bhavcopy CSV download (sec_bhavdata_full), announcements JSON; respect rate limits, set browser-like headers
- **ResearchWriter ↔ Anthropic API**: `claude-sonnet-4-6`, web_search tool enabled, strict JSON output schema for notes
- **TelegramPublisher ↔ Telegram Bot API**: existing bot token, new chat ID via env
- **All components ↔ PostgreSQL**: via Prisma; single database `nse_research`, schema owned by this app only

## 6. Technology Stack (locked)
- **Runtime**: Node.js 20 LTS, TypeScript
- **Framework**: Fastify (API surface kept minimal in Phase 1: health + manual-trigger endpoints)
- **ORM**: Prisma + PostgreSQL 15 (existing server instance, new database)
- **Scheduling**: system cron calling CLI entrypoints (`npm run job:<name>`) — consistent with existing server patterns; each job logs to `logs/` and exits
- **AI**: Anthropic Messages API
- **Deployment**: `/root/nse-research` on AlmaLinux server, systemd service for the Fastify API only

## 7. Non-Functional Requirements
- BTST brief MUST reach Telegram by 3:12 PM IST (hard deadline — market closes 3:30)
- Any job failure MUST send a Telegram error alert within 1 minute of failure
- All external API credentials via `.env` only; `.env` git-ignored
- Every recommendation row immutable once published (corrections via new rows)
- Notification dedup: a job that re-runs MUST NOT re-send an already-published brief for the same date
