---
name: Stocky Terminal
type: ai-agents-reference
description: AI agent capabilities, functions, automation systems, and daily market brief pipeline for the Stocky Terminal global market intelligence platform.
url: https://terminal.stockyai.xyz
blog: https://terminal.stockyai.xyz/blog
repository: https://github.com/SirCharan/stocky-terminal
endpoints:
  - POST /api/ai/summarize
  - POST /api/ai/insight
  - GET /api/ai/signals
  - POST /api/ai/batch-insights
  - GET /api/market/quotes
  - GET /api/market/commodities
  - GET /api/market/forex
  - GET /api/market/gift-nifty
  - GET /api/crypto/prices
  - GET /api/rss-proxy
  - GET /api/x-feed/proxy
  - GET /api/news/aggregated
  - GET /api/data/acled
  - GET /api/data/eia
  - GET /api/data/fred
  - GET /api/data/gdacs
  - GET /api/data/firms
  - GET /api/data/cloudflare-outages
  - GET /api/blog
  - GET /api/blog/:slug
  - GET /api/rate
  - POST /api/feedback
  - GET /api/sitemap
  - GET /api/cron/daily-brief-v2
  - GET /api/cron/generate-insights
  - POST /api/push/subscribe
  - POST /api/push/send
  - GET /api/cron/validate-signals
  - GET /api/cron/aggregate-signals
  - GET /api/market/options
  - GET /api/auth/zerodha-callback
  - GET /api/docs
  - GET /api/docs/:slug
---

# Stocky Terminal — AI Agents & Automation

## Overview

Stocky Terminal uses **Groq AI** (Llama 3.3 70B Versatile) as its primary intelligence engine, with chain-of-thought prompting, live market price injection, and Nifty-aware signal coherence filtering. All AI calls route through edge functions with JSON mode enforcement and error recovery. The platform runs automated cron jobs for daily market brief generation, pre-cached AI insight refresh, and 2-hour signal validation against live prices. It is installable as a PWA with push notifications and offline support.

**Live**: [terminal.stockyai.xyz](https://terminal.stockyai.xyz)
**Blog**: [terminal.stockyai.xyz/blog](https://terminal.stockyai.xyz/blog)

---

## AI Functions

All AI functions are defined in `src/services/summarization.ts`. Responses are parsed with `stripMarkdownFences()` for robustness.

### 1. `summarizeHeadlines(headlines: string[])`
- **Purpose**: Generate a 3-4 sentence market brief from top news headlines
- **Input**: Up to 15 headline strings
- **Output**: Concise market analysis with global equity and commodity impact
- **Trigger**: Called by `DataLoader.loadNews()` when news items > 5
- **Panel**: InsightsPanel

### 2. `generateTradeSignal(headline: string)`
- **Purpose**: Assess market impact of a single headline and return structured trade signal
- **Input**: One news headline
- **Output**: JSON with impact (high/medium/low), direction (bullish/bearish/neutral), affectedAssets, expectedMove, rationale, confidence (0-100)
- **Trigger**: Called for top 3 geopolitical/commodity/macro headlines
- **Panel**: HighImpactSignalsPanel

### 3. `generateFEDImpact(title: string, type: string)`
- **Purpose**: Assess Federal Reserve event impact on global and emerging markets
- **Input**: FED event title and type (rate-decision, minutes, speech, data-release)
- **Output**: 2-3 sentence analysis covering FII flows, currencies, commodities
- **Trigger**: Called by `DataLoader.loadUSEvents()` for new FED events

### 4. `summarizeXPosts(posts: string[])`
- **Purpose**: Generate sentiment summary from X/Twitter posts
- **Input**: Up to 10 post text strings
- **Output**: 2-3 sentence sentiment analysis
- **Trigger**: Called by `DataLoader.loadXFeed()` when posts > 3
- **Panel**: XFeedPanel (AI Sentiment section)

### 5. `generateSymbolAnalysis(symbol: string, price: number, changePercent: number)`
- **Purpose**: Generate analysis for a specific stock/commodity/crypto symbol
- **Input**: Symbol name, current price, percentage change
- **Output**: 3-4 sentence analysis with support/resistance levels and outlook
- **Trigger**: Called when user clicks a market row to open ChartDetailModal
- **Panel**: ChartDetailModal (AI Analysis section)

### 6. `summarizeSearchResults(query: string, results: Array)`
- **Purpose**: Summarize search results in market context
- **Input**: User search query + matched result titles/categories
- **Output**: 2-3 sentence impact summary
- **Trigger**: Called by CommandPalette after search completes
- **Panel**: CommandPalette (AI Summary section)

---

## AI Infrastructure

### Edge Function: `api/ai/summarize.ts`

Single endpoint handling all AI requests:

```
POST /api/ai/summarize
Body: { prompt: string, model?: string }
Response: { summary: string }
```

**Features**:
- JSON response format (`response_format: { type: 'json_object' }`)
- Markdown fence stripping for robust JSON parsing
- 30-second abort timeout
- CORS-enabled for cross-origin access

**Provider chain**:
1. **Groq API** (primary) — `GROQ_API_KEY` env var, model: `llama-3.3-70b-versatile` (chain-of-thought, 1024 max tokens)
2. **Ollama** (fallback) — `OLLAMA_URL` env var (default: `localhost:11434`)
3. **Graceful degradation** — Returns empty string on failure, UI shows error state

### Signal Validation: `api/cron/validate-signals.ts`
- Runs every 2 hours
- Reads `ai:signals:latest` from Redis, fetches live prices via `/api/market/quotes`
- Contradiction >0.5%: bullish + market down or bearish + market up
- Strong move >1.5%: flip direction, reduce confidence by 15
- Weak contradiction 0.5-1.5%: remove signal
- Preserves original `updatedAt` timestamp

---

## Blog & Daily Brief Automation

### Cron Schedule
- **Morning brief**: `30 2 * * 1-5` UTC = 8:00 AM IST, Mon-Fri
- **Evening brief**: `30 14 * * 1-5` UTC = 8:00 PM IST, Mon-Fri

### Pipeline: `api/cron/daily-brief-v2.ts`
1. **Fetch market data**: Nifty 50, Sensex, Bank Nifty, 8 sector indices, Gift Nifty, 8 global indices, 5 commodities, 5 forex pairs, 5 cryptos
2. **Fetch news**: Top headlines from aggregated news endpoint
3. **AI analysis**: Groq generates market outlook, key movers, trade signals
4. **Render HTML**: Server-rendered blog post with charts, tables, collapsible sections
5. **Store in Redis**: `blog:post:{slug}` (full HTML), indexed in `blog:posts` sorted set
6. **Send emails**: Resend API to 70+ subscribers with personalized footers

### Email System: `api/_lib/email.ts`
- Strips collapsible `<details>` sections and nav from email HTML
- Appends personalized footer: blog link, WhatsApp community link, 1-10 rating buttons
- Batched at 2 emails/second (Resend free tier rate limit)
- Subscriber list: `api/_lib/subscribers.ts`

### Rating System: `api/rate.ts`
- GET `/api/rate?slug=...&score=...&email=...`
- Stores per-subscriber rating in Redis with 90-day TTL
- Aggregated in Redis sorted set `blog:ratings:{slug}`
- Returns styled "Thank you" HTML page

---

## Pre-Cached AI Insights

### Cron: `api/cron/generate-insights.ts`
- Runs every 15 minutes (`*/15 * * * *`)
- Fetches high-severity headlines from `/api/news/aggregated`
- Generates batch AI insights via Groq
- Caches results in Redis
- Served via `/api/ai/signals` and `/api/ai/insight`

### Cron: `api/cron/aggregate-signals.ts`
- Runs every hour (`30 * * * *`)
- Re-aggregates cached AI insights into top-5 signals
- Time-weighted sentiment scoring (12h lookback, exponential decay)
- Correlation-aware amplification (21 asset pairs)
- Nifty coherence filtering
- Does NOT call the LLM — uses pre-cached insights from generate-insights cron

---

## Options Chain

### Endpoint: `api/market/options.ts`
- `GET /api/market/options?underlying=NIFTY&expiry=2026-03-27`
- Fetches live options chain from Dhan API
- Supported underlyings: NIFTY, BANKNIFTY, SENSEX, FINNIFTY, MIDCPNIFTY
- Returns: full Greeks, OI, IV, PCR, ATM strike, max pain

---

## Zerodha Kite Connect

### Integration: `api/_lib/zerodha.ts`
- Live NSE/BSE market prices via Zerodha broker API
- OAuth flow via `api/auth/zerodha-callback.ts`
- Automated daily token refresh via GitHub Actions (`.github/workflows/zerodha-token-refresh.yml`)
- Tokens expire daily at 6 AM IST — refresh script runs automatically

---

## News Intelligence Pipeline

### Service: `src/services/rss.ts`

Processes 30+ RSS feeds through a multi-stage pipeline:

1. **Fetch** — Parallel fetch of all configured feeds via RSS proxy
2. **Parse** — XML → `NewsItem` with title, link, source, date, description
3. **Classify** — Category assignment (india-market, commodity, macro, geopolitical, etc.)
4. **Filter** — Keyword-based relevance scoring (keep/reject regex patterns)
5. **Score** — Severity classification: critical, high, medium, low
6. **Detect** — Affected asset identification (16 regex patterns → asset arrays)
7. **Sort** — Date descending, then by source credibility tier
8. **Deduplicate** — Two-phase: exact prefix matching + Jaccard similarity (>0.6)

### Source Credibility Tiers

| Tier | Sources | Badge |
|------|---------|-------|
| T1 (Wire) | Reuters, Bloomberg, AP | Green "WIRE" |
| T2 (Major) | CNBC, ET, BBC, Moneycontrol, MarketWatch | — |
| T3 (Specialty) | OilPrice, Kitco, DefenseOne, Mining.com | — |
| T4 (Regional) | TASS, Business Today, Indian Express | — |

---

## Notification System

### Service: `src/services/notifications.ts`

Web Audio API-based alert system with browser notification support.

**3-Tier Audio Alerts** (oscillator-generated, no audio files):
| Tier | Sound | Duration | Use Case |
|------|-------|----------|----------|
| Critical | Alarm (saw wave, 880Hz→440Hz) | 1.5s | Active conflicts, rate decisions |
| High | Double beep (square wave, 660Hz) | 0.6s | FED events, sanctions, earthquakes M5+ |
| Medium | Single ping (sine wave, 440Hz) | 0.3s | Commodity moves, weather events |

---

## Event Store

### Service: `src/services/event-store.ts`

IndexedDB-based persistent storage for all ingested events.

**Capabilities**:
- Store up to 1000 events (auto-evicts oldest)
- Query by date range, severity, category, country
- Full-text search on title and description

---

## Search Intelligence

### Service: `src/services/search-index.ts`

Fuzzy search across all terminal data, triggered by Cmd/Ctrl+K.

**Indexed sources**: News items, market data, GeoEvents, map actions
**Algorithm**: Custom fuzzy matching with scoring based on exact substring matches, character-by-character matching, and category boosting.

---

## Machine-Readable Files

| File | Format | Purpose |
|------|--------|---------|
| `metadata.json` | JSON (Schema.org) | Structured project metadata |
| `llm.md` | Markdown + YAML | LLM-optimized reference |
| `llms.txt` | Plaintext | Summary for LLM crawlers |
| `llms-full.txt` | Plaintext | Full documentation for LLM crawlers |
| `agents.txt` | Plaintext | AI crawler-friendly capabilities list |
| `.well-known/ai-plugin.json` | JSON | OpenAI plugin discovery manifest |
| `robots.txt` | Standard | Crawler directives |
| `sitemap.xml` | XML | URL index (dynamic, includes blog posts) |

## Crawlable Paths

| Path | Content |
|------|---------|
| `/` | Main terminal application |
| `/docs` | Documentation index |
| `/docs/*` | Individual documentation pages |
| `/blog` | Blog listing (daily market briefs) |
| `/blog/*` | Individual market brief posts |
| `/llms.txt` | LLM summary documentation |
| `/llms-full.txt` | Full LLM documentation |
| `/llm.md` | Structured LLM reference |
| `/agents.md` | AI agents documentation (markdown) |
| `/agents.txt` | AI agents documentation (plaintext) |
| `/metadata.json` | Schema.org structured metadata |
| `/.well-known/ai-plugin.json` | OpenAI plugin manifest |
| `/sitemap.xml` | XML sitemap |
| `/robots.txt` | Crawler directives |
