# shreesha345/binance-trading-bot architecture

> Architecture diagram of the GitHub repository shreesha345/binance-trading-bot, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-07-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/shreesha345/binance-trading-bot
- Repository: https://github.com/shreesha345/binance-trading-bot

## Overview

##### Project type and purpose
- This is an automated trading system for Binance Futures, written in Python.
- It consists of two main runtime services:
a) The **Trading Engine** (main.py + utils + api/) that connects to Binance REST & WebSocket, implements the Heikin Ashi strategy, manages orders, state, persistence, and exposes a small HTTP API.
b) The **Telegram Bot Service** (telegram_bot/) that handles user commands, subscription payments via Razorpay, and proxies requests to the trading engine.
- Supporting artifacts include configuration, data storage, logging, and Docker deployment.

##### File structure
Top-level:
- `.env`, `pyproject.toml`, `Dockerfile.backend`, `docker-compose.yml`: Deployment and environment.
- `main.py`: Entry point for the trading engine service.
- `api/` (routes.py, trading_config.json): HTTP routes for status, manual controls, and configuration.
- `utils/`: Core trading logic (HA calculation, order management, WebSocket client, quantity calculation, logging, etc.).
- `data/`: Persistent JSON stores (`order_book.json`, init scripts).
- `telegram_bot/`: Standalone service with its own Dockerfile. Contains bot logic, Razorpay integration, and server calls.
- `logs/`: Centralized logs for API, WebSocket, and errors.

##### Extract architectural insights from the README
- The bot opens a WebSocket connection to Binance for live kline data.
- Each new candle triggers strategy logic: place/cancel/update orders via Binance REST API.
- Order and state tracking in memory + JSON persist.
- Environment variables drive mode (test vs live), API keys, offsets, quantity settings.
- docker-compose can orchestrate both services and shared volumes (for data, logs).

##### Main components & interactions
a. External Systems
- **Binance**
- WebSocket Endpoint (stream OHLC data)
- REST API (order placement, cancelation, account/balance queries)
- **Telegram Users** via Telegram servers
- **Razorpay** (external payment gateway)
b. Internal Services
1. **Trading Engine Service** (Dockerfile.backend)
- WebSocket Client (utils/websocket_client) listens to Binance kline data
- Strategy & Order Manager (utils/strategy, buy_sell_handler, pnl_analyzer)
- HTTP API (api/routes.py) for status, manual overrides, config exposure
- Persistence Layer (data/order_book.json, utils/order_storage)
- Logging (utils/logger → logs/)
2. **Telegram Bot Service** (Dockerfile.telegram)
- Bot Interface (telegram_bot/bot.py) registers commands
- Server Call Module (telegram_bot/server_call.py) talks to Trading Engine API
- Payment Module (telegram_bot/razerpay.py + payments.json, payment_cycle.json, etc.)
- Customer Data Store (telegram_bot/customer_details.json)
c. Shared Infrastructure
- **Environment Configuration** (.env) mounted into both containers
- **Docker Compose** (docker-compose.yml) for multi-container orchestration
- **Volume Mounts** for logs/ and data/

##### Architectural patterns & principles
- **Separation of Concerns**: Trading logic vs user interface vs payment logic.
- **Event-Driven**: WebSocket events trigger strategy execution.
- **Stateful Order Management**: Finite state machine tracks position states in memory + persisted JSON.
- **Configuration-Driven**: trading behavior from JSON (api/trading_config.json) + ENV vars.
- **Resilience**: Auto-reconnect logic for WebSocket; error logging; tick-size validation.

##### Final checklist
- Internal services (containers)
- Data stores (JSON volumes)
- External APIs (Binance, Razorpay, Telegram)
- Call out architectural patterns: event-driven WebSocket, stateful FSM, config-driven behavior

## Diagram (Mermaid)

```mermaid
flowchart TB
    %% External Systems
    BinanceWS["Binance WebSocket"]:::external
    BinanceREST["Binance REST API"]:::external
    TelegramCloud["Telegram Cloud"]:::external
    RazorpayAPI["Razorpay API"]:::external

    %% Trading Engine Service
    subgraph "Trading Engine Service"
        TE_Docker["Dockerfile.backend"]:::internal
        TE_Main["main.py"]:::internal

        subgraph "WebSocket Client"
            WS_Listener["ws_listener.py"]:::internal
            Ohlc["ohlc_collector.py"]:::internal
            HA["heikin_ashi.py"]:::internal
            HA_utils["ha_utils.py"]:::internal
            StrategyClient["strategy.py"]:::internal
            Display["display.py"]:::internal
            Clear["clear_screen.py"]:::internal
        end

        subgraph "Strategy & Order Management"
            BuySell["buy_sell_handler.py"]:::internal
            PnL["pnl_analyzer.py"]:::internal
            OrderUtils["order_utils.py"]:::internal
            Hist["historical_handler.py"]:::internal
        end

        subgraph "Persistence Layer"
            OrderStore["order_storage.py"]:::internal
            StorageUtils["order_storage_utils.py"]:::internal
            InitStorage["init_order_storage.py"]:::internal
            OrderBook["order_book.json"]:::datastore
        end

        subgraph "HTTP API"
            Routes["routes.py"]:::internal
            ConfigJSON["trading_config.json"]:::datastore
        end

        ConfigModule["config.py"]:::internal
        Env[".env"]:::external
        Logger["logger.py"]:::internal
        LogsAPI["api.log"]:::datastore
        LogsWS["websocket.log"]:::datastore
        LogsErr["errors.log"]:::datastore
    end

    %% Telegram Bot Service
    subgraph "Telegram Bot Service"
        BotDocker["Dockerfile.telegram"]:::internal
        Bot["bot.py"]:::internal
        ServerCall["server_call.py"]:::internal
        RazarPayP["razerpay.py"]:::internal
        CustStore["customer_details.json"]:::datastore
        PaymentsConf["payments.json"]:::datastore
        PaymentCycle["payment_cycle.json"]:::datastore
    end

    %% Shared Infrastructure
    subgraph "Shared Infrastructure"
        Compose["docker-compose.yml"]:::internal
        DataVol["data/"]:::datastore
        LogsVol["logs/"]:::datastore
        EnvVol[".env"]:::external
    end

    %% Interactions
    BinanceWS -->|"kline stream (WSS)"| WS_Listener
    WS_Listener --> Ohlc
    Ohlc --> HA
    HA --> HA_utils
    HA_utils --> StrategyClient
    StrategyClient --> BuySell
    BuySell --> OrderUtils
    OrderUtils --> PnL
    OrderUtils --> Hist
    BuySell -->|"REST: POST /order"| BinanceREST

    StrategyClient --> OrderStore
    OrderStore --> StorageUtils
    StorageUtils --> OrderBook

    TE_Main --> WS_Listener
    TE_Main --> Routes
    TE_Main --> Logger

    Routes --> ConfigJSON
    ConfigModule --> TE_Main
    Env --> TE_Main

    Logger --> LogsAPI
    Logger --> LogsWS
    Logger --> LogsErr

    Bot --> ServerCall
    ServerCall --> Routes
    Bot --> RazorpayAPI
    Bot --> RazarPayP
    RazarPayP --> PaymentsConf
    RazarPayP --> PaymentCycle
    RazarPayP --> CustStore
    TelegramCloud --> Bot

    Compose --> TE_Docker
    Compose --> BotDocker
    Compose --> EnvVol
    Compose --> DataVol
    Compose --> LogsVol

    %% Click Events
    click TE_Docker "https://github.com/shreesha345/binance-trading-bot/blob/main/Dockerfile.backend"
    click TE_Main "https://github.com/shreesha345/binance-trading-bot/blob/main/main.py"
    click WS_Listener "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/ws_listener.py"
    click Ohlc "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/ohlc_collector.py"
    click HA "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/heikin_ashi.py"
    click HA_utils "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/ha_utils.py"
    click StrategyClient "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/strategy.py"
    click Display "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/display.py"
    click Clear "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/websocket_client/clear_screen.py"
    click BuySell "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/buy_sell_handler.py"
    click PnL "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/pnl_analyzer.py"
    click OrderUtils "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/order_utils.py"
    click Hist "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/historical_handler.py"
    click OrderStore "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/order_storage.py"
    click StorageUtils "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/order_storage_utils.py"
    click InitStorage "https://github.com/shreesha345/binance-trading-bot/blob/main/data/init_order_storage.py"
    click OrderBook "https://github.com/shreesha345/binance-trading-bot/blob/main/data/order_book.json"
    click Routes "https://github.com/shreesha345/binance-trading-bot/blob/main/api/routes.py"
    click ConfigJSON "https://github.com/shreesha345/binance-trading-bot/blob/main/api/trading_config.json"
    click ConfigModule "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/config.py"
    click Env "https://github.com/shreesha345/binance-trading-bot/blob/main/ .env"
    click Logger "https://github.com/shreesha345/binance-trading-bot/blob/main/utils/logger.py"
    click LogsAPI "https://github.com/shreesha345/binance-trading-bot/blob/main/logs/api.log"
    click LogsWS "https://github.com/shreesha345/binance-trading-bot/blob/main/logs/websocket.log"
    click LogsErr "https://github.com/shreesha345/binance-trading-bot/blob/main/logs/errors.log"
    click Bot "https://github.com/shreesha345/binance-trading-bot/blob/main/telegram_bot/bot.py"
    click ServerCall "https://github.com/shreesha345/binance-trading-bot/blob/main/telegram_bot/server_call.py"
    click RazarPayP "https://github.com/shreesha345/binance-trading-bot/blob/main/telegram_bot/razerpay.py"
    click BotDocker "https://github.com/shreesha345/binance-trading-bot/blob/main/telegram_bot/Dockerfile.telegram"
    click Compose "https://github.com/shreesha345/binance-trading-bot/blob/main/docker-compose.yml"

    %% Styles
    classDef internal fill:#cce5ff,stroke:#333,stroke-width:1px
    classDef external fill:#d4edda,stroke:#333,stroke-width:1px
    classDef datastore fill:#fff3cd,stroke:#333,stroke-width:1px
```
