# shinnytech/tqsdk-python architecture

> Architecture diagram of the GitHub repository shinnytech/tqsdk-python, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-03-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/shinnytech/tqsdk-python
- Repository: https://github.com/shinnytech/tqsdk-python

## Overview

##### Project Type and Purpose
- This project is a specialized trading strategy development package. It is designed to be the core engine that enables users to subscribe to market data, execute algorithmic trading strategies (both in simulation/backtesting and real trades), manage risk, calculate technical indicators, and provide a web-based GUI for visualization and debugging.
- The README emphasizes the core components: connecting to行情网关 (Market Data Gateway) and交易中继网关 (Trade Gateway) via the Diff协议 and providing robust backtesting, simulation, and real trading functionalities.

##### File Structure
- The top-level structure includes documentation (doc/), standard configuration files (setup.py, requirements.txt, etc.), and the main package directory “tqsdk”.
- API Initialization and Utility Files: files like tqsdk/api.py, tqsdk/connect.py, tqsdk/baseApi.py, and tqsdk/utils.py encapsulate the main API interactions.
- Market & Trade Components: files such as tqsdk/account.py, tqsdk/backtest.py with its submodules, tqsdk/sim/ and tqsdk/trade_extension.py implement functionalities for backtesting, simulation, account management, and actual trades.
- Algorithm and Demo Modules: the “algorithm” subdirectory and “demo” subdirectories (e.g., tqsdk/demo/*) contain example strategy implementations and algorithmic trading examples.
- Risk Management and Position Handling: files such as tqsdk/risk_manager.py, tqsdk/risk_rule.py, and TargetPosTask utility (encapsulated within the library) support risk control and target positioning.
- Web and GUI Components: the “tqsdk/web” folder provides web assets (HTML, CSS, JavaScript) for the integrated graphical interface.
- Integration with External Gateways: although the gateways themselves (Open Md Gateway / Open Trade Gateway) are separate projects, TqSdk’s core connectivity (via tqsdk/connect.py, tqsdk/channel.py) is clearly designed to conform to the Diff协议.

##### Extract and Emphasize README Insights
- The two gates: Open Md Gateway for market data and Open Trade Gateway for trading.
- Diff协议 as the integration layer between TqSdk and the gateways.
- A demonstration snippet that shows how the user’s strategy code instantiates the API, subscribes to quotes, and uses the TargetPosTask to adjust positions.
- This reinforces that the main architectonic design involves a central API engine that seamlessly interacts with external services and offers multiple modes (real trading, simulation, backtesting).

a. Main Components:
- User Strategy Application: The client that uses the library (i.e., developer-written strategy code using TqSdk).
- TqSdk Core Engine: This includes modules for the API, connection handling, and the in-memory data management.
- Diff协议 Layer: Abstract layer ensuring communication with external gateways.
- Market Data & Order Management: Modules handling market data (tqsdk/api, tqsdk/channel) and executing orders.
- Backtesting & Simulation: Separate submodules for replaying historical data (tqsdk/backtest) and simulating trades (tqsdk/sim, tqsdk/tradeable/sim).
- Risk & Trade Management: Modules like risk_manager.py, risk_rule.py, and TargetPosTask within lib/ to enforce risk control and manage positions.
- Technical Analysis: The algorithm and TA functions (tqsdk/algorithm, tqsdk/ta, tqsdk/tafunc) for technical indicator computations.
- Demo & Examples: Represent the sample strategies that illustrate usage.
- Web GUI: Stand-alone or integrated component showing interactive visual representation (found in tqsdk/web).

b. Relationships and Interactions:
- That the User Strategy Application interacts with the TqSdk Core Engine via a well-defined API. This API internally orchestrates the flow of data between:
- The Diff协议 Layer and external gateways: Market Data Gateway (Open Md Gateway) and Trade Gateway (Open Trade Gateway).
- The in-memory database holding real-time market data and order status.
- The backtesting/simulation modules, which can work with historical data and simulate execution.
- External components (Market and Trade Gateways) towards the Diff协议 Module.
- The Diff协议 Module into the Core Engine.
- The Core Engine (especially order and risk management) back out to external trade systems for real trading.
- User code calling into API functions that drive trading decisions.

c. Architectural Patterns and Design Principles:
- Separation of Concerns: Clearly separate components that handle market data retrieval, order execution, risk management, and simulation/backtesting.
- Modularity: Each module (e.g., backtest, sim, algorithm) is self-contained, supporting extensibility.
- Abstraction via the Diff协议 layer: Encapsulates communication to varying external gateways.

d. Technologies and Libraries:
- Python 3.7+ forms the base environment.
- Support for pandas and numpy is explicitly optimized within the system.
- Web assets that provide a GUI (using JavaScript/CSS/HTML from tqsdk/web).

##### Elements
- Clearly labeled nodes for each major component (e.g., “User Strategy Code”, “TqSdk API Engine”, “Diff协议 Adapter”, “Market Data Gateway”, “Trade Gateway”, “Backtesting Module”, “Risk Manager”, “Web GUI”).
- Data flow (market data, order execution signals, trading commands) from external systems to the API engine and back.
- Dependencies between modules (for instance, the User Strategy relies on API updates that are processed by the risk manager and order management modules).
- Differentiate between external systems (gateways), core engine modules, and user interface components.
- Annotations or callouts where needed (e.g., “Diff协议 layer facilitates uniform communication”, “In-memory database for high-speed data access”, “Risk rules enforced before order execution”).

##### Be Detailed but Organized
- The goal is to allow a principal software engineer to quickly grasp the architecture’s modularity, data flow, and integration boundaries.

## Diagram (Mermaid)

```mermaid
graph TD
    %% External Systems and User Application
    US["User Strategy Code"]:::external
    MG["Market Data Gateway"]:::external
    TG["Trade Gateway"]:::external

    %% TqSdk Core Engine Subgraph
    subgraph "TqSdk Core Engine"
        API["API Initialization & Utility"]:::utility
        DIF["Diff协议 Layer"]:::adapter
        MO["Market Data & Order Management"]:::order
        BT["Backtesting Module"]:::simulation
        SIM["Simulation Module"]:::simulation
        RM["Risk Management & Target Positioning"]:::risk
        TA["Technical Analysis & Algorithm"]:::tech
        DM["Demo & Examples"]:::demo
        WG["Web GUI"]:::gui
    end

    %% Connections from User Strategy Code to Core Engine
    US -->|"calls"| API
    US -->|"triggers_demo"| DM

    %% Internal Core Engine Interactions
    API -->|"uses"| DIF
    API -->|"routes_to"| MO
    API -->|"invokes"| RM
    API -->|"starts"| BT
    API -->|"starts"| SIM
    API -->|"utilizes"| TA

    %% Data Flow Between Modules
    DIF -->|"integrates_with"| MG
    DIF -->|"integrates_with"| TG
    MO -->|"feeds"| RM
    RM -->|"executes_orders"| TG
    TA --> WG
    RM --> WG

    %% External Gateways pushing data into Diff协议 Layer
    MG -->|"market_data"| DIF
    TG -->|"trade_info"| DIF

    %% Styles
    classDef external fill:#FFCCCC,stroke:#AA3333,stroke-width:2px,color:#000000;
    classDef utility fill:#CCFFCC,stroke:#228B22,stroke-width:2px,color:#000000;
    classDef adapter fill:#CCCCFF,stroke:#3333AA,stroke-width:2px,color:#000000;
    classDef order fill:#FFFFCC,stroke:#CCCC00,stroke-width:2px,color:#000000;
    classDef simulation fill:#FFCC99,stroke:#FF6600,stroke-width:2px,color:#000000;
    classDef risk fill:#FF9999,stroke:#CC0000,stroke-width:2px,color:#000000;
    classDef tech fill:#CCFFFF,stroke:#008B8B,stroke-width:2px,color:#000000;
    classDef demo fill:#E6CCFF,stroke:#9932CC,stroke-width:2px,color:#000000;
    classDef gui fill:#CCE5FF,stroke:#0066CC,stroke-width:2px,color:#000000;

    %% Click Events for Component Mapping
    click API "https://github.com/shinnytech/tqsdk-python/blob/master/tqsdk/api.py"
    click DIF "https://github.com/shinnytech/tqsdk-python/blob/master/tqsdk/diff.py"
    click MO "https://github.com/shinnytech/tqsdk-python/blob/master/tqsdk/account.py"
    click BT "https://github.com/shinnytech/tqsdk-python/tree/master/tqsdk/backtest/"
    click SIM "https://github.com/shinnytech/tqsdk-python/tree/master/tqsdk/sim/"
    click RM "https://github.com/shinnytech/tqsdk-python/blob/master/tqsdk/risk_manager.py"
    click TA "https://github.com/shinnytech/tqsdk-python/blob/master/tqsdk/ta.py"
    click DM "https://github.com/shinnytech/tqsdk-python/tree/master/tqsdk/demo/"
    click WG "https://github.com/shinnytech/tqsdk-python/tree/master/tqsdk/web/"
```
