TDX API
repository·main·Indexed 20 days ago
https://github.com/oficcejo/tdx-apiA 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+.
What's inside tdx-api
- 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.
How to interpret Five-Level Quotes (五档行情)
mainThe 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)Available Stock Data Types
mainThe system provides five main categories of data:
- 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).
- 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.
- Intraday (Minute) Data: Price and volume per minute during trading hours (09:30-11:30, 13:00-15:00).
- Intraday Transactions (Tick Data): Precise transaction details including time (to the second), price, volume, and nature (Active Buy vs. Active Sell).
- Stock Lists: Searchable lists of stocks across major Chinese exchanges.
TDX API Base Information and Response Format
mainThe 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-8Standard Response Format: All endpoints return a JSON object with the following keys:
code: Integer.0indicates success,-1indicates failure.message: String. A status or error message.data: Object/Array. The actual payload requested.
{ "code": 0, "message": "success", "data": {} }Convert TDX API data units to standard values
mainThe API returns financial data in specific units that must be converted for standard use:
Data Type API Return Value Conversion Formula Example Price Li (厘) Price (Yuan) = Value / 100012500$\rightarrow$12.50元Volume Hand (手) Volume (Shares) = Value * 1001235$\rightarrow$123500股Turnover Li (厘) Turnover (Yuan) = Value / 1000156000000$\rightarrow$156000元Understand K-line Forward Adjustment (QFQ) behavior
mainThe 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), andmonth(Monthly). - Unadjusted: All minute-level data (
minute1,minute5,minute15,minute30) andhourK-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.
- Forward Adjusted (Default):
Configure Go Proxy for Faster Downloads
mainIf you encounter connection timeouts while downloading Go modules (e.g.,
dial tcp: i/o timeout), configure the Go proxy to use a domestic mirror (recommended for users in China):go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,directRun TDX API from Source
mainIf you prefer running from source, ensure you have Go 1.22+ installed.
Steps to run:
- Download dependencies:
go mod download. - Navigate to the
webdirectory. - Run the server using
go run ..
⚠️ Important: You must use
go run .to compile all Go files in the directory. Do not usego 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 .- Download dependencies:
Install and run the Stock Data Query Web System from source
mainTo 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:
- Clone the repository to your local machine.
- Install dependencies using
go mod tidy. - Navigate to the
webdirectory and start the server usinggo run server.go. - Access the application at
http://localhost:8080.
# 1. Install dependencies go mod tidy # 2. Run the Web server cd web go run server.goOne-click startup via Docker
mainTo quickly start the TDX API service using Docker, use the provided scripts depending on your operating system.
Windows: Double-click the
docker-start.batfile.Linux/Mac: Run the
docker-start.shscript after granting execution permissions.Once started, the service is accessible at
http://localhost:8080(local) orhttp://<YOUR_IP>:8080(LAN).### Windows ```powershell 双击运行: docker-start.batLinux/Mac
chmod +x docker-start.sh ./docker-start.shSecure the API with Authentication Middleware
mainTo protect your API endpoints, implement an authentication middleware that checks for a specific token in the
Authorizationheader. If the token is missing or incorrect, return an error response usingerrorResponse.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))Deploy TDX via Docker Compose (Recommended)
mainThe 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.- Navigate to the project directory.
- Run
docker-compose up -dto build and start in detached mode. - Verify success by checking logs for:
成功连接到通达信服务器and服务启动成功,访问 http://localhost:8080. - 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