# fardu6288/trade_bot architecture

> Architecture diagram of the GitHub repository fardu6288/trade_bot, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-02-24). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/fardu6288/trade_bot
- Repository: https://github.com/fardu6288/trade_bot

## Overview

This is a **semi-automated trading system**:
- **Web UI (static HTML/JS)** used by a human to review signals and approve trades
- **FastAPI backend** that:
- fetches market data
- runs **indicator-based strategy** (SMA/EMA crossovers)
- validates risk constraints (balance + price bounds)
- places orders via **Zerodha KiteConnect API**
- “Semi-automated” (human-in-the-loop) is the core architectural constraint: **signals can be automatic, execution is gated by user approval**.

- the **approval gate**
- the **broker integration boundary**
- the **data-flow**: watchlist → data → indicators/strategy → signal → UI → validate → order

Use the repo structure to “explode” the system into accurate components:

##### Frontend (Browser)
**Files:** `frontend/index.html`, `frontend/script.js`, `frontend/style.css`
Role:
- Renders signal list / candidate buys
- Collects user inputs (qty, min/max buy price)
- Calls backend endpoints (likely REST over HTTP)

##### Backend API layer (FastAPI)
**Files:** `backend/main.py`, `backend/api.py`
Role:
- Defines HTTP endpoints for:
- login/session initiation/redirect (Zerodha auth)
- fetching balance
- fetching signals
- placing an order after user approval

##### Strategy / Indicators engine
**Files:** `backend/strategy.py`, `backend/indicators.py`, `backend/instruments.py`
Role:
- Strategy orchestration (SMA/EMA crossover selection)
- Indicator computations
- Instrument metadata / symbol mappings

##### Market data acquisition
**Files:** `backend/data_provider.py`
Role:
- Fetches historical/market data used by strategy computations
- Source is likely Zerodha endpoints (or a KiteConnect method)

##### Broker session & trading execution
**Files:** `backend/zerodha_session.py`, `backend/zerodha_trader.py`
Role:
- Auth/session lifecycle with Zerodha (token, login)
- Order placement + balance fetching
- **Session/Auth Manager**
- **Order Execution / Portfolio & Balance**

##### Configuration + watchlist
**Files:** `config/config.yaml`, `config/watchlist.json`, `backend/config_loader.py`, `.env`
Role:
- Watchlist is the input universe for scanning
- Config controls strategy params, limits, environment settings

##### Persistence / artifacts / logs (supporting components)
**Files:** `logs/app.log`, `logs/trades.log`, `models/trading_model.pkl`, `models/scaler.pkl`
Role:
- Logs: observability + audit trail (especially trades.log)
- **Logging / Audit Trail**
- **Model Artifacts (Optional)**

##### External system
**External:** **Zerodha Kite API** (plus “Live Market & Orders” behind it)

##### Safety/controls (must be visible)
- An explicit **“Human Approval Gate”** between **Signal Generation** and **Order Execution**.
- Available balance validation
- Min/max buy price validation

##### Architectural patterns / principles to call out
- **Layered architecture**: UI → API → domain (strategy) → integration (broker).
- **Human-in-the-loop control**: order placement is not triggered by strategy; it is triggered by a user action.
- **Integration boundary**: Zerodha is an external dependency; isolate it behind `zerodha_session.py` and `zerodha_trader.py`.
- **Configuration-driven scanning**: watchlist/config define what is scanned and how.

- User (Trader)
- Browser Frontend
- FastAPI Backend
- Zerodha Kite API (External)
- User ↔ Browser
- Browser ↔ FastAPI (HTTP)
- FastAPI ↔ Zerodha (KiteConnect)
- FastAPI → Logs

- API Routes (`api.py`)
- Strategy Engine (`strategy.py`)
- Indicators (`indicators.py`)
- Data Provider (`data_provider.py`)
- Zerodha Session (`zerodha_session.py`)
- Zerodha Trader (`zerodha_trader.py`)
- Config Loader (`config_loader.py`)
- Logging (writes to `logs/`)
Externalized stores:
- Config files (`config.yaml`, `watchlist.json`, `.env`)
- Model artifacts (`models/*.pkl`) as optional dependency if referenced

Exact gating:
- UI requests signals
- backend fetches data → computes indicators → returns signals
- user approves trade
- backend validates constraints
- backend places order
- backend logs trade

##### What to label explicitly (to avoid ambiguity)
- **Protocols**: “HTTP (REST)” between Browser and FastAPI
- **External SDK**: “KiteConnect SDK / Zerodha API”
- **Artifacts**: “watchlist.json”, “config.yaml”, “.env”
- **Outputs**: “BUY signals”, “Order request”, “Order status”
- **Constraints**: “Manual approval required”, “Balance check”, “Min/Max price validation”

##### “As-many-components-as-possible” decomposition (practical checklist)
When drawing, separate at least into:
- Frontend UI
- FastAPI app + routing
- Signal generation pipeline:
- watchlist loading
- market data retrieval
- indicator calculation
- strategy decision
- Trade approval + inputs
- Validation (balance + price bounds)
- Order execution
- Session/auth management
- Logging/audit
- External broker API

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% Diagram A — Context (C4 L1)
  %% =========================
  subgraph DIAG_A["Diagram A — Context (C4 L1)"]
    direction TB

    U["Trader (Human)"]:::external

    subgraph A_FE_BOUND["Frontend (Browser Boundary)"]
      direction TB
      FE["Browser UI (Static HTML/JS)"]:::frontend
      FE_JS["UI Logic (JS)"]:::frontend
      FE_CSS["UI Styling (CSS)"]:::frontend
      FE --> FE_JS
      FE --> FE_CSS
    end

    subgraph A_BE_BOUND["Backend (Service Boundary)"]
      direction TB
      BE["FastAPI Backend (Service)"]:::backend
    end

    Z_A["Zerodha KiteConnect (External)"]:::external
    LOGS_A[("Logs / Audit Trail")]:::store

    U -->|"reviews_signals"| FE
    FE -->|"HTTP (REST)"| BE
    BE -->|"KiteConnect SDK/API"| Z_A
    BE -.->|"writes"| LOGS_A
  end

  %% ==========================================
  %% Diagram B — Container/Component (C4 L2/3)
  %% ==========================================
  subgraph DIAG_B["Diagram B — Container/Component (C4 L2/3)"]
    direction TB

    subgraph B_FE["Frontend (Browser)"]
      direction TB
      BUI["Browser UI (Static HTML/JS)"]:::frontend
      BUI_JS["Browser UI (JS logic / API calls)"]:::frontend
      BUI_CSS["Browser UI (Styling)"]:::frontend
      BUI --> BUI_JS
      BUI --> BUI_CSS
    end

    subgraph B_BE["Backend (FastAPI)"]
      direction TB

      APP["FastAPI App (Uvicorn)"]:::backend
      API["API Routes / Controllers"]:::backend

      subgraph SIG_PIPE["Signal Generation Pipeline"]
        direction TB
        CFG["Config Loader"]:::backend
        INSTR["Instrument Universe"]:::backend
        DP["Market Data Provider"]:::backend
        IND["Indicators (SMA/EMA)"]:::backend
        STRAT["Strategy Engine"]:::backend
      end

      subgraph HITL["Human-in-the-Loop Controls"]
        direction TB
        GATE["Human Approval Gate"]:::control
        RISK["Risk Validation (Balance + Min/Max Price)"]:::control
      end

      subgraph BROKER["Broker Integration (Isolated Boundary)"]
        direction TB
        ZSESS["Zerodha Session/Auth Manager"]:::integration
        ZTRD["Zerodha Trader (Order + Balance)"]:::integration
      end

      AUD["Logging / Audit Trail"]:::backend

      APP --> API

      API -->|"load_config"| CFG
      CFG -.->|"reads"| CFGSTORE
      CFG -.->|"reads"| WLIST
      CFG -.->|"reads"| ENV

      API -->|"signals_request"| STRAT
      STRAT -->|"loads_symbols"| INSTR
      STRAT -->|"fetches_market_data"| DP
      DP -->|"get_historical/quotes"| ZSESS
      ZSESS -->|"KiteConnect SDK/API"| ZEXT

      STRAT -->|"compute"| IND
      IND -->|"indicator_values"| STRAT
      STRAT -->|"BUY_signals"| API
      API -->|"HTTP response: signals"| BUI_JS

      BUI_JS -->|"order_request (qty,min,max)"| API
      API -->|"manual_approval_required"| GATE
      GATE -->|"approved_trade"| RISK
      RISK -->|"check_balance"| ZTRD
      ZTRD -->|"KiteConnect SDK/API"| ZEXT
      RISK -->|"bounds_ok"| ZTRD
      ZTRD -->|"place_order"| ZEXT
      ZTRD -->|"order_status"| API
      API -->|"HTTP response: status"| BUI_JS

      API -.->|"writes"| AUD
      AUD -.->|"append"| APPLOG
      AUD -.->|"append"| TRDLOG

      STRAT -.->|"optional_load"| MODELS
    end

    %% External + Stores
    ZEXT["Zerodha KiteConnect (External)"]:::external

    CFGSTORE[("config.yaml")]:::store
    WLIST[("watchlist.json")]:::store
    ENV[(".env")]:::store

    APPLOG[("app.log")]:::store
    TRDLOG[("trades.log")]:::store

    MODELS[("Model Artifacts (Optional)")]:::store
    M1[("trading_model.pkl")]:::store
    M2[("scaler.pkl")]:::store
    MODELS --> M1
    MODELS --> M2

    %% Frontend -> Backend edge (explicit protocol)
    BUI_JS -->|"HTTP (REST)"| API
  end

  %% =========================
  %% Diagram C — Sequence (Gate) as Flow
  %% =========================
  subgraph DIAG_C["Diagram C — Sequence (Gate)"]
    direction TB

    S1["1. Trader opens UI / reviews"]:::external
    S2["2. UI requests signals (GET /signals)"]:::frontend
    S3["3. API loads watchlist + config"]:::backend
    S4["4. Strategy computes signals"]:::backend
    S5["5. Data provider fetches market data (via session/auth)"]:::backend
    S6["6. Indicators compute SMA/EMA"]:::backend
    S7["7. API returns BUY signals to UI"]:::frontend
    S8["8. Trader approves trade + sets qty + min/max"]:::external
    S9["9. UI places order request (POST /order)"]:::frontend
    S10["10. Risk validation: balance + bounds"]:::control
    S11["11. Place order via Zerodha trader"]:::integration
    S12["12. Return order status + write audit logs"]:::backend

    S1 --> S2 --> S3 --> S4 --> S5 --> S6 --> S7 --> S8 --> S9 --> S10 --> S11 --> S12

    %% Tie sequence steps to system components (for traceability)
    S2 -.-> FE
    S2 -.-> BUI_JS
    S3 -.-> API
    S3 -.-> CFG
    S4 -.-> STRAT
    S5 -.-> DP
    S5 -.-> ZSESS
    S6 -.-> IND
    S7 -.-> API
    S7 -.-> BUI_JS
    S9 -.-> API
    S10 -.-> RISK
    S11 -.-> ZTRD
    S11 -.-> ZEXT
    S12 -.-> AUD
    S12 -.-> APPLOG
    S12 -.-> TRDLOG
  end

  %% Click events (Frontend)
  click FE "https://github.com/fardu6288/trade_bot/blob/main/frontend/index.html"
  click FE_JS "https://github.com/fardu6288/trade_bot/blob/main/frontend/script.js"
  click FE_CSS "https://github.com/fardu6288/trade_bot/blob/main/frontend/style.css"
  click BUI "https://github.com/fardu6288/trade_bot/blob/main/frontend/index.html"
  click BUI_JS "https://github.com/fardu6288/trade_bot/blob/main/frontend/script.js"
  click BUI_CSS "https://github.com/fardu6288/trade_bot/blob/main/frontend/style.css"

  %% Click events (Backend entry)
  click BE "https://github.com/fardu6288/trade_bot/blob/main/backend/main.py"
  click APP "https://github.com/fardu6288/trade_bot/blob/main/backend/main.py"
  click API "https://github.com/fardu6288/trade_bot/blob/main/backend/api.py"
  click STRAT "https://github.com/fardu6288/trade_bot/blob/main/backend/strategy.py"
  click IND "https://github.com/fardu6288/trade_bot/blob/main/backend/indicators.py"
  click INSTR "https://github.com/fardu6288/trade_bot/blob/main/backend/instruments.py"
  click DP "https://github.com/fardu6288/trade_bot/blob/main/backend/data_provider.py"
  click ZSESS "https://github.com/fardu6288/trade_bot/blob/main/backend/zerodha_session.py"
  click ZTRD "https://github.com/fardu6288/trade_bot/blob/main/backend/zerodha_trader.py"
  click CFG "https://github.com/fardu6288/trade_bot/blob/main/backend/config_loader.py"

  %% Click events (Stores)
  click CFGSTORE "https://github.com/fardu6288/trade_bot/blob/main/config/config.yaml"
  click WLIST "https://github.com/fardu6288/trade_bot/blob/main/config/watchlist.json"
  click ENV "https://github.com/fardu6288/trade_bot/blob/main/.env"
  click APPLOG "https://github.com/fardu6288/trade_bot/blob/main/logs/app.log"
  click TRDLOG "https://github.com/fardu6288/trade_bot/blob/main/logs/trades.log"
  click M1 "https://github.com/fardu6288/trade_bot/blob/main/models/trading_model.pkl"
  click M2 "https://github.com/fardu6288/trade_bot/blob/main/models/scaler.pkl"

  %% Styles
  classDef frontend fill:#cfe8ff,stroke:#1b6fbf,stroke-width:2px,color:#0b2b45;
  classDef backend fill:#d6f5e3,stroke:#1f7a4d,stroke-width:2px,color:#0c2a1a;
  classDef integration fill:#d7f0ff,stroke:#146b9a,stroke-width:2px,color:#06324a;
  classDef external fill:#e6e6e6,stroke:#666,stroke-width:2px,color:#111;
  classDef store fill:#ffe9a8,stroke:#b38400,stroke-width:2px,color:#3a2a00;
  classDef control fill:#fff,stroke:#c1121f,stroke-width:3px,color:#3a0a0d;
```
