TDX API

repository·main·Indexed 20 days ago

https://github.com/oficcejo/tdx-api

A stock data query system based on the TongdaXing (TDX) protocol. It features a Go-based library for data acquisition, a RESTful API with 32 endpoints for retrieving market depth, K-line data, and transaction history, and a Web visualization interface using ECharts. The system supports A-shares from Shanghai, Shenzhen, and Beijing exchanges and can be deployed via Docker Compose or run from source using Go 1.22+.

Tokens
31.8K
Snippets
118
Records
148
Agent score
70%

What's inside tdx-api

  1. Overview of TDX Stock Data Query System

    main
    The TDX Stock Data Query System is a visualization platform based on TongdaXing (TDX) data sources. It provides real-time market quotes and historical data analysis for stocks in the Shanghai, Shenzhen, and Beijing stock exchanges, including A-shares, ETFs, and indices.
  2. How to interpret Five-Level Quotes (五档行情)

    main

    The Five-Level Quote view shows the top five price levels for both buyers and sellers.

    • Left Column: Level name (e.g., Bid 1, Ask 5).
    • Middle Column: Price (Red typically indicates Sell/Ask side, Green indicates Buy/Bid side).
    • Right Column: Order quantity (Note: 1 unit/手 = 100 shares).

    This view helps you understand market depth and liquidity.

    卖五  12.55  1000手 (Ask 5)
    卖四  12.54   800手 (Ask 4)
    ...
    买一  12.50   350手 (Bid 1)
  3. Available Stock Data Types

    main

    The system provides five main categories of data:

    1. Real-time Market Data: Includes five-level quotes (Bid/Ask 1-5), basic indicators (latest price, change amount, change percentage, volume, turnover, etc.), and daily data (open, high, low, previous close).
    2. K-Line Data (Historical Price Trends):
      • Minute levels: 1m, 5m, 15m, 30m, 60m.
      • Day levels: Daily, Weekly, Monthly, Quarterly, Yearly.
      • Content: Open, Close, High, Low, Volume, Turnover.
    3. Intraday (Minute) Data: Price and volume per minute during trading hours (09:30-11:30, 13:00-15:00).
    4. Intraday Transactions (Tick Data): Precise transaction details including time (to the second), price, volume, and nature (Active Buy vs. Active Sell).
    5. Stock Lists: Searchable lists of stocks across major Chinese exchanges.
  4. TDX API Base Information and Response Format

    main

    The TDX API provides stock data via HTTP GET requests. All responses follow a unified JSON structure.

    Base URL: http://your-server:8080
    Content-Type: application/json; charset=utf-8
    Encoding: UTF-8

    Standard Response Format: All endpoints return a JSON object with the following keys:

    • code: Integer. 0 indicates success, -1 indicates failure.
    • message: String. A status or error message.
    • data: Object/Array. The actual payload requested.
    {
      "code": 0,
      "message": "success",
      "data": {}
    }
  5. Convert TDX API data units to standard values

    main

    The API returns financial data in specific units that must be converted for standard use:

    Data TypeAPI Return ValueConversion FormulaExample
    PriceLi (厘)Price (Yuan) = Value / 100012500 $\rightarrow$ 12.50元
    VolumeHand (手)Volume (Shares) = Value * 1001235 $\rightarrow$ 123500股
    TurnoverLi (厘)Turnover (Yuan) = Value / 1000156000000 $\rightarrow$ 156000元
  6. Understand K-line Forward Adjustment (QFQ) behavior

    main

    The system uses Forward Adjustment (前复权) for specific K-line types to eliminate price gaps caused by dividends or stock splits. This ensures technical indicators (like moving averages) remain accurate and historical price continuity is maintained.

    Supported K-line Types

    • Forward Adjusted (Default): day (Daily), week (Weekly), and month (Monthly).
    • Unadjusted: All minute-level data (minute1, minute5, minute15, minute30) and hour K-lines remain unadjusted because intra-day price gaps due to ex-rights are not applicable.

    Data Source and Fallback

    • Primary Source: Data is fetched via the Tonghuashun (THS) API (extend.GetTHSDayKline).
    • Fallback Mechanism: If the THS API fails (due to network issues or invalid codes), the system automatically falls a fallback to standard unadjusted Tongdaqin data.
  7. Run TDX API from Source

    main

    If you prefer running from source, ensure you have Go 1.22+ installed.

    Steps to run:

    1. Download dependencies: go mod download.
    2. Navigate to the web directory.
    3. Run the server using go run ..

    ⚠️ Important: You must use go run . to compile all Go files in the directory. Do not use go run server.go, as it will fail to include necessary files.

    After running, access the system at http://localhost:8080.

    # 1. Download dependencies
    go mod download
    
    # 2. Enter web directory and run
    cd web
    go run .
  8. Install and run the Stock Data Query Web System from source

    main

    To run the web application locally, ensure you have Go 1.20 or higher installed and a stable network connection to access TongdaXing (TDX) servers. Follow these steps:

    1. Clone the repository to your local machine.
    2. Install dependencies using go mod tidy.
    3. Navigate to the web directory and start the server using go run server.go.
    4. Access the application at http://localhost:8080.
    # 1. Install dependencies
    go mod tidy
    
    # 2. Run the Web server
    cd web
    go run server.go
  9. One-click startup via Docker

    main

    To quickly start the TDX API service using Docker, use the provided scripts depending on your operating system.

    Windows: Double-click the docker-start.bat file.

    Linux/Mac: Run the docker-start.sh script after granting execution permissions.

    Once started, the service is accessible at http://localhost:8080 (local) or http://<YOUR_IP>:8080 (LAN).

    ### Windows
    ```powershell
    双击运行: docker-start.bat

    Linux/Mac

    chmod +x docker-start.sh
    ./docker-start.sh
  10. Secure the API with Authentication Middleware

    main

    To protect your API endpoints, implement an authentication middleware that checks for a specific token in the Authorization header. If the token is missing or incorrect, return an error response using errorResponse.

    func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
        return func(w http.ResponseWriter, r *http.Request) {
            token := r.Header.Get("Authorization")
            if token != "your-secret-token" {
                errorResponse(w, "未授权")
                return
            }
            next(w, r)
        }
    }
    
    // Usage
    http.HandleFunc("/api/quote", authMiddleware(handleGetQuote))
  11. Deploy TDX via Docker Compose (Recommended)

    main

    The easiest way to deploy the TDX stock data query system is using docker-compose. This method automatically builds the image, starts the container, and maps the service to port 8080 on your host machine.

    1. Navigate to the project directory.
    2. Run docker-compose up -d to build and start in detached mode.
    3. Verify success by checking logs for: 成功连接到通达信服务器 and 服务启动成功,访问 http://localhost:8080.
    4. Access the application at http://localhost:8080.
    # 1. Enter project directory
    cd C:\Users\Administrator\Downloads\tdx-master
    
    # 2. Build and start
    docker-compose up -d
    
    # 3. View logs to confirm success
    docker-compose logs -f