tdx

package module
v0.0.0-...-9264027 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2026 License: MIT Imports: 20 Imported by: 0

README

📈 通达信协议解析

Go Version
License


📚 参考资源


🛠 功能列表 & 完成情况

功能 状态
盘口(5档报价) ✅ 已完成
代码数量 ✅ 已完成
代码列表 ✅ 已完成
分时图 ✅ 已完成
历史分时图 ✅ 已完成
分时成交 ✅ 已完成
历史分时成交 ✅ 已完成
K线 ✅ 已完成
历史K线 ✅ 已完成
股本变迁 ✅ 已完成
集合竞价 ✅ 已完成

🚀 快速开始

package main

import (
	"fmt"
	"github.com/injoyai/tdx"
)

func main() {
	// 连接服务器,开启日志,支持断线重连
	c, err := tdx.Dial("124.71.187.122:7709", tdx.WithDebug(), tdx.WithRedial())
	if err != nil {
		panic(err)
	}

	// 获取行情
	resp, err := c.GetQuote("sz000001", "sh600008")
	if err != nil {
		panic(err)
	}

	for _, v := range resp {
		fmt.Printf("%#v\n", v)
	}

	<-c.Done()
}

🌐 服务器列表 (端口 7709)

🏙 上海
IP 测试时间 运营商 结果
124.71.187.122 2026-01-26 华为 ✅️
122.51.120.217 2026-01-26 腾讯 ✅️
111.229.247.189 2026-01-26 腾讯 ✅️
124.70.176.52 2026-01-26 华为 ✅️
123.60.186.45 2026-01-26 华为 ✅️
122.51.232.182 2026-01-26 腾讯 ✅️
118.25.98.114 2026-01-26 腾讯 ✅️
124.70.199.56 2026-01-26 华为 ✅️
121.36.225.169 2026-01-26 华为 ✅️
123.60.70.228 2026-01-26 华为 ✅️
123.60.73.44 2026-01-26 华为 ✅️
124.70.133.119 2026-01-26 华为 ✅️
124.71.187.72 2026-01-26 华为 ✅️
123.60.84.66 2026-01-26 华为 ✅️
🏙 北京
IP 测试时间 运营商 结果
121.36.54.217 2026-01-26 华为
121.36.81.195 2026-01-26 华为
123.249.15.60 2026-01-26 华为
124.70.75.113 2026-01-26 华为
120.46.186.223 2026-01-26 华为
124.70.22.210 2026-01-26 华为
139.9.133.247 2026-01-26 华为
🏙 广州
IP 测试时间 运营商 结果
124.71.85.110 2026-01-26 华为 ✅️
139.9.51.18 2026-01-26 华为 ✅️
139.159.239.163 2026-01-26 华为 ✅️
124.71.9.153 2026-01-26 华为 ✅️
116.205.163.254 2026-01-26 华为 ✅️
116.205.171.132 2026-01-26 华为 ✅️
116.205.183.150 2026-01-26 华为 ✅️
111.230.186.52 2026-01-26 腾讯 ✅️
110.41.4.4 2026-01-26 华为 ✅️
110.41.2.72 2026-01-26 华为 ✅️
110.41.154.219 2026-01-26 华为 ✅️
110.41.147.114 2026-01-26 华为 ✅️
🏙 武汉
IP 测试时间 运营商 结果
119.97.185.59 2026-01-26 电信 ✅️

⚠️ 免责声明

  1. 本项目仅供 学习、研究和技术交流 使用,禁止用于任何商业或非法用途。
  2. 使用本项目产生的任何数据、损失或法律责任,作者 不承担任何责任
  3. 对第三方服务器或服务的访问,用户需自行遵守相关法律法规及服务协议。
  4. 请勿将本项目用于侵犯他人权益或违反监管规定的行为。

📄 许可证

MIT License - 详见 LICENSE

⭐ 喜欢这个项目吗?点个 Star 支持一下吧!

Documentation

Overview

Package tdx provides a minimal Go client for the TDX (通达信) 7709 market data protocol.

Quick Start

c, err := tdx.Dial("110.41.147.114:7709")
if err != nil { ... }
defer c.Close()

klines, err := c.GetKline("sh600000", "day", 10)
if err != nil { ... }
for _, k := range klines {
    fmt.Printf("%s O=%.3f H=%.3f L=%.3f C=%.3f V=%d\n",
        k.Time.Format("2006-01-02"), k.Open, k.High, k.Low, k.Close, k.Volume)
}

Index

Constants

View Source
const (
	BitmapPreClose       = 0x00
	BitmapOpen           = 0x01
	BitmapHigh           = 0x02
	BitmapLow            = 0x03
	BitmapClose          = 0x04
	BitmapVol            = 0x05
	BitmapVolRatio       = 0x06
	BitmapAmount         = 0x07
	BitmapInsideVol      = 0x08
	BitmapOutsideVol     = 0x09
	BitmapTotalShares    = 0x0a
	BitmapFloatShares    = 0x0b
	BitmapEPS            = 0x0c
	BitmapNetAssets      = 0x0d
	BitmapTotalMcapAB    = 0x0f
	BitmapPEDynamic      = 0x10
	BitmapBid            = 0x11
	BitmapAsk            = 0x12
	BitmapServerDate     = 0x13
	BitmapServerTime     = 0x14
	BitmapBidVol         = 0x18
	BitmapAskVol         = 0x19
	BitmapLastVol        = 0x1a
	BitmapTurnover       = 0x1b
	BitmapIndustry       = 0x1c
	BitmapDecimalPoint   = 0x1f
	BitmapBuyPriceLimit  = 0x20
	BitmapSellPriceLimit = 0x21
	BitmapLotSize        = 0x23
	BitmapSpeedPct       = 0x25
	BitmapAvgPrice       = 0x26
	BitmapKCBFlag        = 0x2b
	BitmapBJFlag         = 0x2c
	BitmapPETTM          = 0x30
	BitmapPEStatic       = 0x31
	BitmapChange20d      = 0x3b
	BitmapYtdPct         = 0x3c
	BitmapChange60d      = 0x44
	BitmapChange5d       = 0x45
	BitmapChange10d      = 0x46
	BitmapActivity       = 0x59
	BitmapConsecutiveUp  = 0x5c
)

Bitmap field bit positions.

View Source
const (
	ServiceIDPing  uint16 = 0x0000
	PingCMD        uint16 = 0x0015
	ServiceIDAuth  uint16 = 0x1894
	ServiceIDStage uint16 = 0x1899
	Stage2CMD      uint16 = 0x0FDB
)

Handshake protocol constants.

View Source
const (
	SPLoginCMD       uint16 = 0x2454
	FundBootstrapCMD uint16 = 0x23F0 // wire bytes: f0 23
	FundDetailCMD    uint16 = 0x2488 // wire bytes: 88 24
	FundKlineCMD     uint16 = 0x2489 // wire bytes: 89 24
)

SP mode constants.

View Source
const (
	Period1Minute  = "1m"
	Period5Minute  = "5m"
	Period15Minute = "15m"
	Period30Minute = "30m"
	Period60Minute = "60m"
	PeriodDay      = "day"
	PeriodWeek     = "week"
	PeriodMonth    = "month"
	PeriodQuarter  = "quarter"
	PeriodYear     = "year"
)

Period constants for GetKline.

View Source
const (
	KlinePeriod5Minute  uint16 = 0
	KlinePeriod15Minute uint16 = 1
	KlinePeriod30Minute uint16 = 2
	KlinePeriod60Minute uint16 = 3
	KlinePeriodDay      uint16 = 4
	KlinePeriodWeek     uint16 = 5
	KlinePeriodMonth    uint16 = 6
	KlinePeriod1Minute  uint16 = 7
	KlinePeriodMultiMin uint16 = 8
	KlinePeriodMultiDay uint16 = 9
	KlinePeriodQuarter  uint16 = 10
	KlinePeriodYear     uint16 = 11
)

Kline period constants (wire protocol values).

View Source
const (
	DirectFrameTypeCodeList     uint16 = 0x0450
	DirectFrameTypeKLineOffset  uint16 = 0x052D
	DirectFrameTypeTick         uint16 = 0x053E
	DirectFrameTypeTickChart    uint16 = 0x0537
	DirectFrameTypeTransaction  uint16 = 0x0FC5
	DirectFrameTypeHistoryTrade uint16 = 0x0FB5
	DirectFrameTypeXdXr         uint16 = 0x000F
	DirectFrameTypeFinance      uint16 = 0x0010
	DirectFrameTypeCompanyCat   uint16 = 0x02CF
	DirectFrameTypeCompanyCtn   uint16 = 0x02D0
	DirectFrameTypeTopBoard     uint16 = 0x053F
	DirectFrameTypeQuotesList   uint16 = 0x054B
	DirectFrameTypeBoardMembers uint16 = 0x122C
	DirectFrameTypeBatchQuote   uint16 = 0x054C
)

Direct frame type constants.

View Source
const (
	MarketShenzhen uint16 = 0
	MarketShanghai uint16 = 1
	MarketBeijing  uint16 = 2
)

Market constants.

View Source
const (
	SortCode          uint16 = 0x00  // 代码
	SortPrice         uint16 = 0x06  // 现价
	SortVolume        uint16 = 0x09  // 总量
	SortAmount        uint16 = 0x0A  // 总金额
	SortChangePct     uint16 = 0x0E  // 涨幅%
	SortAmplitudePct  uint16 = 0x0F  // 振幅%
	SortPEDynamic     uint16 = 0x11  // 市盈(动)
	SortEntrustRatio  uint16 = 0x12  // 委比%
	SortInOutRatio    uint16 = 0x15  // 内外比
	SortLockedRatio   uint16 = 0x1B  // 封成比
	SortLockedAmount  uint16 = 0x1C  // 封单额
	SortOpenAmount    uint16 = 0x1D  // 开盘金额
	SortVolRatio      uint16 = 0x23  // 量比
	SortTurnoverRate  uint16 = 0x24  // 换手率%
	SortFloatMcap     uint16 = 0x26  // 流通市值
	SortTotalMcapAB   uint16 = 0x27  // AB股总市值
	SortStrengthPct   uint16 = 0x2D  // 强弱度%
	SortSpeedPct      uint16 = 0x2E  // 涨速%
	SortActivity      uint16 = 0x2F  // 活跃度
	SortShortTurnover uint16 = 0xCC  // 短换手%
	SortVolSpeedPct   uint16 = 0xD0  // 量涨速%
	SortMainNetAmount uint16 = 0xD4  // 主力净额
	SortAmount2M      uint16 = 0x10C // 2分钟金额
)

QuotesList sort type constants.

View Source
const (
	FilterNew uint16 = 1 << 0 // 排除未开板次新股
	FilterKCB uint16 = 1 << 1 // 排除科创板
	FilterST  uint16 = 1 << 2 // 排除ST股
	FilterCYB uint16 = 1 << 3 // 排除创业板
	FilterBJ  uint16 = 1 << 4 // 排除北证A股
)

QuotesList filter type constants (exclude bitmask, OR to combine). Set bits to EXCLUDE those stock types from results.

View Source
const (
	CategorySH       uint16 = 0      // 上证A
	CategorySZ       uint16 = 2      // 深证A
	CategoryA        uint16 = 6      // A股
	CategoryB        uint16 = 7      // B股
	CategoryKCB      uint16 = 8      // 科创板
	CategoryBJ       uint16 = 12     // 北证A
	CategoryCYB      uint16 = 14     // 创业板
	CategoryHGT      uint16 = 0x2AF9 // 沪股通
	CategorySGT      uint16 = 0x2B01 // 深股通
	CategoryETF      uint16 = 0x2AFD // ETF基金
	CategoryLOF      uint16 = 0x2B04 // LOF基金
	CategoryZS       uint16 = 0x2B2C // 沪深系列指数
	CategoryBoardHY  uint16 = 10001  // 行业一级
	CategoryBoardHY2 uint16 = 10002  // 行业二级
	CategoryBoardGN  uint16 = 10004  // 概念
	CategoryBoardFG  uint16 = 10005  // 风格
	CategoryBoardDQ  uint16 = 10006  // 地区
)

QuotesList category constants.

View Source
const (
	SortNone uint16 = 0
	SortDesc uint16 = 1
	SortAsc  uint16 = 2
)

QuotesList sort order constants.

View Source
const (
	TopBoardSH  uint16 = 0  // 上证A股
	TopBoardSZ  uint16 = 2  // 深证A股
	TopBoardA   uint16 = 6  // 所有A股
	TopBoardB   uint16 = 7  // B股
	TopBoardKCB uint16 = 8  // 科创板
	TopBoardBJ  uint16 = 12 // 北证A股
	TopBoardCYB uint16 = 14 // 创业板
)

TopBoard category constants.

View Source
const (
	XdXrChuQuanChuXi         uint8 = 1  // 除权除息
	XdXrSongPeiGuShangShi    uint8 = 2  // 送配股上市
	XdXrFeiLiuTongGuShangShi uint8 = 3  // 非流通股上市
	XdXrGuBenBianDong        uint8 = 4  // 未知股本变动
	XdXrGuBenBianHua         uint8 = 5  // 股本变化
	XdXrZengFaXinGu          uint8 = 6  // 增发新股
	XdXrGuFenHuiGou          uint8 = 7  // 股份回购
	XdXrZengFaShangShi       uint8 = 8  // 增发新股上市
	XdXrZhuanPeiGuShangShi   uint8 = 9  // 转配股上市
	XdXrKeZhuanZhaiShangShi  uint8 = 10 // 可转债上市
	XdXrKuoSuoGu             uint8 = 11 // 扩缩股
	XdXrFeiLiuTongGuSuoGu    uint8 = 12 // 非流通股缩股
	XdXrSongRenGouQuanZheng  uint8 = 13 // 送认购权证
	XdXrSongRenGuQuanZheng   uint8 = 14 // 送认沽权证
)

XdXr event type constants.

Variables

View Source
var ErrNoReachableHosts = errors.New("no reachable hosts")

ErrNoReachableHosts indicates that every probed host failed.

View Source
var SPLoginBody = []byte{
	0xe5, 0xbb, 0x1c, 0x2f, 0xaf, 0xe5, 0x25, 0x94,
	0x1f, 0x32, 0xc6, 0xe5, 0xd5, 0x3d, 0xfb, 0x41,
	0x5b, 0x73, 0x4c, 0xc9, 0xcd, 0xbf, 0x0a, 0xc9,
	0x20, 0x21, 0xbf, 0xdd, 0x1e, 0xb0, 0x6d, 0x22,
	0xd0, 0x08, 0x88, 0x4c, 0x16, 0x11, 0xcb, 0x13,
	0x78, 0xf6, 0xab, 0xd8, 0x24, 0xd8, 0x99, 0xd2,
	0x1f, 0x32, 0xc6, 0xe5, 0xd5, 0x3d, 0xfb, 0x41,
	0x1f, 0x32, 0xc6, 0xe5, 0xd5, 0x3d, 0xfb, 0x41,
	0xa9, 0x32, 0x5a, 0xc9, 0x35, 0xdc, 0x08, 0x37,
	0x33, 0x5a, 0x16, 0xe4, 0xce, 0x17, 0xc1, 0xbb,
}

SPLoginBody is the encrypted login body for SP mode (80 bytes).

Functions

func BestExAddresses

func BestExAddresses(timeout time.Duration) []string

BestExAddresses returns reachable extension quote addresses sorted by latency.

func BestMainAddresses

func BestMainAddresses(timeout time.Duration) []string

BestMainAddresses returns reachable main addresses sorted by latency. Results are cached in-memory for 10 minutes.

func BestSPAddresses

func BestSPAddresses(timeout time.Duration) []string

BestSPAddresses returns reachable SP addresses sorted by latency. Results are cached in-memory for 10 minutes.

func BuildDirectFrame

func BuildDirectFrame(msgID uint32, control byte, frameType uint16, body []byte) []byte

BuildDirectFrame constructs a 12-byte header + body direct frame.

func BuildSPFrame

func BuildSPFrame(head byte, msgID uint16, body []byte) []byte

BuildSPFrame constructs an SP mode frame (head=0x01) used by mac_quotation protocols. Wire format: [head:1][customize:4][control:1][len:2][len:2][msg_id:2][body...]

func ConnectAuthRequest

func ConnectAuthRequest(seq uint16) []byte

ConnectAuthRequest builds the 13-byte connect-auth packet (0x1894/0x000D).

func DecodeCompanyContent

func DecodeCompanyContent(body []byte) (string, error)

DecodeCompanyContent decodes a 0x02D0 company content response body.

Layout: "<H6sHH" (12 bytes header), then content bytes (GBK encoded).

func Decompress

func Decompress(data []byte) ([]byte, error)

Decompress decompresses zlib data.

func ExAddresses

func ExAddresses() []string

ExAddresses returns the built-in extension quote host:port list.

func FormatAmount

func FormatAmount(f float64) string

FormatAmount formats an amount value with Chinese units (万/亿).

func FormatVolume

func FormatVolume(n int64) string

FormatVolume formats a volume value with Chinese units (万/亿).

func FundAddresses

func FundAddresses() []string

FundAddresses returns the built-in fund host:port list.

func FundBootstrapRequest

func FundBootstrapRequest(seq uint16) []byte

FundBootstrapRequest builds the 0x23F0 fund bootstrap packet using 0x01 framing.

func MainAddresses

func MainAddresses() []string

MainAddresses returns the built-in main quote host:port list.

func MarketString

func MarketString(m uint16) string

MarketString returns a short market label ("SH", "SZ", "BJ") for the given market code.

func PingRequest

func PingRequest(seq uint16) []byte

PingRequest builds the 12-byte ping/probe packet (0x0015).

func RequestBatchQuoteFrame

func RequestBatchQuoteFrame(msgID uint32, control byte, stocks []QuoteStock) ([]byte, error)

RequestBatchQuoteFrame builds a 0x054C batch quote request frame.

func RequestBoardMembersFrame

func RequestBoardMembersFrame(msgID uint32, control byte, boardCode uint32, sortType uint16, start uint32, pageSize uint8, sortOrder uint16, bitmap []byte) ([]byte, error)

RequestBoardMembersFrame builds a 0x122C board members request frame.

func RequestCodeListFrame

func RequestCodeListFrame(msgID uint32, control byte, market uint16, start uint16) ([]byte, error)

RequestCodeListFrame builds a 0x0450 code list request frame.

func RequestCompanyCategoryFrame

func RequestCompanyCategoryFrame(msgID uint32, control byte, market uint16, code string) ([]byte, error)

RequestCompanyCategoryFrame builds a 0x02CF company category request frame.

func RequestCompanyContentFrame

func RequestCompanyContentFrame(msgID uint32, control byte, market uint16, code string, filename string, start uint32, length uint32) ([]byte, error)

RequestCompanyContentFrame builds a 0x02D0 company content request frame.

func RequestFinanceFrame

func RequestFinanceFrame(msgID uint32, control byte, market uint16, code string) ([]byte, error)

RequestFinanceFrame builds a 0x0010 finance info request frame.

func RequestFundDetailFrame

func RequestFundDetailFrame(code string, mode uint16) ([]byte, error)

RequestFundDetailFrame builds a 0x2488 fund detail request frame.

func RequestFundKLineFrame

func RequestFundKLineFrame(code string, period uint16, times uint16, start uint32, count uint32) ([]byte, error)

RequestFundKLineFrame builds a 0x2489 fund kline request frame.

func RequestHistoryTradeFrame

func RequestHistoryTradeFrame(msgID uint32, control byte, date string, market uint16, code string, start uint16, count uint16) ([]byte, error)

RequestHistoryTradeFrame builds a 0x0FB5 history trade request frame.

func RequestKLineOffsetFrame

func RequestKLineOffsetFrame(msgID uint32, control byte, market uint16, code string, period uint16, times uint16, start uint16, count uint16) ([]byte, error)

RequestKLineOffsetFrame builds a 0x052D kline request frame.

func RequestQuotesListFrame

func RequestQuotesListFrame(msgID uint32, control byte, category uint16, sortType uint16, start uint16, count uint16, sortReverse uint16, filter uint16) ([]byte, error)

RequestQuotesListFrame builds a 0x054B quotes list request frame.

func RequestTickChartFrame

func RequestTickChartFrame(msgID uint32, control byte, market uint16, code string, start uint16, count uint16) ([]byte, error)

RequestTickChartFrame builds a 0x0537 tick chart request frame.

func RequestTickFrame

func RequestTickFrame(msgID uint32, control byte, stocks []QuoteStock) ([]byte, error)

RequestTickFrame builds a 0x053E tick request frame for one or more stocks.

func RequestTopBoardFrame

func RequestTopBoardFrame(msgID uint32, control byte, category uint16, size uint8) ([]byte, error)

RequestTopBoardFrame builds a 0x053F top board request frame.

func RequestTransactionFrame

func RequestTransactionFrame(msgID uint32, control byte, market uint16, code string, start uint16, count uint16) ([]byte, error)

RequestTransactionFrame builds a 0x0FC5 transaction request frame.

func RequestXdXrFrame

func RequestXdXrFrame(msgID uint32, control byte, market uint16, code string) ([]byte, error)

RequestXdXrFrame builds a 0x000F XDXR request frame.

func SPAddresses

func SPAddresses() []string

SPAddresses returns the built-in MAC/SP host:port list.

func SPLoginRequest

func SPLoginRequest(seq uint16) []byte

SPLoginRequest builds the SP mode login packet (0x2454) using head=0x01 framing.

func Stage2Request

func Stage2Request(seq uint16) []byte

Stage2Request builds the stage2 session-init packet (0x1899/0x0FDB).

func XdXrCategoryString

func XdXrCategoryString(cat uint8) string

XdXrCategoryString returns a Chinese description for an XDXR category code.

Types

type BatchQuote

type BatchQuote struct {
	Market        uint16
	Code          string
	Active        uint16
	Price         float64
	PreClose      float64
	Open          float64
	High          float64
	Low           float64
	ServerTime    string
	Volume        int64
	CurVolume     int64
	Amount        float32
	InsideVolume  int64
	OutsideVolume int64
	BidPrice      float64
	BidVol        int64
	AskPrice      float64
	AskVol        int64
	RiseSpeed     float32
	ShortTurnover float32
	Min2Amount    float32
	VolRatio      float32
	Depth         float32
}

BatchQuote represents a compact quote for a single security (0x054C).

func DecodeBatchQuotes

func DecodeBatchQuotes(body []byte) ([]BatchQuote, error)

DecodeBatchQuotes decodes a 0x054C batch quote response body.

type BoardMembersItem

type BoardMembersItem struct {
	Market         uint16
	Code           string
	Name           string
	PreClose       float32
	Open           float32
	High           float32
	Low            float32
	Close          float32
	Volume         uint32
	VolRatio       float32
	Amount         float32
	InsideVol      uint32
	OutsideVol     uint32
	TotalShares    float32
	FloatShares    float32
	EPS            float32
	NetAssets      float32
	TotalMcapAB    float32
	Bid            float32
	Ask            float32
	BidVol         uint32
	AskVol         uint32
	LastVol        uint32
	Turnover       float32
	BuyPriceLimit  float32
	SellPriceLimit float32
	LotSize        uint32
	SpeedPct       float32
	AvgPrice       float32
	KCBFlag        uint32
	BJFlag         uint32
	PETTM          float32
	PEDynamic      float32
	PEStatic       float32
	Change20d      float32
	YtdPct         float32
	Change60d      float32
	Change5d       float32
	Change10d      float32
	Activity       uint32
	ConsecutiveUp  int32
}

BoardMembersItem represents a single stock from the board members list.

func DecodeBoardMembers

func DecodeBoardMembers(body []byte) ([]BoardMembersItem, error)

DecodeBoardMembers decodes a 0x122C board members response body.

Header: 20-byte bitmap echo + 4-byte total + 2-byte row_count = 26 bytes. Per row: 68-byte fixed header (market:2 + code:22 GBK + name:44 GBK) + 4 bytes per active bit.

type Client

type Client = MainClient

Client keeps the main-quote client name in this module.

type CompanyCategoryItem

type CompanyCategoryItem struct {
	Name     string // Section name (e.g. "公司概况")
	Filename string // Section filename
	Start    uint32 // Content start offset
	Length   uint32 // Content length in bytes
}

CompanyCategoryItem represents one section in the F10 information directory.

func DecodeCompanyCategory

func DecodeCompanyCategory(body []byte) ([]CompanyCategoryItem, error)

DecodeCompanyCategory decodes a 0x02CF company category response body.

Layout: uint16 count, then count * 152-byte records:

name[64] + filename[80] + start(uint32) + length(uint32)

type DecodedBody

type DecodedBody struct {
	WirePayload []byte
	Decoded     []byte
}

DecodedBody holds the decoded payload of a response.

type ExClient

type ExClient struct {
	// contains filtered or unexported fields
}

ExClient represents a connection to a TDX 7727 extension quote server.

func DialEx

func DialEx(addr string, opts ...Option) (*ExClient, error)

DialEx connects to a 7727 extension quote server, performs SP login + extension bootstrap, and returns a Client ready for extension quote requests.

func DialExBest

func DialExBest(addresses []string, opts ...Option) (*ExClient, error)

DialExBest probes extension quote addresses, then tries each with DialEx until one succeeds.

func DialFund

func DialFund(addr string, opts ...Option) (*ExClient, error)

DialFund connects to a 7727 extension quote server, performs SP login + fund bootstrap, and returns a Client ready for fund KLine requests.

func (ExClient) Addr

func (c ExClient) Addr() string

Addr returns the server address this client is connected to.

func (ExClient) Close

func (c ExClient) Close() error

Close closes the underlying TCP connection and waits for the listener to exit.

func (*ExClient) GetFundDetail

func (c *ExClient) GetFundDetail(code string) (*FundDetail, error)

GetFundDetail retrieves fund detail data via the 7727 extension quote 0x2488 protocol.

func (*ExClient) GetFundDetailMode

func (c *ExClient) GetFundDetailMode(code string, mode uint16) (*FundDetail, error)

GetFundDetailMode retrieves fund detail data via the 7727 extension quote 0x2488 protocol using the provided mode.

func (*ExClient) GetFundKline

func (c *ExClient) GetFundKline(code string, period string, count int) ([]Kline, error)

GetFundKline retrieves fund K-line data via the 7727 extension quote protocol.

func (ExClient) IsAlive

func (c ExClient) IsAlive() bool

IsAlive reports whether the underlying connection is still active.

type FinanceInfo

type FinanceInfo struct {
	LiuTongGuBen float64 // 流通股本(股)
	Province     uint16  // 省份代码
	Industry     uint16  // 行业代码
	UpdatedDate  uint32  // 更新日期 YYYYMMDD
	IPODate      uint32  // 上市日期 YYYYMMDD

	ZongGuBen      float64 // 总股本(股)
	GuoJiaGu       float64 // 国家股(股)
	FaQiRenFaRenGu float64 // 发起人法人股(股)
	FaRenGu        float64 // 法人股(股)
	BGu            float64 // B股(股)
	HGu            float64 // H股(股)

	MeiGuShouYi         float64 // 每股收益(元)
	ZiChanZongJi        float64 // 资产总计(元)
	LiuDongZiChanZongJi float64 // 流动资产总计(元)
	GuDingZiChanJinE    float64 // 固定资产金额(元)
	WuXingZiChan        float64 // 无形资产(元)
	GuDongRenShu        float64 // 股东人数

	LiuDongFuZhaiHeJi float64 // 流动负债合计(元)
	ChangQiFuZhai     float64 // 长期负债(元)
	ZiBenGongJiJin    float64 // 资本公积金(元)
	GuiMoQuanYiHeJi   float64 // 所有者权益(元)

	YinYeZongShouRu   float64 // 营业总收入(元)
	YinYeChengBen     float64 // 营业成本(元)
	YingShouZhangKuan float64 // 应收帐款(元)
	YinYeLiRun        float64 // 营业利润(元)
	TouZiShouYi       float64 // 投资收益(元)

	JingYingXianJinLiu float64 // 经营现金流量净额(元)
	ZongXianJinLiu     float64 // 总现金流(元)
	CunHuo             float64 // 存货(元)
	LiRunZongE         float64 // 利润总额(元)
	ShuiHouLiRun       float64 // 税后利润(元)

	GuiMoJinLiRun   float64 // 净利润(元)
	WeiFenLiRun     float64 // 未分配利润(元)
	MeiGuJingZiChan float64 // 每股净资产(元)
	BaoLiu2         float64 // 保留字段
}

FinanceInfo represents fundamental financial data for a stock.

Wire format (opentdx): "<HB6sfHHII" + 31 "f" = 9 (header) + 140 (data) bytes. All float fields are IEEE 754 little-endian float32, converted to float64.

func DecodeFinance

func DecodeFinance(body []byte) (*FinanceInfo, error)

DecodeFinance decodes a 0x0010 finance response body.

type FundDetail

type FundDetail struct {
	Category byte
	Code     string
	Items    []FundDetailItem
}

FundDetail represents a 0x2488 fund detail response.

The response format is verified, but the semantic meaning of each item ID and the six uint16 values is not fully mapped yet, so the raw structure is exposed directly.

func DecodeFundDetail

func DecodeFundDetail(body []byte) (*FundDetail, error)

DecodeFundDetail decodes a 0x2488 fund detail response body.

func (*FundDetail) FindItem

func (d *FundDetail) FindItem(id uint32) (FundDetailItem, bool)

FindItem returns the first detail row matching id.

type FundDetailItem

type FundDetailItem struct {
	ID     uint32
	Values [6]uint16
}

FundDetailItem represents one 16-byte row in a 0x2488 response.

type HistoryTrade

type HistoryTrade struct {
	Time   time.Time
	Price  float64
	Volume int64
	Status int64
}

HistoryTrade represents a single historical intraday trade record.

func DecodeHistoryTrades

func DecodeHistoryTrades(body []byte, date string) ([]HistoryTrade, error)

DecodeHistoryTrades decodes a 0x0FB5 history trade response body.

type HostInfo

type HostInfo struct {
	Name string `json:"name"`
	IP   string `json:"ip"`
	Port int    `json:"port"`
}

HostInfo describes a TDX server entry.

func ExHosts

func ExHosts() []HostInfo

ExHosts returns the built-in extension quote servers.

func FundHosts

func FundHosts() []HostInfo

FundHosts returns the built-in fund quote servers.

func MainHosts

func MainHosts() []HostInfo

MainHosts returns the built-in main quote servers.

func SPHosts

func SPHosts() []HostInfo

SPHosts returns the built-in MAC/SP quote servers.

func (HostInfo) Address

func (h HostInfo) Address() string

Address returns the "host:port" form.

type HostProbeResult

type HostProbeResult struct {
	Name      string        `json:"name"`
	IP        string        `json:"ip"`
	Port      int           `json:"port"`
	Address   string        `json:"address"`
	Latency   time.Duration `json:"latency"`
	Reachable bool          `json:"reachable"`
	Error     string        `json:"error,omitempty"`
}

HostProbeResult records a single TCP probe result.

func CachedMainResults

func CachedMainResults(timeout time.Duration) []HostProbeResult

CachedMainResults returns the cached main probe results (for display).

func CachedSPResults

func CachedSPResults(timeout time.Duration) []HostProbeResult

CachedSPResults returns the cached SP probe results (for display).

func FastestAddress

func FastestAddress(addresses []string, timeout time.Duration) (HostProbeResult, error)

FastestAddress returns the single fastest reachable address.

func ProbeAddresses

func ProbeAddresses(addresses []string, timeout time.Duration) []HostProbeResult

ProbeAddresses concurrently dials each address and returns results sorted by reachability then latency (ascending).

func ProbeHosts

func ProbeHosts(hosts []HostInfo, timeout time.Duration) []HostProbeResult

ProbeHosts probes HostInfo entries and enriches results with Name/IP/Port.

type Kline

type Kline struct {
	Time      time.Time // Bar timestamp
	Open      float64   // Open price (yuan)
	High      float64   // High price (yuan)
	Low       float64   // Low price (yuan)
	Close     float64   // Close price (yuan)
	Volume    int64     // Volume (shares)
	Amount    float64   // Turnover (yuan)
	UpCount   int       // Advancing stocks count (index only)
	DownCount int       // Declining stocks count (index only)
}

Kline represents a single candlestick bar.

func DecodeFundKlines

func DecodeFundKlines(body []byte, code string, period uint16) ([]Kline, error)

DecodeFundKlines decodes a 0x2489 fund kline response body.

func DecodeKlines

func DecodeKlines(body []byte, code string, market uint16, period uint16, kind string) ([]Kline, error)

DecodeKlines decodes a 0x052D kline response body.

func (Kline) String

func (k Kline) String() string

String returns a human-readable representation.

type LHBRecord

type LHBRecord struct {
	Date      string
	InfoType  string
	ChangePct float64
	Volume    float64 // 万股
	Amount    float64 // 万元
	BuySeats  []LHBSeat
	SellSeats []LHBSeat
}

LHBRecord represents one entry in the Dragon-Tiger list.

func ParseLHB

func ParseLHB(text string) []LHBRecord

ParseLHB extracts Dragon-Tiger list records from the "资金动向" F10 section text.

type LHBSeat

type LHBSeat struct {
	Name    string
	BuyAmt  float64 // 万元
	SellAmt float64 // 万元
}

LHBSeat represents one seat (broker branch) in the Dragon-Tiger list.

type MainClient

type MainClient struct {
	// contains filtered or unexported fields
}

MainClient represents a connection to a TDX 7709 market data server.

func Dial

func Dial(addr string, opts ...Option) (*MainClient, error)

Dial connects to a TDX server, performs the 3-stage bootstrap handshake (Ping → ConnectAuth → Stage2), and returns a ready-to-use Client.

func DialBest

func DialBest(addresses []string, opts ...Option) (*MainClient, error)

DialBest probes addresses (sorted by latency), then tries each with Dial until one succeeds. Uses in-memory cache with 10min TTL.

func DialSP

func DialSP(addr string, opts ...Option) (*MainClient, error)

DialSP connects to a TDX mac_hosts server, performs standard bootstrap + SP mode login, and returns a Client ready for mac_quotation protocols (0x122C, etc.).

func DialSPBest

func DialSPBest(addresses []string, opts ...Option) (*MainClient, error)

DialSPBest probes addresses, then tries each with DialSP until one succeeds.

func (MainClient) Addr

func (c MainClient) Addr() string

Addr returns the server address this client is connected to.

func (MainClient) Close

func (c MainClient) Close() error

Close closes the underlying TCP connection and waits for the listener to exit.

func (*MainClient) GetBatchQuotes

func (c *MainClient) GetBatchQuotes(codes []string) ([]BatchQuote, error)

GetBatchQuotes retrieves compact quotes for multiple stock codes in one request (0x054C).

func (*MainClient) GetBoardMembers

func (c *MainClient) GetBoardMembers(board string, sortType uint16, count int, sortOrder uint16) ([]BoardMembersItem, error)

GetBoardMembers retrieves stock list for a board with auto-pagination.

func (*MainClient) GetCompanyCategory

func (c *MainClient) GetCompanyCategory(code string) ([]CompanyCategoryItem, error)

GetCompanyCategory retrieves the F10 information section list.

func (*MainClient) GetCompanyContent

func (c *MainClient) GetCompanyContent(code string, filename string, start uint32, length uint32) (string, error)

GetCompanyContent retrieves F10 section content for the given stock code.

func (*MainClient) GetFinance

func (c *MainClient) GetFinance(code string) (*FinanceInfo, error)

GetFinance retrieves fundamental financial data for the given stock code.

func (*MainClient) GetFundDetail

func (c *MainClient) GetFundDetail(code string) (*FundDetail, error)

GetFundDetail retrieves fund detail data via the 7727 extension quote 0x2488 protocol.

func (*MainClient) GetFundDetailMode

func (c *MainClient) GetFundDetailMode(code string, mode uint16) (*FundDetail, error)

GetFundDetailMode retrieves fund detail data via the 7727 extension quote 0x2488 protocol using the provided mode.

func (*MainClient) GetHistoryTrade

func (c *MainClient) GetHistoryTrade(date string, code string, count int) ([]HistoryTrade, error)

GetHistoryTrade retrieves historical intraday trade records for the given stock code.

Parameters:

  • date: trade date, format "20060102" or "2006-01-02"
  • code: stock code, supports "600000", "sh600000", "SH600000" formats
  • count: number of records to retrieve, max 2000

Example:

trades, err := c.GetHistoryTrade("20260421", "sh600000", 500)

func (*MainClient) GetKline

func (c *MainClient) GetKline(code string, period string, count int) ([]Kline, error)

GetKline retrieves K-line data for the given stock code and period.

Parameters:

  • code: stock code, supports "600000", "sh600000", "SH600000" formats
  • period: one of Period* constants (e.g. "day", "5m", "1m")
  • count: number of bars to retrieve, max 800

Example:

klines, err := c.GetKline("sh600000", "day", 100)

func (*MainClient) GetLHB

func (c *MainClient) GetLHB(code string) ([]LHBRecord, error)

GetLHB retrieves the Dragon-Tiger list for the given stock code. It finds the "资金动向" section in F10 data, downloads it, and parses LHB records.

func (*MainClient) GetMarketCodes

func (c *MainClient) GetMarketCodes(market uint16, start uint16) (*MarketCodePage, error)

GetMarketCodes retrieves one page of stock codes for the given market.

Parameters:

  • market: MarketShenzhen (0), MarketShanghai (1), or MarketBeijing (2)
  • start: page offset (0, 1000, 2000, ...)

Example:

page, err := c.GetMarketCodes(MarketShanghai, 0)

func (*MainClient) GetQuotesList

func (c *MainClient) GetQuotesList(category uint16, sortType uint16, start int, count int, reverse bool, exclude ...uint16) ([]QuotesItem, error)

GetQuotesList retrieves a sorted quotes list for the given market category. The optional exclude parameter is a bitmask to exclude stock types (OR multiple FilterXxx constants).

func (*MainClient) GetTick

func (c *MainClient) GetTick(code string) (*Tick, error)

GetTick retrieves a real-time quote snapshot for the given stock code.

Parameters:

  • code: stock code, supports "600000", "sh600000", "SH600000" formats

Example:

tick, err := c.GetTick("sh600000")

func (*MainClient) GetTickChart

func (c *MainClient) GetTickChart(code string, count int) ([]TickChart, error)

GetTickChart retrieves intraday tick chart data for the given stock code.

Parameters:

  • code: stock code, supports "600000", "sh600000", "SH600000" formats
  • count: number of data points to retrieve

Example:

chart, err := c.GetTickChart("sh600000", 240)

func (*MainClient) GetTicks

func (c *MainClient) GetTicks(codes []string) ([]Tick, error)

GetTicks retrieves real-time quote snapshots for multiple stock codes in one request.

Parameters:

  • codes: stock codes, supports "600000", "sh600000", "SH600000" formats

Example:

ticks, err := c.GetTicks([]string{"sh600000", "sz000001", "sz300750"})

func (*MainClient) GetTopBoard

func (c *MainClient) GetTopBoard(category uint16, size int) (*TopBoardResult, error)

GetTopBoard retrieves 9 ranking lists (涨幅/跌幅/振幅/涨速/跌速/量比/委比/换手率).

func (*MainClient) GetTransaction

func (c *MainClient) GetTransaction(code string, date string, count int) ([]Transaction, error)

GetTransaction retrieves intraday transaction records for the given stock code.

Parameters:

  • code: stock code, supports "600000", "sh600000", "SH600000" formats
  • date: trade date, format "20060102" or "2006-01-02", defaults to today if empty
  • count: number of records to retrieve, max 900

Example:

trades, err := c.GetTransaction("sh600000", "", 100)

func (*MainClient) GetXdXr

func (c *MainClient) GetXdXr(code string) ([]XdXrItem, error)

GetXdXr retrieves ex-rights/ex-dividend history for the given stock code.

func (MainClient) IsAlive

func (c MainClient) IsAlive() bool

IsAlive reports whether the underlying connection is still active.

type MarketCode

type MarketCode struct {
	Market    uint16
	Code      string
	Name      string
	Multiple  uint16
	Decimal   int8
	LastPrice float64
}

MarketCode represents a single security in the code list response.

type MarketCodePage

type MarketCodePage struct {
	Count uint16
	List  []MarketCode
}

MarketCodePage is one page of the code list response.

func DecodeMarketCodeList

func DecodeMarketCodeList(body []byte, market uint16) (*MarketCodePage, error)

DecodeMarketCodeList decodes a 0x0450 code list response body.

type Option

type Option func(*config)

Option configures a Client.

func WithEx

func WithEx() Option

WithEx enables extension quote mode (7727 protocol).

func WithSP

func WithSP() Option

WithSP enables SP mode login (mac_quotation protocol) after bootstrap.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the dial and bootstrap timeout.

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool maintains a set of connections to the fastest TDX servers. It automatically probes nodes, establishes connections, and runs background health checks to replace dead connections.

func NewPool

func NewPool(size int, opts ...Option) (*Pool, error)

NewPool creates a connection pool of the given size. It probes servers, connects to the fastest ones, and starts a background maintenance goroutine.

func (*Pool) Close

func (p *Pool) Close() error

Close shuts down the background goroutine and closes all connections.

func (*Pool) Get

func (p *Pool) Get() *MainClient

Get returns a client using round-robin. If the selected client is dead, it is replaced with a new connection before returning.

func (*Pool) GetEx

func (p *Pool) GetEx() *ExClient

GetEx returns an extension quote client using round-robin. For non-Ex pools, it returns nil.

func (*Pool) Stats

func (p *Pool) Stats() PoolStats

Stats returns current pool statistics.

type PoolStats

type PoolStats struct {
	Size   int // desired pool size
	Active int // currently alive connections
}

PoolStats holds pool status information.

type QuoteStock

type QuoteStock struct {
	Market byte
	Code   string
}

QuoteStock is a market+code pair used in batch requests.

type QuotesItem

type QuotesItem struct {
	Market    uint16
	Code      string
	Price     float64 // 现价 (元)
	Open      float64 // 开盘价 (元)
	High      float64 // 最高价 (元)
	Low       float64 // 最低价 (元)
	PreClose  float64 // 昨收价 (元)
	Volume    int64   // 总量 (手)
	CurVol    int64   // 现量 (手)
	Amount    float64 // 总金额 (元)
	InVol     int64   // 内盘 (手)
	OutVol    int64   // 外盘 (手)
	RiseSpeed float64 // 涨速 (%)
	Active    uint16  // 活跃度
}

QuotesItem represents a single stock in the sorted quotes list.

func DecodeQuotesList

func DecodeQuotesList(body []byte) ([]QuotesItem, error)

DecodeQuotesList decodes a 0x054B quotes list response body.

Header: <HH> (block + count), 4 bytes. Per row (variable length due to get_price varint encoding):

<B6sH> (9 bytes) — market, code, active1
9 get_price() varints: price, pre_close, open, high, low, server_time, neg_price, vol, cur_vol
<f> (4 bytes) — amount (float32)
3 get_price() varints: in_vol, out_vol, s_amount, open_amount
4 get_price() varints: bid, ask, bid_vol, ask_vol
<Hhhfh10sff24sH> (56 bytes) — trailing fixed fields

Post-processing: prices /= 100 (厘→元), open/high/low/pre_close += price then /= 100.

type ResponseHeader

type ResponseHeader struct {
	Magic     uint32
	Unknown1  uint16
	ServiceID uint16
	PacketSeq uint16
	CMD       uint16
	ZipLen    uint16
	RawLen    uint16
}

ResponseHeader is the 16-byte header of server response packets.

func DecodeResponseHeader

func DecodeResponseHeader(data []byte) (*ResponseHeader, error)

DecodeResponseHeader parses a 16-byte response header.

type ResponsePacket

type ResponsePacket struct {
	Header *ResponseHeader
	Body   *DecodedBody
}

ResponsePacket is a fully decoded server response.

func DecodeResponsePacket

func DecodeResponsePacket(headerData, payload []byte) (*ResponsePacket, error)

DecodeResponsePacket decodes a full response from header + payload bytes.

type Tick

type Tick struct {
	Market        uint16
	Code          string
	Active1       uint16
	Time          string
	PrevClose     float64
	Open          float64
	High          float64
	Low           float64
	Price         float64
	TotalVolume   int64
	Volume        int64
	Amount        float64
	InsideVolume  int64
	OutsideVolume int64
	BuyLevels     [5]TickLevel
	SellLevels    [5]TickLevel
	// ChangeRate is the raw change rate field from the protocol tail.
	// Use CalcChangeRate() for the actual price change percentage.
	ChangeRate float64
	Active2    uint16
}

Tick represents a real-time quote snapshot for a single security.

func DecodeTicks

func DecodeTicks(body []byte) ([]Tick, error)

DecodeTicks decodes a 0x053E tick response body.

func (*Tick) CalcChangeRate

func (t *Tick) CalcChangeRate() float64

CalcChangeRate returns the price change percentage relative to PrevClose. Returns 0 if PrevClose is zero.

type TickChart

type TickChart struct {
	Time   string  // HH:MM
	Price  float64 // yuan (price / 100)
	Avg    float64 // yuan (avg / 10000)
	Volume int64   // lots (手)
}

TickChart represents one sampling point on the intraday chart.

func DecodeTickChart

func DecodeTickChart(body []byte) ([]TickChart, error)

DecodeTickChart decodes a 0x0537 tick chart response body.

Body layout: [count:u16, _:u16] followed by `count` varint records. Each record contains 3 varint fields:

  • price (signed): first record is the base price; subsequent records are deltas
  • avg (signed): first record is the base avg; subsequent records are deltas
  • volume (signed, unit: lots 手)

Final units: price / 100 = yuan, avg / 10000 = yuan.

type TickLevel

type TickLevel struct {
	Price  float64
	Volume int64
}

TickLevel represents one level of the order book (buy or sell).

type TopBoardItem

type TopBoardItem struct {
	Market uint16
	Code   string
	Price  float32
	Value  float32
}

TopBoardItem represents a single entry in a ranking list.

type TopBoardResult

type TopBoardResult struct {
	Increase           []TopBoardItem // 涨幅榜
	Decrease           []TopBoardItem // 跌幅榜
	Amplitude          []TopBoardItem // 振幅榜
	RiseSpeed          []TopBoardItem // 涨速榜
	FallSpeed          []TopBoardItem // 跌速榜
	VolRatio           []TopBoardItem // 量比榜
	PosCommissionRatio []TopBoardItem // 委比正序
	NegCommissionRatio []TopBoardItem // 委比倒序
	Turnover           []TopBoardItem // 换手率榜
}

TopBoardResult holds all 9 ranking lists from a single 0x53F response.

func DecodeTopBoard

func DecodeTopBoard(body []byte) (*TopBoardResult, error)

DecodeTopBoard decodes a 0x053F top board response body.

Layout: 1 byte size, then 9 lists × size entries. Each entry: <B6sff> = market(1) + code(6) + price(float32) + value(float32) = 15 bytes.

type Transaction

type Transaction struct {
	Time   time.Time
	Price  float64
	Volume int64
	Number int64
	Status int64
}

Transaction represents a single intraday trade record.

func DecodeTransactions

func DecodeTransactions(body []byte, code string, date string) ([]Transaction, error)

DecodeTransactions decodes a 0x0FC5 transaction response body.

type WrapperHeader

type WrapperHeader struct {
	Magic     uint8
	Type      uint8
	ServiceID uint16
	PacketSeq uint16
	Len1      uint16
	Len2      uint16
	CMD       uint16
}

WrapperHeader is the 12-byte outer header for request packets.

func (*WrapperHeader) Serialize

func (h *WrapperHeader) Serialize() []byte

Serialize encodes the 12-byte wrapper header.

type XdXrItem

type XdXrItem struct {
	Date     time.Time
	Category uint8

	FenHong     float32 // 分红(每股,元) - category 1
	PeiGuJia    float32 // 配股价       - category 1
	SongZhuanGu float32 // 送转股(每10股) - category 1
	PeiGu       float32 // 配股(每10股)  - category 1

	SuoGu float32 // 缩股比例 - category 11/12

	XingQuanJia float32 // 行权价 - category 13/14
	FenShu      float32 // 份数   - category 13/14

	PanQianLiuTong float32 // 盘前流通股本 - category 2-10
	QianZongGuBen  float32 // 前总股本     - category 2-10
	PanHouLiuTong  float32 // 盘后流通股本 - category 2-10
	HouZongGuBen   float32 // 后总股本     - category 2-10
}

XdXrItem represents a single ex-rights/ex-dividend event.

func DecodeXdXr

func DecodeXdXr(body []byte) ([]XdXrItem, error)

DecodeXdXr decodes a 0x000F XDXR response body.

Layout: "<HB6sH" (11 bytes header) + count records. Each record (29 bytes): "<B6sBIB" (13 bytes) + 16 bytes payload.

Directories

Path Synopsis
cmd
tdx-cli command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL