Skip to content

Architecture

Durva Dongre edited this page Jun 4, 2025 · 1 revision

🏗️ Architecture.md – BullsEye Phase 1

Welcome to the BullsEye Phase 1 architecture guide. This document outlines the system design, component architecture, API contracts, data flow, and implementation details for the 5 key components that power BullsEye’s research, portfolio, and analytics interface for Zerodha Kite users.


📦 System Overview

BullsEye is a modular, chat-based analytics platform for retail investors and traders. Users ask natural language queries, which are parsed, resolved, and served via a pipeline of semantic and API layers.


User Query ➝ Query Analyzer ➝ Data Assembler ➝ Insights Generator ➝ Chat UI

Each of the 5 main components (market data, portfolio, screener, technicals, fundamentals) are self-contained, fetch and transform data, and return a typed response to be rendered by widgets.


🧠 Core Modules

1. api/query/ – Query Analyzer

  • Input: User query (natural language)
  • Output: components[], tags[]
  • Purpose: Detects which services to call and what data to retrieve.
  • Example: "Show me IV for NIFTY 45000 CE"components: ['market-data'], tags: ['IV', 'options', 'NIFTY']

2. api/assemble/ – Data Orchestrator

  • Input: { components[], tags[] }
  • Output: Raw API responses
  • Purpose: Coordinates API calls to relevant components with resolved tags/params.

3. api/insights/ – Post-processing Engine

  • Input: { query, raw_responses[] }
  • Output: Enhanced interpretation, summaries, conclusions
  • Purpose: Applies heuristics or GPT reasoning to convert raw numbers into insights.

🧩 Component APIs

✅ 1. Market Data Component

Route: /api/components/market-data
Methods: GET

Key Parameters:

  • symbols[]: e.g., ["RELIANCE", "BANKNIFTY"]
  • fields[]: e.g., ["LTP", "IV", "VWAP", "Depth"]

Computed Metrics:

  • LTP, % Change, Net Change
  • Implied Volatility (Options)
  • Beta
  • VWAP, OHLC, Pivot Points
  • Order Depth (Top 5 Bids/Asks)
  • Volume Shock, 52W High/Low
  • Sector Heatmaps

Example Query:

"Is there buy pressure on RELIANCE?"


✅ 2. Portfolio & Positions Component

Route: /api/components/portfolio
Methods: GET

Key Parameters:

  • segment: "equity" | "futures"
  • user_id/session_id: tied to auth token

Computed Metrics:

  • Holdings: Quantity, LTP, Average Cost, P&L
  • Realized / Unrealized Gain
  • Sharpe Ratio, Max Drawdown
  • Margin (SPAN, Exposure)
  • Asset Allocation (Equity vs Debt vs F&O)
  • Order History with Slippage

Example Query:

"Estimate my short-term capital gains today."


✅ 3. Stock Screener Component

Route: /api/components/stock-screener
Methods: POST

Payload:

{
  "filters": {
    "pe_max": 20,
    "peg_max": 1,
    "macd_cross": true,
    "delivery_pct_min": 70
  }
}

Supported Filters:

  • Valuation: P/E, EV/EBITDA, PEG
  • Momentum: MACD, RSI, Moving Avg
  • Volume: Delivery %, Volume Spike
  • Quality: Piotroski Score, FCF Yield
  • Prebuilt Screens: “Oversold + High Delivery”

Example Query:

"Show smallcaps with PEG < 1 and bullish MACD crossover"


✅ 4. Technical Analysis Component

Route: /api/components/technical-analysis Methods: GET

Key Parameters:

  • symbol: "RELIANCE"
  • interval: "5m", "1h", "1d"
  • study: "MACD", "RSI", "Supertrend"

Computed Metrics:

  • Chart Types: Candlestick, Heikin Ashi, Renko
  • Indicators: RSI, MACD, Bollinger Bands, etc.
  • Custom Indicator Scripts (via sandbox)
  • Correlation Matrix
  • Event Annotations (earnings, splits)

Example Query:

"Plot Supertrend on NIFTY for 15-min intervals"


✅ 5. Fundamental Analysis Component

Route: /api/components/fundamental-analysis Methods: GET

Key Parameters:

  • symbol: "TCS"
  • data_type: "ratios" | "balance-sheet" | "dividends"

Computed Metrics:

  • Financial Ratios: P/E, ROE, ROCE, FCF Yield
  • Profitability: EBITDA Margin, Net Margin, EPS Growth
  • Cash Flow: Cash Conversion Cycle, Working Capital
  • Ownership: Shareholding Pattern, Insider Trades, Pledges
  • Dividends: Payout history, Yield vs Sector

Example Query:

"Show FCF yield and ROCE trend for TCS (5Y)"


🗂️ Directory Structure

app/
├── api/
│   ├── query/                  # Query classification
│   ├── assemble/               # Async parallel data fetch
│   ├── insights/               # Final reasoning + GPT
│   └── components/
│       ├── market-data/
│       ├── portfolio/
│       ├── stock-screener/
│       ├── technical-analysis/
│       └── fundamental-analysis/
├── lib/
│   ├── clients/                # kite.ts, supabase.ts
│   └── utils/                  # tags.ts, crypto.ts
└── components/
    └── chat/
        ├── Chat.tsx
        └── widgets/            # UI Tiles e.g., PriceTile, RiskGauge

📡 Data Flow

[User Query] → /api/query → Detect `market-data`, `fundamental-analysis`
                  ↓
           /api/assemble → Fetch data from all required APIs in parallel
                  ↓
           /api/insights → Add explanation: "Buyers dominating order book"
                  ↓
               Chat.tsx → Render Tiles: LTP, IV, Beta, Summary

🔐 Security Notes

  • All sensitive operations (portfolio, tax) require auth headers.
  • Supabase stores chat history (AES-256 encrypted).
  • API keys are stored encrypted and only decrypted per-session.
  • Mock APIs available for local dev/testing.

🧪 Testing

  • ✅ Unit tests using Jest for each component API
  • ✅ End-to-end tests for /assemble and /insights routes
  • ✅ Mock response snapshots for screener and charts

⏭️ Next Phases

  • Phase 2: Options Strategy Builder
  • Phase 3: Portfolio Rebalancer + Alerts
  • Phase 4: Real-Time NLP Copilot

📚 Navigation

  • 📋 Research
    What we're actually going to build vs what we dream about
  • 🗺️ Roadmap
    Our master plan (subject to reality checks)
  • 🧩 Components
    The building blocks that hopefully work together
  • 📡 API Guide
    Interfaces to every modular service, from market data to tax
  • 💰 Funding
    How we keep the lights on (and the servers running)
  • 🏗️ Architecture
    The technical deep dive for masochists
  • Todo List
    What’s pending, what’s burning, and who’s guilty
  • 🤝 Contributing
    Join the chaos, we have cookies*

*Cookies not guaranteed

Clone this wiki locally