Skip to content

Plan Phase 1

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

Hereโ€™s the revised technical blueprint with all planned APIs, including the new Supabase chat storage module, while maintaining the original structureโ€™s rigor:


๐ŸŽฏ Bullseye AI Trading Chatbot - Technical Blueprint (v2)

1. System Architecture Overview

1.1 Enhanced Component Diagram

flowchart TD
    A[User Query] --> B[Query Analysis]
    B --> C[Data Assembly]
    C --> D[Insights Generation]
    D --> E[Tagged Response]
    E --> F[UI Rendering]
    E --> G[Encrypted Chat Storage - New]
    
    subgraph Backend
        B -->|Groq| H[Initial Intent Analysis]
        C --> I[Market Data]
        C --> J[Portfolio]
        C --> K[Risk Engine]
        D -->|Groq| L[Contextual Insights]
        G -->|Supabase| M[Chat History DB - New]
    end

Loading

2. Complete API Component Matrix

2.1 Core API Endpoints

Component API Path Method Key Parameters Output Tags
Query Analyzer /api/query POST query: string components[], tags[]
Data Assembler /api/assemble POST {components[], tags[]} Raw component responses
Insights Generator /api/insights POST {query, raw_responses[]} Enhanced tagged response
Market Data /api/market-data GET symbols[], fields[] /price, /depth, /vwap
Portfolio /api/portfolio GET `segment=equity futures`
Stock Screener /api/stock-screener POST {filters: {pe_max: 20}} /screener-result
Technical Analysis /api/technical-analysis GET symbol, interval, study /candlestick, /macd
Fundamental Analysis /api/fundamental-analysis GET symbol, data_type=ratios /pe-ratio, /roe
Risk Metrics /api/risk-metrics GET timeframe, model=historical /var, /max-drawdown
Tax Engine /api/tax-engine POST {trades[], fy=2024} /stcg, /ltcg
Chat Storage ๐Ÿ†• /api/chat-storage POST {session_id, messages[]} stored_at (timestamp)

2.2 Support Services

Service Location Purpose
Kite Client /lib/clients/kite.ts Zerodha API wrapper with OAuth 2.0
Supabase Client ๐Ÿ†• /lib/clients/supabase.ts Encrypted chat history storage (AES-256)
Groq Client /lib/clients/groq.ts Optimized LLM query handler
Crypto Utils ๐Ÿ†• /lib/utils/crypto.ts Handles message encryption/decryption

3. Updated API Tree Structure

app/
โ”œโ”€โ”€ api/
โ”‚   โ”œโ”€โ”€ query/route.ts                 # Initial intent analysis
โ”‚   โ”œโ”€โ”€ assemble/route.ts              # Data orchestration
โ”‚   โ”œโ”€โ”€ insights/route.ts              # Post-analysis
โ”‚   โ”œโ”€โ”€ components/
โ”‚   โ”‚   โ”œโ”€โ”€ market-data/route.ts       # Real-time prices/depth
โ”‚   โ”‚   โ”œโ”€โ”€ portfolio/route.ts         # Holdings/positions
โ”‚   โ”‚   โ”œโ”€โ”€ stock-screener/route.ts    # Watchlist/filters  
โ”‚   โ”‚   โ”œโ”€โ”€ technical-analysis/route.ts # Charts/indicators
โ”‚   โ”‚   โ”œโ”€โ”€ fundamental-analysis/route.ts # Financials
โ”‚   โ”‚   โ”œโ”€โ”€ risk-metrics/route.ts      # VaR/Sharpe
โ”‚   โ”‚   โ”œโ”€โ”€ tax-engine/route.ts        # Capital gains
โ”‚   โ”‚   โ””โ”€โ”€ chat-storage/route.ts ๐Ÿ†•   # Encrypted chat history
โ”‚   โ””โ”€โ”€ lib/
โ”‚       โ”œโ”€โ”€ clients/
โ”‚       โ”‚   โ”œโ”€โ”€ kite.ts
โ”‚       โ”‚   โ”œโ”€โ”€ groq.ts
โ”‚       โ”‚   โ””โ”€โ”€ supabase.ts ๐Ÿ†•
โ”‚       โ””โ”€โ”€ utils/
โ”‚           โ”œโ”€โ”€ crypto.ts ๐Ÿ†•           # Encryption helpers
โ”‚           โ”œโ”€โ”€ tags.ts
โ”‚           โ””โ”€โ”€ formatters.ts
โ””โ”€โ”€ components/
    โ””โ”€โ”€ chat/
        โ”œโ”€โ”€ Chat.tsx
        โ””โ”€โ”€ widgets/
            โ”œโ”€โ”€ PriceTile.tsx
            โ”œโ”€โ”€ RiskGauge.tsx
            โ””โ”€โ”€ TextBubble.tsx

4. Chat Storage API Specification ๐Ÿ†•

4.1 Database Schema (Supabase)

CREATE TABLE encrypted_chat_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id TEXT NOT NULL,
    encrypted_payload TEXT NOT NULL, -- AES-256 encrypted
    iv TEXT NOT NULL, -- Initialization vector
    user_id TEXT REFERENCES auth.users(id),
    created_at TIMESTAMPTZ DEFAULT NOW()
);

4.2 API Details

Endpoint /api/chat-storage
Method POST
Input ```json
{
"session_id": "uuid",
"messages": [
{
  "query": "original text",
  "response": "encrypted tags",
  "timestamp": "ISO8601"
}

] }

| **Encryption**        | AES-256 with client-side key derivation     |
| **Rate Limit**        | 10 requests/minute per user                |

### 4.3 Flow
```mermaid
sequenceDiagram
    participant UI
    participant API
    participant Supabase
    
    UI->>API: POST /chat-storage (encrypted)
    API->>Supabase: Store {iv, encrypted_payload}
    Supabase-->>API: 201 Created
    API-->>UI: {success: true}

5. Updated Implementation Roadmap

5.1 Phase 1: Core Infrastructure (Week 1-2)

  1. Zerodha Integration

    • WebSocket setup for live prices
    • Session management
  2. Supabase Foundation ๐Ÿ†•

    • Table configuration
    • Client-side encryption setup

5.2 Phase 2: Component Rollout (Week 3-5)

Component Key Features Dependencies
Market Data Real-time tick streaming Kite WebSocket
Stock Screener Custom filter builder Yahoo Finance API
Chat Storage ๐Ÿ†• E2E encrypted history Supabase + Crypto utils

5.3 Phase 3: Optimization (Week 6)

  • Chat Storage: Implement message compression before encryption
  • Data Sync: Conflict resolution for offline scenarios
  • Retention Policies: Auto-purge old chats after 90 days

6. Security Additions ๐Ÿ†•

6.1 Encryption Protocol

// /lib/utils/crypto.ts
export function encryptChatMessage(
  text: string,
  secretKey: string
): { iv: string; encryptedData: string } {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cbc', 
    Buffer.from(secretKey), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return {
    iv: iv.toString('hex'),
    encryptedData: encrypted.toString('hex')
  };
}

6.2 Access Controls

Resource Permission Policy
Chat History Read/Write User ID match + JWT validation
Encryption Keys Client-side only Never stored server-side

๐Ÿ“š 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