Real-Time Push

The Go SDK's PushClient maintains a persistent Protobuf/TCP+TLS connection to the Tiger OpenAPI server. Data is transmitted using Protobuf encoding with varint32 length-prefix framing. It supports automatic reconnection, heartbeat keep-alive, and callback-based delivery of market data and account events.

Quick Start

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/tigerfintech/openapi-go-sdk/config"
	"github.com/tigerfintech/openapi-go-sdk/push"
	"github.com/tigerfintech/openapi-go-sdk/push/pb"
)

func main() {
	cfg, err := config.NewClientConfig()
	if err != nil {
		log.Fatal(err)
	}

	pc := push.NewPushClient(cfg)

	// Register all callbacks before connecting
	pc.SetCallbacks(push.Callbacks{
		OnConnect: func() {
			fmt.Println("Connected to push server")
		},
		OnDisconnect: func() {
			fmt.Println("Disconnected from push server")
		},
		OnError: func(err error) {
			fmt.Println("Push error:", err)
		},
		OnKickout: func(reason string) {
			fmt.Println("Kicked out, reason:", reason)
		},
		OnQuote: func(data *pb.QuoteData) {
			fmt.Printf("Quote: %s latest=%.2f\n", data.GetSymbol(), data.GetLatestPrice())
		},
		OnTick: func(data *pb.TradeTickData) {
			fmt.Printf("Tick: %s\n", data.GetSymbol())
		},
		OnDepth: func(data *pb.QuoteDepthData) {
			fmt.Printf("Depth: %s\n", data.GetSymbol())
		},
		OnOrder: func(data *pb.OrderStatusData) {
			fmt.Printf("Order update: id=%d status=%s\n", data.GetId(), data.GetStatus())
		},
		OnAsset: func(data *pb.AssetData) {
			fmt.Println("Asset change received")
		},
		OnPosition: func(data *pb.PositionData) {
			fmt.Printf("Position change: %s\n", data.GetSymbol())
		},
		OnTransaction: func(data *pb.OrderTransactionData) {
			fmt.Printf("Transaction: orderId=%d\n", data.GetOrderId())
		},
	})

	// Establish the TCP+TLS connection
	if err := pc.Connect(); err != nil {
		log.Fatal(err)
	}
	defer pc.Disconnect()

	// Subscribe to market data
	pc.SubscribeQuote([]string{"AAPL", "TSLA"})
	pc.SubscribeTick([]string{"AAPL"})
	pc.SubscribeDepth([]string{"AAPL"})
	pc.SubscribeKline([]string{"AAPL"})

	// Subscribe to account events (pass "" to use the account from config)
	pc.SubscribeAsset("")
	pc.SubscribeOrder("")
	pc.SubscribePosition("")
	pc.SubscribeTransaction("")

	// Keep the program alive to receive push data
	time.Sleep(60 * time.Second)
}

Client Lifecycle

NewPushClient

func NewPushClient(cfg *config.ClientConfig, opts ...PushClientOption) *PushClient

Creates a new PushClient. The client is idle until Connect() is called.

ParameterTypeDescription
cfg*config.ClientConfigLoaded configuration (credentials, server URL)
opts...PushClientOptionOptional functional options

SetCallbacks

func (pc *PushClient) SetCallbacks(cb Callbacks)

Registers the callback functions that will be invoked when push events arrive. Call this before Connect().


Connect

func (pc *PushClient) Connect() error

Opens the TCP+TLS connection and starts the background receive loop. Blocks until the handshake is complete.

if err := pc.Connect(); err != nil {
    log.Fatal("failed to connect:", err)
}

Disconnect

func (pc *PushClient) Disconnect() error

Gracefully closes the connection and stops all background goroutines.

defer pc.Disconnect()

State

func (pc *PushClient) State() ConnectionState

Returns the current connection state (Connecting, Connected, Disconnected).

fmt.Println("Current state:", pc.State())

Callbacks Reference

The Callbacks struct holds all event handler functions. All fields are optional — assign only the ones you need.

All data types are generated from Protobuf in the github.com/tigerfintech/openapi-go-sdk/push/pb package.

FieldSignatureTriggered when
OnConnectfunc()Connection established
OnDisconnectfunc()Connection closed
OnErrorfunc(error)A transport or protocol error occurs
OnKickoutfunc(message string)Server forces disconnection
OnQuotefunc(*pb.QuoteData)Real-time stock quote update
OnQuoteBBOfunc(*pb.QuoteData)Best bid/offer update
OnTickfunc(*pb.TradeTickData)Trade tick received
OnDepthfunc(*pb.QuoteDepthData)Order-book depth update
OnOptionfunc(*pb.QuoteData)Option quote update
OnFuturefunc(*pb.QuoteData)Futures quote update
OnKlinefunc(*pb.KlineData)K-line bar update
OnStockTopfunc(*pb.StockTopData)Stock top-list update
OnOptionTopfunc(*pb.OptionTopData)Option top-list update
OnFullTickfunc(*pb.TickData)Full tick data
OnAssetfunc(*pb.AssetData)Account asset change
OnPositionfunc(*pb.PositionData)Position change
OnOrderfunc(*pb.OrderStatusData)Order status change
OnTransactionfunc(*pb.OrderTransactionData)Fill / execution received
import "github.com/tigerfintech/openapi-go-sdk/push/pb"

pc.SetCallbacks(push.Callbacks{
    OnQuote: func(data *pb.QuoteData) {
        fmt.Printf("%s: %.2f\n", data.GetSymbol(), data.GetLatestPrice())
    },
    OnDepth: func(data *pb.QuoteDepthData) {
        levels := 0
        if data.GetBid() != nil {
            levels = len(data.GetBid().GetPrice())
        }
        fmt.Printf("Depth update for %s: %d bid levels\n", data.GetSymbol(), levels)
    },
    OnKline: func(data *pb.KlineData) {
        fmt.Printf("Kline %s: O=%.2f H=%.2f L=%.2f C=%.2f\n",
            data.GetSymbol(), data.GetOpen(), data.GetHigh(), data.GetLow(), data.GetClose())
    },
    OnError: func(err error) {
        log.Println("push error:", err)
    },
})

Market Data Subscriptions

v0.3.0 note: Fixed a dispatcher bug for crypto (Cc) push — previously subscribing Cc then receiving data triggered a unknown DataType: Cc error. Now fixed, Cc pushes are routed to OnQuote callback uniformly. This release also adds four new subscription method pairs: stock top-list, option top-list, crypto quote, and market state (see the "new in v0.3.0" subsections below).

SubscribeQuote / UnsubscribeQuote

func (pc *PushClient) SubscribeQuote(symbols []string)
func (pc *PushClient) UnsubscribeQuote(symbols []string)

Subscribe to or unsubscribe from real-time best-bid/ask and last-price updates.

pc.SubscribeQuote([]string{"AAPL", "TSLA", "MSFT"})
// Later, remove one symbol
pc.UnsubscribeQuote([]string{"TSLA"})

SubscribeTick / UnsubscribeTick

func (pc *PushClient) SubscribeTick(symbols []string)
func (pc *PushClient) UnsubscribeTick(symbols []string)

Subscribe to tick-by-tick trade data (each individual executed trade).

pc.SubscribeTick([]string{"AAPL"})
pc.UnsubscribeTick([]string{"AAPL"})

SubscribeDepth / UnsubscribeDepth

func (pc *PushClient) SubscribeDepth(symbols []string)
func (pc *PushClient) UnsubscribeDepth(symbols []string)

Subscribe to Level 2 order-book depth updates (up to 10 bid/ask levels).

pc.SubscribeDepth([]string{"AAPL"})
pc.UnsubscribeDepth([]string{"AAPL"})

SubscribeOption / UnsubscribeOption

func (pc *PushClient) SubscribeOption(symbols []string)
func (pc *PushClient) UnsubscribeOption(symbols []string)

Subscribe to real-time option quote updates using OCC-style identifiers.

pc.SubscribeOption([]string{"AAPL  250117C00150000"})
pc.UnsubscribeOption([]string{"AAPL  250117C00150000"})

SubscribeFuture / UnsubscribeFuture

func (pc *PushClient) SubscribeFuture(symbols []string)
func (pc *PushClient) UnsubscribeFuture(symbols []string)

Subscribe to real-time futures quote updates.

pc.SubscribeFuture([]string{"ES2506", "NQ2506"})
pc.UnsubscribeFuture([]string{"ES2506"})

SubscribeKline / UnsubscribeKline

func (pc *PushClient) SubscribeKline(symbols []string)
func (pc *PushClient) UnsubscribeKline(symbols []string)

Subscribe to real-time K-line bar updates (1-minute bars by default).

pc.SubscribeKline([]string{"AAPL"})
pc.UnsubscribeKline([]string{"AAPL"})

SubscribeStockTop / UnsubscribeStockTop (new in v0.3.0)

func (pc *PushClient) SubscribeStockTop(market string, indicators []string) error
func (pc *PushClient) UnsubscribeStockTop(market string, indicators []string) error

Description

Subscribe to real-time stock top-list (ranking) updates for a given market. You may select multiple indicators such as latest price, gainers, losers, volume, turnover, amplitude, turnover rate, etc. Data is delivered via the existing OnStockTop callback.

Parameters

ParameterTypeRequiredDescription
marketstringYesMarket code: US / HK / CN
indicators[]stringYesIndicator list, e.g. LATEST_PRICE / HIGHER / LOWER / VOLUME / AMOUNT / AMPLITUDE / TURNOVER_RATE

Callback

OnStockTop func(data *pb.StockTopData)

FieldTypeDescription
MarketstringMarket code
TopData[]*StockTopData_TopDataRanking data grouped by indicator

Example

pc.SetCallbacks(push.Callbacks{
    OnStockTop: func(data *pb.StockTopData) {
        fmt.Printf("[StockTop] market=%s items=%d\n", data.GetMarket(), len(data.GetTopData()))
    },
})
pc.SubscribeStockTop("US", []string{"LATEST_PRICE", "HIGHER", "LOWER"})
pc.UnsubscribeStockTop("US", []string{"LATEST_PRICE", "HIGHER", "LOWER"})

SubscribeOptionTop / UnsubscribeOptionTop (new in v0.3.0)

func (pc *PushClient) SubscribeOptionTop(market string, indicators []string) error
func (pc *PushClient) UnsubscribeOptionTop(market string, indicators []string) error

Description

Subscribe to real-time option top-list (ranking) updates for a given market. Data is delivered via the existing OnOptionTop callback.

Parameters

ParameterTypeRequiredDescription
marketstringYesMarket code: US / HK / CN
indicators[]stringYesIndicator list, e.g. LATEST_PRICE / HIGHER / LOWER / VOLUME / AMOUNT

Callback

OnOptionTop func(data *pb.OptionTopData)

FieldTypeDescription
MarketstringMarket code
TopData[]*OptionTopData_TopDataRanking data grouped by indicator

Example

pc.SetCallbacks(push.Callbacks{
    OnOptionTop: func(data *pb.OptionTopData) {
        fmt.Printf("[OptionTop] market=%s items=%d\n", data.GetMarket(), len(data.GetTopData()))
    },
})
pc.SubscribeOptionTop("US", []string{"VOLUME", "AMOUNT"})
pc.UnsubscribeOptionTop("US", []string{"VOLUME", "AMOUNT"})

SubscribeCc / UnsubscribeCc (new in v0.3.0)

func (pc *PushClient) SubscribeCc(symbols []string) error
func (pc *PushClient) UnsubscribeCc(symbols []string) error

Description

Subscribe to or unsubscribe from real-time cryptocurrency quote updates.

Note: Cc pushes use the same data type as regular stock quotes. They are routed to the OnQuote callback — there is no separate callback for Cc (aligned with the Python SDK behavior).

Parameters

ParameterTypeRequiredDescription
symbols[]stringYesCrypto symbol list, e.g. BTCUSD, ETHUSD

Callback

OnQuote func(data *pb.QuoteData) (shared with stock quotes)

Example

pc.SetCallbacks(push.Callbacks{
    OnQuote: func(data *pb.QuoteData) {
        // Cc updates also arrive here
        fmt.Printf("[Quote/Cc] %s latest=%.2f\n", data.GetSymbol(), data.GetLatestPrice())
    },
})
pc.SubscribeCc([]string{"BTCUSD", "ETHUSD"})
pc.UnsubscribeCc([]string{"BTCUSD", "ETHUSD"})

SubscribeMarket / UnsubscribeMarket (new in v0.3.0)

func (pc *PushClient) SubscribeMarket(market string) error
func (pc *PushClient) UnsubscribeMarket(market string) error

Description

Subscribe to or unsubscribe from whole-market state updates (e.g. pre-market, open, close, post-market transitions).

Note: On the wire this uses dataType=Quote with a market field, so updates are delivered via the OnQuote callback.

Parameters

ParameterTypeRequiredDescription
marketstringYesMarket code: US / HK / CN / SG

Callback

OnQuote func(data *pb.QuoteData) (shared with stock quotes)

Example

pc.SetCallbacks(push.Callbacks{
    OnQuote: func(data *pb.QuoteData) {
        // Market-state updates also arrive here
        fmt.Printf("[Market/Quote] symbol=%s\n", data.GetSymbol())
    },
})
pc.SubscribeMarket("US")
pc.UnsubscribeMarket("US")

Account Subscriptions

SubscribeAsset / UnsubscribeAsset

func (pc *PushClient) SubscribeAsset(account string)
func (pc *PushClient) UnsubscribeAsset()

Subscribe to account asset changes (cash balance, net liquidation value, buying power).

// Pass "" to use the account in the config file
pc.SubscribeAsset("")
// Or specify an explicit account
pc.SubscribeAsset("DU123456")

pc.UnsubscribeAsset()

SubscribePosition / UnsubscribePosition

func (pc *PushClient) SubscribePosition(account string)
func (pc *PushClient) UnsubscribePosition()

Subscribe to position updates (new position opened, quantity changed, position closed).

pc.SubscribePosition("")
pc.UnsubscribePosition()

SubscribeOrder / UnsubscribeOrder

func (pc *PushClient) SubscribeOrder(account string)
func (pc *PushClient) UnsubscribeOrder()

Subscribe to order status changes (submitted, partially filled, fully filled, cancelled).

pc.SubscribeOrder("")
pc.UnsubscribeOrder()

SubscribeTransaction / UnsubscribeTransaction

func (pc *PushClient) SubscribeTransaction(account string)
func (pc *PushClient) UnsubscribeTransaction()

Subscribe to individual fill (execution) events.

pc.SubscribeTransaction("")
pc.UnsubscribeTransaction()

Complete Subscription Reference

// Market data subscriptions
pc.SubscribeQuote([]string{"AAPL", "TSLA"})
pc.SubscribeTick([]string{"AAPL"})
pc.SubscribeDepth([]string{"AAPL"})
pc.SubscribeOption([]string{"AAPL  250117C00150000"})
pc.SubscribeFuture([]string{"ES2506"})
pc.SubscribeKline([]string{"AAPL"})

// Account subscriptions
pc.SubscribeAsset("")
pc.SubscribePosition("")
pc.SubscribeOrder("")
pc.SubscribeTransaction("")

// Unsubscribe from market data
pc.UnsubscribeQuote([]string{"TSLA"})
pc.UnsubscribeTick([]string{"AAPL"})
pc.UnsubscribeDepth([]string{"AAPL"})
pc.UnsubscribeOption([]string{"AAPL  250117C00150000"})
pc.UnsubscribeFuture([]string{"ES2506"})
pc.UnsubscribeKline([]string{"AAPL"})

// Unsubscribe from account events
pc.UnsubscribeAsset()
pc.UnsubscribePosition()
pc.UnsubscribeOrder()
pc.UnsubscribeTransaction()