market

package
v0.0.0-...-3a9e237 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: Apache-2.0, MIT Imports: 12 Imported by: 0

Documentation

Overview

Package market provides a client for the Longport Market OpenAPI. It covers market status, broker holdings, A/H premium, trade statistics, market anomalies, and index constituents.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AhPremiumIntraday

type AhPremiumIntraday struct {
	// Intraday data points
	Klines []AhPremiumKline
}

AhPremiumIntraday holds A/H premium intraday data for a dual-listed security.

type AhPremiumKline

type AhPremiumKline struct {
	// A-share price
	Aprice decimal.Decimal
	// A-share previous close
	Apreclose decimal.Decimal
	// H-share price
	Hprice decimal.Decimal
	// H-share previous close
	Hpreclose decimal.Decimal
	// CNY/HKD exchange rate
	CurrencyRate decimal.Decimal
	// A/H premium rate (negative = H-share at premium)
	AhpremiumRate decimal.Decimal
	// Price spread
	PriceSpread decimal.Decimal
	// Data point timestamp
	Timestamp time.Time
}

AhPremiumKline is one A/H premium data point.

type AhPremiumKlines

type AhPremiumKlines struct {
	// K-line data points
	Klines []AhPremiumKline
}

AhPremiumKlines holds A/H premium K-line data for a dual-listed security.

type AhPremiumPeriod

type AhPremiumPeriod int

AhPremiumPeriod is the K-line period for A/H premium queries.

const (
	// AhPremiumPeriodMin1 is the 1-minute period.
	AhPremiumPeriodMin1 AhPremiumPeriod = iota
	// AhPremiumPeriodMin5 is the 5-minute period.
	AhPremiumPeriodMin5
	// AhPremiumPeriodMin15 is the 15-minute period.
	AhPremiumPeriodMin15
	// AhPremiumPeriodMin30 is the 30-minute period.
	AhPremiumPeriodMin30
	// AhPremiumPeriodMin60 is the 60-minute period.
	AhPremiumPeriodMin60
	// AhPremiumPeriodDay is the daily period.
	AhPremiumPeriodDay
	// AhPremiumPeriodWeek is the weekly period.
	AhPremiumPeriodWeek
	// AhPremiumPeriodMonth is the monthly period.
	AhPremiumPeriodMonth
	// AhPremiumPeriodYear is the yearly period.
	AhPremiumPeriodYear
)

type AnomalyItem

type AnomalyItem struct {
	// Security symbol (e.g. "700.HK")
	Symbol string
	// Security name
	Name string
	// Anomaly type name, e.g. "大宗交易", "融资买入"
	AlertName string
	// Time of the anomaly (unix timestamp in milliseconds)
	AlertTime int64
	// Change values associated with the anomaly event
	ChangeValues []string
	// Sentiment direction: 1 = positive/up, 2 = negative/down
	Emotion int32
}

AnomalyItem is one market anomaly event (e.g. large block trade, margin buying surge).

type AnomalyResponse

type AnomalyResponse struct {
	// Whether anomaly alerts are globally disabled
	AllOff bool
	// List of market anomaly events
	Changes []AnomalyItem
}

AnomalyResponse holds market anomaly alerts for a market.

type BrokerHoldingChanges

type BrokerHoldingChanges struct {
	// Current value
	Value *decimal.Decimal
	// 1-day change
	Chg1 *decimal.Decimal
	// 5-day change
	Chg5 *decimal.Decimal
	// 20-day change
	Chg20 *decimal.Decimal
	// 60-day change
	Chg60 *decimal.Decimal
}

BrokerHoldingChanges holds the value and period-over-period changes for a holding metric.

type BrokerHoldingDailyHistory

type BrokerHoldingDailyHistory struct {
	// Daily broker holding records
	List []BrokerHoldingDailyItem
}

BrokerHoldingDailyHistory is the daily holding history for a specific broker.

type BrokerHoldingDailyItem

type BrokerHoldingDailyItem struct {
	// Date in "2026.05.05" format
	Date string
	// Total shares held (nil if not available)
	Holding *decimal.Decimal
	// Holding ratio as a decimal (nil if not available)
	Ratio *decimal.Decimal
	// Change vs previous day (nil if not available)
	Chg *decimal.Decimal
}

BrokerHoldingDailyItem is one day's broker holding record.

type BrokerHoldingDetail

type BrokerHoldingDetail struct {
	// Full list of broker holdings
	List []BrokerHoldingDetailItem
	// Last updated (may be empty if not provided)
	UpdatedAt string
}

BrokerHoldingDetail is the full broker holding detail for a security.

type BrokerHoldingDetailItem

type BrokerHoldingDetailItem struct {
	// Broker name
	Name string
	// Participant number / broker code
	PartiNumber string
	// Holding ratio changes over various periods
	Ratio BrokerHoldingChanges
	// Share count changes over various periods
	Shares BrokerHoldingChanges
	// Whether this is a "strengthening" broker
	Strong bool
}

BrokerHoldingDetailItem is one broker's full holding detail.

type BrokerHoldingEntry

type BrokerHoldingEntry struct {
	// Broker name
	Name string
	// Participant number / broker code
	PartiNumber string
	// Net change in shares held (nil if not available)
	Chg *decimal.Decimal
	// Whether this is a "strengthening" broker
	Strong bool
}

BrokerHoldingEntry is one broker entry in a top-holding list.

type BrokerHoldingPeriod

type BrokerHoldingPeriod int

BrokerHoldingPeriod is the lookback period for broker holding queries.

const (
	// BrokerHoldingPeriodRct1 is the 1-day lookback period.
	BrokerHoldingPeriodRct1 BrokerHoldingPeriod = iota
	// BrokerHoldingPeriodRct5 is the 5-day lookback period.
	BrokerHoldingPeriodRct5
	// BrokerHoldingPeriodRct20 is the 20-day lookback period.
	BrokerHoldingPeriodRct20
	// BrokerHoldingPeriodRct60 is the 60-day lookback period.
	BrokerHoldingPeriodRct60
)

type BrokerHoldingTop

type BrokerHoldingTop struct {
	// Top brokers by net buying
	Buy []BrokerHoldingEntry
	// Top brokers by net selling
	Sell []BrokerHoldingEntry
	// Last updated (may be zero if not provided)
	UpdatedAt string
}

BrokerHoldingTop holds the top broker buy/sell leaders for a security.

type ConstituentStock

type ConstituentStock struct {
	// Security symbol (e.g. "700.HK")
	Symbol string
	// Security name
	Name string
	// Latest price (nil if not available)
	LastDone *decimal.Decimal
	// Previous close (nil if not available)
	PrevClose *decimal.Decimal
	// Net capital inflow today (nil if not available)
	Inflow *decimal.Decimal
	// Turnover amount (nil if not available)
	Balance *decimal.Decimal
	// Trading volume in shares (nil if not available)
	Amount *decimal.Decimal
	// Total shares outstanding (nil if not available)
	TotalShares *decimal.Decimal
	// Tags, e.g. ["领涨龙头"]
	Tags []string
	// Brief description
	Intro string
	// Market, e.g. "HK"
	Market string
	// Circulating shares (nil if not available)
	CirculatingShares *decimal.Decimal
	// Whether this is a delayed quote
	Delay bool
	// Day change percentage (nil if not available)
	Chg *decimal.Decimal
	// Raw trade status code
	TradeStatus int32
}

ConstituentStock is one constituent stock of an index.

type IndexConstituents

type IndexConstituents struct {
	// Number of constituent stocks that fell today
	FallNum int32
	// Number of constituent stocks unchanged today
	FlatNum int32
	// Number of constituent stocks that rose today
	RiseNum int32
	// Constituent stock details
	Stocks []ConstituentStock
}

IndexConstituents holds the constituent stocks for an index.

type MarketContext

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

MarketContext is a client for the Longport Market OpenAPI.

Example:

conf, err := config.NewFromEnv()
mctx, err := market.NewFromCfg(conf)
status, err := mctx.MarketStatus(context.Background())

func NewFromCfg

func NewFromCfg(cfg *config.Config) (*MarketContext, error)

NewFromCfg creates a MarketContext from a *config.Config.

func NewFromEnv

func NewFromEnv() (*MarketContext, error)

NewFromEnv returns a MarketContext configured from environment variables.

func (*MarketContext) AhPremium

func (m *MarketContext) AhPremium(ctx context.Context, symbol string, period AhPremiumPeriod, count uint32) (*AhPremiumKlines, error)

AhPremium returns the A/H premium K-line data for a dual-listed security.

Path: GET /v1/quote/ahpremium/klines

func (*MarketContext) AhPremiumIntraday

func (m *MarketContext) AhPremiumIntraday(ctx context.Context, symbol string) (*AhPremiumIntraday, error)

AhPremiumIntraday returns the A/H premium intraday data for a dual-listed security.

Path: GET /v1/quote/ahpremium/timeshares

func (*MarketContext) Anomaly

func (m *MarketContext) Anomaly(ctx context.Context, market string) (*AnomalyResponse, error)

Anomaly returns market anomaly alerts (unusual price/volume events) for a market.

Path: GET /v1/quote/changes

func (*MarketContext) BrokerHolding

func (m *MarketContext) BrokerHolding(ctx context.Context, symbol string, period BrokerHoldingPeriod) (*BrokerHoldingTop, error)

BrokerHolding returns the top broker holdings (buy/sell leaders) for a security.

Path: GET /v1/quote/broker-holding

func (*MarketContext) BrokerHoldingDaily

func (m *MarketContext) BrokerHoldingDaily(ctx context.Context, symbol string, brokerID string) (*BrokerHoldingDailyHistory, error)

BrokerHoldingDaily returns the daily holding history for a specific broker.

Path: GET /v1/quote/broker-holding/daily

func (*MarketContext) BrokerHoldingDetail

func (m *MarketContext) BrokerHoldingDetail(ctx context.Context, symbol string) (*BrokerHoldingDetail, error)

BrokerHoldingDetail returns the full broker holding details for a security.

Path: GET /v1/quote/broker-holding/detail

func (*MarketContext) Constituent

func (m *MarketContext) Constituent(ctx context.Context, symbol string) (*IndexConstituents, error)

Constituent returns the constituent stocks for an index.

symbol should be an index symbol such as "HSI.HK".

Path: GET /v1/quote/index-constituents

func (*MarketContext) MarketStatus

func (m *MarketContext) MarketStatus(ctx context.Context) (*MarketStatusResponse, error)

MarketStatus returns the current trading status for all markets.

Path: GET /v1/quote/market-status

func (*MarketContext) RankCategories

func (m *MarketContext) RankCategories(ctx context.Context) (*RankCategoriesResponse, error)

RankCategories returns the available rank categories.

Path: GET /v1/quote/market/rank/categories

func (*MarketContext) RankList

func (m *MarketContext) RankList(ctx context.Context, key string, needArticle bool) (*RankListResponse, error)

RankList returns the ranked stock list for a given rank key.

Path: GET /v1/quote/market/rank/list

key is the rank category key returned by RankCategories. needArticle controls whether article content is included in the response.

func (*MarketContext) TopMovers

func (m *MarketContext) TopMovers(ctx context.Context, markets []string, sort uint32, date string, limit uint32) (*TopMoversResponse, error)

TopMovers returns top movers (stocks with unusual price movements) across one or more markets.

Path: POST /v1/quote/market/stock-events

markets is a list of market codes (e.g., ["HK", "US"]). sort controls the sort order (0 = ascending, 1 = descending). date is an optional date filter in "YYYY-MM-DD" format; pass an empty string to omit. limit controls the maximum number of results returned.

func (*MarketContext) TradeStats

func (m *MarketContext) TradeStats(ctx context.Context, symbol string) (*TradeStatsResponse, error)

TradeStats returns buy/sell/neutral trade statistics for a security.

Path: GET /v1/quote/trades-statistics

type MarketStatusResponse

type MarketStatusResponse struct {
	// Per-market trading status items
	MarketTime []MarketTimeItem
}

MarketStatusResponse holds the current trading status for all markets.

type MarketTimeItem

type MarketTimeItem struct {
	// Market code, e.g. "HK", "US", "CN"
	Market string
	// Market trade status. See TradeStatus for the code table.
	TradeStatus TradeStatus
	// Current market time
	Timestamp time.Time
	// Delayed-quote market trade status. See TradeStatus for the code table.
	DelayTradeStatus TradeStatus
	// Delayed-quote market time
	DelayTimestamp time.Time
	// Sub-status code
	SubStatus int32
	// Delayed-quote sub-status code
	DelaySubStatus int32
}

MarketTimeItem is the trading status for one market.

type RankCategoriesResponse

type RankCategoriesResponse struct {
	Data json.RawMessage `json:"data"`
}

RankCategoriesResponse holds the raw data for rank categories from GET /v1/quote/market/rank/categories.

type RankListItem

type RankListItem struct {
	// Symbol — converted from counter_id (e.g. "MU.US")
	Symbol string
	// Code — ticker code (e.g. "MU")
	Code     string
	Name     string
	LastDone string
	// Chg — price change as decimal ratio (e.g. 0.0252 = +2.52%)
	Chg string
	// Change — absolute price change
	Change       string
	Inflow       string
	MarketCap    string
	Industry     string
	PrePostPrice string
	PrePostChg   string
	Amplitude    string
	FiveDayChg   string
	TurnoverRate string
	VolumeRate   string
	PbTtm        string
}

RankListItem is one item in the popularity rank list.

type RankListResponse

type RankListResponse struct {
	Bmp   bool
	Lists []*RankListItem
}

RankListResponse is the response for MarketContext.RankList.

type TopMoversEvent

type TopMoversEvent struct {
	// Timestamp — RFC 3339
	Timestamp   string
	AlertReason string
	AlertType   int64
	Stock       TopMoversStock
	// Post — associated news article (raw JSON, complex structure; nil when no news)
	Post json.RawMessage
}

TopMoversEvent is one top-movers event.

type TopMoversResponse

type TopMoversResponse struct {
	Events []*TopMoversEvent
	// NextParams — pagination cursor; pass to next call to get next page
	NextParams json.RawMessage
}

TopMoversResponse is the response for MarketContext.TopMovers.

type TopMoversStock

type TopMoversStock struct {
	// Symbol — converted from counter_id
	Symbol   string
	Code     string
	Name     string
	FullName string
	Change   string
	LastDone string
	Market   string
	Labels   []string
}

TopMoversStock holds stock info for a top-movers event.

type TradePriceLevel

type TradePriceLevel struct {
	// Buy volume at this price
	BuyAmount decimal.Decimal
	// Neutral (unknown direction) volume at this price
	NeutralAmount decimal.Decimal
	// Price level
	Price decimal.Decimal
	// Sell volume at this price
	SellAmount decimal.Decimal
}

TradePriceLevel holds trade volume at one price level.

type TradeStatistics

type TradeStatistics struct {
	// Volume-weighted average price
	Avgprice decimal.Decimal
	// Total buy volume (shares)
	Buy decimal.Decimal
	// Total neutral / unknown-direction volume
	Neutral decimal.Decimal
	// Previous close price
	Preclose decimal.Decimal
	// Total sell volume (shares)
	Sell decimal.Decimal
	// Data timestamp (unix timestamp string, raw from API)
	Timestamp string
	// Total trading volume (shares)
	TotalAmount decimal.Decimal
	// Unix timestamps for the last N trading days (raw strings)
	TradeDate []string
	// Total number of trades (raw string from API)
	TradesCount string
}

TradeStatistics holds summary buy/sell/neutral trade statistics.

type TradeStatsResponse

type TradeStatsResponse struct {
	// Summary statistics
	Statistics TradeStatistics
	// Per-price-level breakdown
	Trades []TradePriceLevel
}

TradeStatsResponse holds buy/sell/neutral trade statistics for a security.

type TradeStatus

type TradeStatus int32

TradeStatus is a market trading status code returned by /v1/quote/market-status.

const (
	// TradeStatusUnknown is an unknown or unsupported market trading status.
	TradeStatusUnknown TradeStatus = -1
	// TradeStatusNoRegisterQuote means quote is not registered.
	TradeStatusNoRegisterQuote TradeStatus = 0
	// TradeStatusClean is clearing before the market opens.
	TradeStatusClean TradeStatus = 101
	// TradeStatusOpenBid is the opening auction.
	TradeStatusOpenBid TradeStatus = 102
	// TradeStatusMorningClosing is the morning break, currently used by VIX indexes.
	TradeStatusMorningClosing TradeStatus = 103
	// TradeStatusTrading is regular trading.
	TradeStatusTrading TradeStatus = 105
	// TradeStatusNoonClosing is the midday break.
	TradeStatusNoonClosing TradeStatus = 106
	// TradeStatusCloseBid is the closing auction.
	TradeStatusCloseBid TradeStatus = 107
	// TradeStatusClosing means the market is closed.
	TradeStatusClosing TradeStatus = 108
	// TradeStatusDarkWait is dark trading waiting to open.
	TradeStatusDarkWait TradeStatus = 110
	// TradeStatusDarkTrading is dark trading.
	TradeStatusDarkTrading TradeStatus = 111
	// TradeStatusDarkClosing is dark trading closed.
	TradeStatusDarkClosing TradeStatus = 112
	// TradeStatusAfterFix is after-hours fixed-price trading.
	TradeStatusAfterFix TradeStatus = 120
	// TradeStatusHalfClosing is half-day market closed.
	TradeStatusHalfClosing TradeStatus = 121
	// TradeStatusNotOpened means the exchange is waiting to open under special conditions.
	TradeStatusNotOpened TradeStatus = 122
	// TradeStatusRealtimeQuote is a temporary intraday break.
	TradeStatusRealtimeQuote TradeStatus = 123
	// TradeStatusUSPrev is US pre-market.
	TradeStatusUSPrev TradeStatus = 201
	// TradeStatusUSTrading is US regular trading.
	TradeStatusUSTrading TradeStatus = 202
	// TradeStatusUSAfter is US post-market.
	TradeStatusUSAfter TradeStatus = 203
	// TradeStatusUSClosing is US closed.
	TradeStatusUSClosing TradeStatus = 204
	// TradeStatusUSStop is US halted.
	TradeStatusUSStop TradeStatus = 205
	// TradeStatusUSClean is US clearing plus pre-market.
	TradeStatusUSClean TradeStatus = 206
	// TradeStatusUSNight is US overnight trading.
	TradeStatusUSNight TradeStatus = 207
	// TradeStatusUSPrevMarketClean is a US pre-market clearing alias returned by the quote engine.
	TradeStatusUSPrevMarketClean TradeStatus = 209
	// TradeStatusUSAfterMarketClean is a US post-market clearing alias returned by the quote engine.
	TradeStatusUSAfterMarketClean TradeStatus = 210
	// TradeStatusRefresh is stock refresh. It is deprecated in the status definition.
	TradeStatusRefresh TradeStatus = 1000
	// TradeStatusDelist is delisted.
	TradeStatusDelist TradeStatus = 1001
	// TradeStatusPrepare is preparing to list.
	TradeStatusPrepare TradeStatus = 1002
	// TradeStatusCodeChange is code changed.
	TradeStatusCodeChange TradeStatus = 1003
	// TradeStatusStop is halted.
	TradeStatusStop TradeStatus = 1004
	// TradeStatusWillOpen is waiting to open, typically for a US IPO auction.
	TradeStatusWillOpen TradeStatus = 1005
	// TradeStatusCommonSuspend is split or merge suspended.
	TradeStatusCommonSuspend TradeStatus = 1006
	// TradeStatusExpire is expired.
	TradeStatusExpire TradeStatus = 1007
	// TradeStatusNoQuote means no quote data.
	TradeStatusNoQuote TradeStatus = 1008
	// TradeStatusUnited is not listed. The historical variant name is kept for compatibility.
	TradeStatusUnited TradeStatus = 1009
	// TradeStatusTradingHalt is terminated trading, usually for warrants.
	TradeStatusTradingHalt TradeStatus = 1010
	// TradeStatusWaitListing is waiting to list, usually for new warrants.
	TradeStatusWaitListing TradeStatus = 1011
	// TradeStatusFuse is fuse.
	TradeStatusFuse TradeStatus = 2001
)

func TradeStatusFromCode

func TradeStatusFromCode(code int32) TradeStatus

TradeStatusFromCode converts a raw market trading status code to TradeStatus.

func (TradeStatus) AllowTrading

func (s TradeStatus) AllowTrading() bool

AllowTrading reports whether this status allows trading.

func (TradeStatus) Code

func (s TradeStatus) Code() int32

Code returns the raw numeric status code.

func (TradeStatus) IsClosing

func (s TradeStatus) IsClosing() bool

IsClosing reports whether this is a closed status.

func (TradeStatus) IsDark

func (s TradeStatus) IsDark() bool

IsDark reports whether this is a dark-pool status.

func (TradeStatus) IsSpecial

func (s TradeStatus) IsSpecial() bool

IsSpecial reports whether this is a special non-regular status.

func (TradeStatus) IsTrading

func (s TradeStatus) IsTrading() bool

IsTrading reports whether this is a trading status.

func (TradeStatus) IsUSClosing

func (s TradeStatus) IsUSClosing() bool

IsUSClosing reports whether this is a US closed status.

func (TradeStatus) IsUSMarket

func (s TradeStatus) IsUSMarket() bool

IsUSMarket reports whether this is a US market status.

func (TradeStatus) IsUSNight

func (s TradeStatus) IsUSNight() bool

IsUSNight reports whether this is a US overnight status.

func (TradeStatus) IsUSPostMarket

func (s TradeStatus) IsUSPostMarket() bool

IsUSPostMarket reports whether this is a US post-market status.

func (TradeStatus) IsUSPreMarket

func (s TradeStatus) IsUSPreMarket() bool

IsUSPreMarket reports whether this is a US pre-market status.

func (TradeStatus) IsUSPrePost

func (s TradeStatus) IsUSPrePost() bool

IsUSPrePost reports whether this is a US pre/post-market status.

func (TradeStatus) Label

func (s TradeStatus) Label() string

Label returns a simplified label for key display states.

func (TradeStatus) Name

func (s TradeStatus) Name() string

Name returns the full English status name.

func (TradeStatus) Normalize

func (s TradeStatus) Normalize() TradeStatus

Normalize maps quote-engine aliases to their display-equivalent status.

func (TradeStatus) String

func (s TradeStatus) String() string

String returns the full English status name.

func (*TradeStatus) UnmarshalJSON

func (s *TradeStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes numeric market trading status codes.

Directories

Path Synopsis
Package jsontypes holds raw JSON-deserialization structs for the market package.
Package jsontypes holds raw JSON-deserialization structs for the market package.

Jump to

Keyboard shortcuts

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