okx

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 20 Imported by: 0

README

OKX SDK Guide And Core Concepts

This document introduces the OKX V5 API concepts needed when using github.com/QuantProcessing/exchanges/sdk/okx directly: instId, tdMode, posSide, and the difference between instType, instFamily, and concrete instrument identifiers.

For the Chinese version, see README_CN.md.

Instrument ID (instId)

OKX identifies every tradable instrument with instId. You pass it to calls such as GetTicker, GetOrderBook, and PlaceOrder.

Product Format Example Notes
Spot BASE-QUOTE BTC-USDT BTC spot quoted in USDT.
Swap BASE-QUOTE-SWAP BTC-USDT-SWAP USDT-margined perpetual.
Swap BASE-USD-SWAP BTC-USD-SWAP Coin-margined inverse perpetual.
Futures BASE-QUOTE-YYMMDD BTC-USDT-250328 USDT-margined delivery contract.
Option BASE-USD-YYMMDD-STRIKE-C/P BTC-USD-250328-100000-C BTC option, call or put.

When a user gives only a base symbol such as BTC, construct the final OKX instrument from the trading context:

  • spot BTC/USDT: BTC -> BTC-USDT;
  • USDT-margined BTC perpetual: BTC -> BTC-USDT-SWAP;
  • coin-margined BTC perpetual: BTC -> BTC-USD-SWAP.

Use client.GetInstruments(ctx, "SWAP") or the equivalent product type to build an instrument cache instead of guessing listed markets.

Trade Mode (tdMode)

tdMode controls how margin is used when placing an order.

Value Meaning Typical use
cash Non-margin cash mode Spot orders.
cross Cross margin Margin and derivatives where account collateral is shared.
isolated Isolated margin Position-scoped risk control.

Position Side (posSide)

For derivatives, especially in hedge mode, posSide tells OKX which side of the position the order targets.

Value Meaning
long Open or close the long side.
short Open or close the short side.
net Net-position mode; also the practical default for spot/cash flows.

Quick Examples

Fetch a ticker:

instID := "BTC-USDT" // spot
// instID := "BTC-USDT-SWAP" // perpetual swap

ticker, err := client.GetTicker(ctx, instID)
fmt.Println("last:", ticker[0].Last)

Place a BTC spot limit order:

req := &okx.OrderRequest{
    InstId:  "BTC-USDT",
    TdMode:  "cash",
    Side:    "buy",
    OrdType: "limit",
    Px:      "95000",
    Sz:      "0.1",
}
resp, err := client.PlaceOrder(ctx, req)

Place an isolated BTC perpetual long:

req := &okx.OrderRequest{
    InstId:  "BTC-USDT-SWAP",
    TdMode:  "isolated",
    Side:    "buy",
    PosSide: "long",
    OrdType: "market",
    Sz:      "1",
}
resp, err := client.PlaceOrder(ctx, req)

Size Units

Sz means different things for different OKX products:

  • spot: base asset quantity, for example 1 means 1 BTC;
  • contracts: number of contracts. Query instrument metadata such as ctVal and ctMult before converting a target coin notional into contract size.

instType Versus instFamily

instType selects the market family such as SPOT, SWAP, FUTURES, OPTION, or MARGIN.

instFamily groups related derivative instruments by underlying, such as BTC-USD or BTC-USDT.

instId is the concrete final market, such as BTC-USDT-SWAP.

Documentation

Index

Constants

View Source
const (
	ReadTimeout      = 60 * time.Second
	ReconnectWait    = 5 * time.Second
	WSBaseURL        = "wss://ws.okx.com:8443/ws/v5/public"
	WSPrivateBaseURL = "wss://ws.okx.com:8443/ws/v5/private"
)
View Source
const (
	ArgChannel  = "channel"
	ArgInstId   = "instId"
	ArgInstType = "instType"
)

Common args keys

View Source
const (
	BaseURL = "https://www.okx.com"
)

Variables

This section is empty.

Functions

func Request

func Request[T any](c *Client, ctx context.Context, method Method, path string, payload interface{}, auth bool) ([]T, error)

Request parses the response into a specific type T.

Types

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"msg"`
}

APIError represents an error returned by the OKX API.

func (*APIError) Error

func (e *APIError) Error() string

type AccountConfig

type AccountConfig struct {
	AcctLv              string   `json:"acctLv"`
	AcctStpMode         string   `json:"acctStpMode"`
	AutoLoan            bool     `json:"autoLoan"`
	CtIsoMode           string   `json:"ctIsoMode"`
	EnableSpotBorrow    bool     `json:"enableSpotBorrow"`
	GreeksType          string   `json:"greeksType"`
	FeeType             string   `json:"feeType"`
	Ip                  string   `json:"ip"`
	Type                string   `json:"type"`
	KycLv               string   `json:"kycLv"`
	Label               string   `json:"label"`
	Level               string   `json:"level"`
	LevelTmp            string   `json:"levelTmp"`
	LiquidationGear     string   `json:"liquidationGear"`
	MainUid             string   `json:"mainUid"`
	MgnIsoMode          string   `json:"mgnIsoMode"`
	OpAuth              string   `json:"opAuth"`
	Perm                string   `json:"perm"`
	PosMode             string   `json:"posMode"`
	RoleType            string   `json:"roleType"`
	SpotBorrowAutoRepay bool     `json:"spotBorrowAutoRepay"`
	SpotOffsetType      string   `json:"spotOffsetType"`
	SpotRoleType        string   `json:"spotRoleType"`
	SpotTraderInsts     []string `json:"spotTraderInsts"`
	StgyType            string   `json:"stgyType"`
	TraderInsts         []string `json:"traderInsts"`
	Uid                 string   `json:"uid"`
	SettleCcy           string   `json:"settleCcy"`
	SettleCcyList       []string `json:"settleCcyList"`
}

func (AccountConfig) AccountLevel

func (c AccountConfig) AccountLevel() AccountLevel

type AccountLevel

type AccountLevel string
const (
	AccountLevelUnknown              AccountLevel = ""
	AccountLevelSimple               AccountLevel = "simple"
	AccountLevelSingleCurrencyMargin AccountLevel = "single_currency_margin"
	AccountLevelMultiCurrencyMargin  AccountLevel = "multi_currency_margin"
	AccountLevelPortfolioMargin      AccountLevel = "portfolio_margin"
)

type Announcement

type Announcement struct {
	Title        string `json:"title"`
	URL          string `json:"url"`           // Full URL to announcement
	AnnType      string `json:"annType"`       // Type of announcement
	PublishTime  string `json:"pTime"`         // Timestamp in milliseconds
	BusinessTime string `json:"businessPTime"` // Business timestamp in milliseconds
}

Announcement represents a single announcement detail from OKX API Based on /api/v5/support/announcements response structure

type Balance

type Balance struct {
	AdjEq                 string          `json:"adjEq"`
	AvailEq               string          `json:"availEq"`
	BorrowFroz            string          `json:"borrowFroz"`
	Delta                 string          `json:"delta"`
	DeltaLever            string          `json:"deltaLever"`
	DeltaNeutralStatus    string          `json:"deltaNeutralStatus"`
	Details               []BalanceDetail `json:"details"`
	Imr                   string          `json:"imr"`
	IsoEq                 string          `json:"isoEq"`
	MgnRatio              string          `json:"mgnRatio"`
	Mmr                   string          `json:"mmr"`
	NotionalUsd           string          `json:"notionalUsd"`
	NotionalUsdForBorrow  string          `json:"notionalUsdForBorrow"`
	NotionalUsdForFutures string          `json:"notionalUsdForFutures"`
	NotionalUsdForOption  string          `json:"notionalUsdForOption"`
	NotionalUsdForSwap    string          `json:"notionalUsdForSwap"`
	OrdFroz               string          `json:"ordFroz"`
	TotalEq               string          `json:"totalEq"`
	UTime                 string          `json:"uTime"`
	Upl                   string          `json:"upl"`
}

type BalanceDetail

type BalanceDetail struct {
	AutoLendStatus        string `json:"autoLendStatus"`
	AutoLendMtAmt         string `json:"autoLendMtAmt"`
	AvailBal              string `json:"availBal"`
	AvailEq               string `json:"availEq"`
	BorrowFroz            string `json:"borrowFroz"`
	CashBal               string `json:"cashBal"`
	Ccy                   string `json:"ccy"`
	CrossLiab             string `json:"crossLiab"`
	ColRes                string `json:"colRes"`
	CollateralEnabled     bool   `json:"collateralEnabled"`
	CollateralRestrict    bool   `json:"collateralRestrict"`
	ColBorrAutoConversion string `json:"colBorrAutoConversion"`
	DisEq                 string `json:"disEq"`
	Eq                    string `json:"eq"`
	EqUsd                 string `json:"eqUsd"`
	SmtSyncEq             string `json:"smtSyncEq"`
	SpotCopyTradingEq     string `json:"spotCopyTradingEq"`
	FixedBal              string `json:"fixedBal"`
	FrozenBal             string `json:"frozenBal"`
	FrpType               string `json:"frpType"`
	Imr                   string `json:"imr"`
	Interest              string `json:"interest"`
	IsoEq                 string `json:"isoEq"`
	IsoLiab               string `json:"isoLiab"`
	IsoUpl                string `json:"isoUpl"`
	Liab                  string `json:"liab"`
	MaxLoan               string `json:"maxLoan"`
	MgnRatio              string `json:"mgnRatio"`
	Mmr                   string `json:"mmr"`
	NotionalLever         string `json:"notionalLever"`
	OrdFrozen             string `json:"ordFrozen"`
	RewardBal             string `json:"rewardBal"`
	SpotInUseAmt          string `json:"spotInUseAmt"`
	ClSpotInUseAmt        string `json:"clSpotInUseAmt"`
	MaxSpotInUse          string `json:"maxSpotInUse"`
	SpotIsoBal            string `json:"spotIsoBal"`
	StgyEq                string `json:"stgyEq"`
	Twap                  string `json:"twap"`
	UTime                 string `json:"uTime"`
	Upl                   string `json:"upl"`
	UplLiab               string `json:"uplLiab"`
	SpotBal               string `json:"spotBal"`
	OpenAvgPx             string `json:"openAvgPx"`
	AccAvgPx              string `json:"accAvgPx"`
	SpotUpl               string `json:"spotUpl"`
	SpotUplRatio          string `json:"spotUplRatio"`
	TotalPnl              string `json:"totalPnl"`
	TotalPnlRatio         string `json:"totalPnlRatio"`
}

type BaseResponse

type BaseResponse[T any] struct {
	Code    string `json:"code"`
	Message string `json:"msg"`
	Data    []T    `json:"data"`
}

BaseResponse is the standard response wrapper for OKX API. generic type T allows flexible data parsing.

type CancelOrderRequest

type CancelOrderRequest struct {
	InstId     string  `json:"instId"`
	InstIdCode *int64  `json:"instIdCode,omitempty"`
	OrdId      *string `json:"ordId,omitempty"`
	ClOrdId    *string `json:"clOrdId,omitempty"`
}

type Candle

type Candle [9]string

[0] ts [1] open [2] high [3] low [4] close [5] volume size [6] volume ccy [7] volume ccy quote [8] confirm: 0 (not finish) or 1 (finish)

type Client

type Client struct {
	ApiKey     string
	SecretKey  string
	Passphrase string

	HTTPClient *http.Client
	Signer     *Signer

	// BaseURL overrides the default OKX base URL. Used in tests to point at
	// an httptest server. Leave empty to use the package-level BaseURL constant.
	BaseURL string
}

func NewClient

func NewClient() *Client

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, instId, ordId, clOrdId string) ([]OrderId, error)

CancelOrder cancels an incomplete order.

func (*Client) CancelOrders

func (c *Client) CancelOrders(ctx context.Context, reqs []CancelOrderRequest) ([]OrderId, error)

CancelOrders cancels multiple orders (max 20).

func (*Client) ClosePosition

func (c *Client) ClosePosition(ctx context.Context, instId, mgnMode string) ([]ClosePosition, error)

ClosePosition closes a position.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method Method, path string, payload interface{}, auth bool) ([]byte, error)

Do executes a generic HTTP request and returns the raw response body. It handles authentication signatures if auth is required.

func (*Client) GetAccountBalance

func (c *Client) GetAccountBalance(ctx context.Context, ccy *string) ([]Balance, error)

GetAccountBalance retrieves the account balance. ccy: optional, comma-separated list of currencies (e.g. "BTC,ETH")

func (*Client) GetAccountConfig

func (c *Client) GetAccountConfig(ctx context.Context) ([]AccountConfig, error)

GetAccountConfig retrieves the account configuration.

func (*Client) GetAllFundingRates

func (c *Client) GetAllFundingRates(ctx context.Context) ([]FundingRateData, error)

GetAllFundingRates retrieves funding rates for all instruments. FundingRate is the venue settlement-interval rate; HourlyFundingRate is derived.

func (*Client) GetAnnouncements

func (c *Client) GetAnnouncements(ctx context.Context, annType string) ([]Announcement, error)

GetAnnouncements returns a list of announcements. annType: Announcement type (optional) page: Page number (optional, default 1)

func (*Client) GetCandles

func (c *Client) GetCandles(ctx context.Context, instId string, bar *string, after *string, before *string, limit *int) ([]Candle, error)

GetCandles retrieves candles for a specific instrument. bar: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h limit: default 100, max 300

func (*Client) GetFundingRate

func (c *Client) GetFundingRate(ctx context.Context, instId string) (*FundingRateData, error)

GetFundingRate retrieves the current funding rate for a specific instrument. FundingRate is the venue settlement-interval rate; HourlyFundingRate is derived.

func (*Client) GetFundingRateHistory

func (c *Client) GetFundingRateHistory(ctx context.Context, instId string, beforeMillis, afterMillis int64, limit int) ([]FundingRateHistoryEntry, error)

GetFundingRateHistory retrieves historical funding rates. beforeMillis / afterMillis are optional OKX timestamp cursors (pass 0 to omit). OKX `before` = newer than timestamp; `after` = older than timestamp. limit is capped at 100 by OKX; zero means exchange default. Docs: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate-history

func (*Client) GetHistoryTrades

func (c *Client) GetHistoryTrades(ctx context.Context, instId string, typ int, before, after string, limit int) ([]HistoryTrade, error)

GetHistoryTrades returns paginated historical public trades. typ is OKX's pagination mode: 1=by tradeId, 2=by timestamp. before/after are cursors; either may be empty. Docs: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-trades-history

func (*Client) GetInstruments

func (c *Client) GetInstruments(ctx context.Context, instType string) ([]Instrument, error)

GetInstruments retrieves instruments information. instType: SPOT, SWAP, FUTURES, OPTION, MARGIN

func (*Client) GetInstrumentsByFamily

func (c *Client) GetInstrumentsByFamily(ctx context.Context, instType, instFamily string) ([]Instrument, error)

GetInstrumentsByFamily retrieves instruments for products, such as options, that require an instrument family.

func (*Client) GetOpenInterest

func (c *Client) GetOpenInterest(ctx context.Context, instId string) (*OpenInterest, error)

GetOpenInterest returns the current open interest for a single instrument. Docs: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-open-interest

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, instId, ordId, clOrdId string) ([]Order, error)

GetOrder retrieves order details.

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(ctx context.Context, instId string, sz *int) ([]OrderBook, error)

GetOrderBook retrieves order book depth. sz: depth size, e.g. 400

func (*Client) GetOrders

func (c *Client) GetOrders(ctx context.Context, instType, instId *string) ([]Order, error)

GetOrders retrieves pending orders. instType: SPOT, MARGIN, SWAP, FUTURES, OPTION instId: optional, Instrument ID

func (*Client) GetPositions

func (c *Client) GetPositions(ctx context.Context, instType, instId *string) ([]Position, error)

GetPositions retrieves the account positions. instId: optional, instrument ID posType: optional, position type

func (*Client) GetTicker

func (c *Client) GetTicker(ctx context.Context, instId string) ([]Ticker, error)

GetTicker retrieves the ticker for a specific instrument.

func (*Client) GetTickers

func (c *Client) GetTickers(ctx context.Context, instType string, instFamily *string) ([]Ticker, error)

GetTickers retrieves the tickers for a specific instrument type and family.

func (*Client) GetTradeFee

func (c *Client) GetTradeFee(ctx context.Context, instType string, instId *string) ([]TradeFee, error)

GetTradeFee retrieves the trade fee rates. instType: SPOT, MARGIN, SWAP, FUTURES, OPTION instId: instrument ID

func (*Client) GetTrades

func (c *Client) GetTrades(ctx context.Context, instId string, limit *int) ([]PublicTrade, error)

GetTrades retrieves recent public trades for an instrument.

func (*Client) ModifyOrder

func (c *Client) ModifyOrder(ctx context.Context, req *ModifyOrderRequest) ([]OrderId, error)

ModifyOrder amends an incomplete order.

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(ctx context.Context, req *OrderRequest) ([]OrderId, error)

PlaceOrder submits a new order.

func (*Client) SetLeverage

func (c *Client) SetLeverage(ctx context.Context, params SetLeverage) ([]SetLeverage, error)

SetLeverage sets the leverage. instId: instrument ID lever: leverage mgnMode: isolated or cross

func (*Client) SetPositionMode

func (c *Client) SetPositionMode(ctx context.Context, posMode string) ([]PositionMode, error)

SetPositionMode sets the position mode. posMode: long_short_mode or net_mode(for perp and option)

func (*Client) WithCredentials

func (c *Client) WithCredentials(apiKey, secretKey, passphrase string) *Client

func (*Client) WithHTTPClient

func (c *Client) WithHTTPClient(httpClient *http.Client) *Client

type ClosePosition

type ClosePosition struct {
	ClOrdId string `json:"clOrdId"`
	InstId  string `json:"instId"`
	PosSide string `json:"posSide"`
	Tag     string `json:"tag"`
}

type Environment

type Environment string

Environment type

const (
	Production Environment = "0"
	Simulated  Environment = "1"
)

type FeeGroup

type FeeGroup struct {
	GroupId string `json:"groupId"`
	Maker   string `json:"maker"`
	Taker   string `json:"taker"`
}

type FundingRate

type FundingRate struct {
	InstrumentType  string `json:"instType"`
	InstrumentID    string `json:"instId"`
	FundingRate     string `json:"fundingRate"`
	NextFundingRate string `json:"nextFundingRate"`
	FundingTime     string `json:"fundingTime"`
	NextFundingTime string `json:"nextFundingTime"`
	Premium         string `json:"premium"`
	SettFundingRate string `json:"settFundingRate"`
	SettState       string `json:"settState"`
	Ts              string `json:"ts"`
}

type FundingRateData

type FundingRateData struct {
	Symbol               string `json:"symbol"`
	FundingRate          string `json:"fundingRate"`          // Rate for the settlement interval returned by the venue.
	HourlyFundingRate    string `json:"hourlyFundingRate"`    // Derived FundingRate / FundingIntervalHours.
	FundingIntervalHours int64  `json:"fundingIntervalHours"` // Calculated from time difference.
	FundingTime          string `json:"fundingTime"`
	NextFundingTime      string `json:"nextFundingTime"`
}

FundingRateData contains funding rate information with venue and derived units.

type FundingRateHistoryEntry

type FundingRateHistoryEntry struct {
	InstType     string `json:"instType"`
	InstId       string `json:"instId"`
	FundingRate  string `json:"fundingRate"`
	RealizedRate string `json:"realizedRate"`
	FundingTime  string `json:"fundingTime"`
	Method       string `json:"method"`
}

FundingRateHistoryEntry matches one element of /api/v5/public/funding-rate-history.

type HistoryTrade

type HistoryTrade struct {
	InstId  string `json:"instId"`
	TradeId string `json:"tradeId"`
	Px      string `json:"px"`
	Sz      string `json:"sz"`
	Side    string `json:"side"`
	Ts      string `json:"ts"`
}

HistoryTrade matches one element of /api/v5/market/history-trades.

type Instrument

type Instrument struct {
	InstId            string   `json:"instId"`
	GroupId           string   `json:"groupId"`
	Uly               string   `json:"uly"`
	InstFamily        string   `json:"instFamily"`
	BaseCcy           string   `json:"baseCcy"`
	QuoteCcy          string   `json:"quoteCcy"`
	TradeQuoteCcyList []string `json:"tradeQuoteCcyList"`
	SettCcy           string   `json:"settCcy"`
	SettleCcy         string   `json:"settleCcy"`
	CtVal             string   `json:"ctVal"`
	CtMult            string   `json:"ctMult"`
	CtValCcy          string   `json:"ctValCcy"`
	OptType           string   `json:"optType"`
	Stk               string   `json:"stk"`
	ListTime          string   `json:"listTime"`
	ExpTime           string   `json:"expTime"`
	Leverage          string   `json:"leverage"`
	TickSz            string   `json:"tickSz"`
	LotSz             string   `json:"lotSz"`
	MinSz             string   `json:"minSz"`
	InstType          string   `json:"instType"`
	RuleType          string   `json:"ruleType"`
	State             string   `json:"state"`
	InstIdCode        *int64   `json:"instIdCode"`
	InstCategory      string   `json:"instCategory"`
}

type LinkedAlgoOrder

type LinkedAlgoOrder struct {
	AlgoId string `json:"algoId"`
}

type Method

type Method string

Method represents HTTP methods

const (
	MethodGet  Method = "GET"
	MethodPost Method = "POST"
)

type MgnMode

type MgnMode string
const (
	MgnModeCross    MgnMode = "cross"
	MgnModeIsolated MgnMode = "isolated"
	MgnModeCash     MgnMode = "cash"
)

type ModifyOrderRequest

type ModifyOrderRequest struct {
	InstId     string  `json:"instId"`
	InstIdCode *int64  `json:"instIdCode,omitempty"`
	OrdId      *string `json:"ordId,omitempty"`
	ClOrdId    *string `json:"clOrdId,omitempty"`
	NewSz      *string `json:"newSz,omitempty"`
	NewPx      *string `json:"newPx,omitempty"`
	CxlOnFail  *bool   `json:"cxlOnFail,omitempty"`
	ReqId      *string `json:"reqId,omitempty"`
}

type OpenInterest

type OpenInterest struct {
	InstType string `json:"instType"`
	InstId   string `json:"instId"`
	OI       string `json:"oi"`              // open interest in contracts
	OICcy    string `json:"oiCcy"`           // OI in coin (base asset)
	OIUsd    string `json:"oiUsd,omitempty"` // OI in USD
	Ts       string `json:"ts"`
}

OpenInterest matches one element of /api/v5/public/open-interest's data array.

type Order

type Order struct {
	AccFillSz          string          `json:"accFillSz"`
	AlgoClOrdId        string          `json:"algoClOrdId"`
	AlgoId             string          `json:"algoId"`
	AttachAlgoClOrdId  string          `json:"attachAlgoClOrdId"`
	AttachAlgoOrds     []int           `json:"attachAlgoOrds"`
	AvgPx              string          `json:"avgPx"`
	CTime              string          `json:"cTime"`
	CancelSource       string          `json:"cancelSource"`
	CancelSourceReason string          `json:"cancelSourceReason"`
	Category           string          `json:"category"`
	Ccy                string          `json:"ccy"`
	ClOrdId            string          `json:"clOrdId"`
	ExecType           string          `json:"execType"`
	Fee                string          `json:"fee"`
	FeeCcy             string          `json:"feeCcy"`
	FillPx             string          `json:"fillPx"`
	FillSz             string          `json:"fillSz"`
	FillTime           string          `json:"fillTime"`
	InstId             string          `json:"instId"`
	InstType           string          `json:"instType"`
	IsTpLimit          string          `json:"isTpLimit"`
	Lever              string          `json:"lever"`
	LinkedAlgoOrder    LinkedAlgoOrder `json:"linkedAlgoOrder"`
	OrdId              string          `json:"ordId"`
	OrdType            OrderType       `json:"ordType"`
	Pnl                string          `json:"pnl"`
	PosSide            PosSide         `json:"posSide"`
	Px                 string          `json:"px"`
	PxType             string          `json:"pxType"`
	PxUsd              string          `json:"pxUsd"`
	PxVol              string          `json:"pxVol"`
	QuickMgnType       string          `json:"quickMgnType"`
	Rebate             string          `json:"rebate"`
	RebateCcy          string          `json:"rebateCcy"`
	ReduceOnly         string          `json:"reduceOnly"`
	Side               Side            `json:"side"`
	SlOrdPx            string          `json:"slOrdPx"`
	SlTriggerPx        string          `json:"slTriggerPx"`
	SlTriggerPxType    string          `json:"slTriggerPxType"`
	Source             string          `json:"source"`
	State              OrderStatus     `json:"state"`
	StpId              string          `json:"stpId"`
	StpMode            string          `json:"stpMode"`
	Sz                 string          `json:"sz"`
	Tag                string          `json:"tag"`
	TdMode             TdMode          `json:"tdMode"`
	TgtCcy             string          `json:"tgtCcy"`
	TpOrdPx            string          `json:"tpOrdPx"`
	TpTriggerPx        string          `json:"tpTriggerPx"`
	TpTriggerPxType    string          `json:"tpTriggerPxType"`
	TradeId            string          `json:"tradeId"`
	TradeQuoteCcy      string          `json:"tradeQuoteCcy"`
	UTime              string          `json:"uTime"`
}

type OrderBook

type OrderBook struct {
	Asks [][]string `json:"asks"` // [price, size, trash, numOrders]
	Bids [][]string `json:"bids"`
	Ts   string     `json:"ts"`
}

type OrderId

type OrderId struct {
	OrdId   string  `json:"ordId"`
	ClOrdId string  `json:"clOrdId"`
	Tag     *string `json:"tag,omitempty"`
	SCode   string  `json:"sCode"`
	SMsg    string  `json:"sMsg"`
	SubCode string  `json:"subCode,omitempty"`
	Ts      string  `json:"ts"`
}

type OrderRequest

type OrderRequest struct {
	InstId     string  `json:"instId"`
	InstIdCode *int64  `json:"instIdCode,omitempty"`
	TdMode     string  `json:"tdMode"` // cross, isolated, cash (spot)
	ClOrdId    *string `json:"clOrdId,omitempty"`
	Side       string  `json:"side"`              // buy, sell
	PosSide    *string `json:"posSide,omitempty"` // long, short, net (required for long/short mode)
	OrdType    string  `json:"ordType"`           // market, limit, etc.
	Sz         string  `json:"sz"`
	Px         *string `json:"px,omitempty"`
	Ccy        *string `json:"ccy,omitempty"`
	TgtCcy     *string `json:"tgtCcy,omitempty"`
	Tag        *string `json:"tag,omitempty"`
	ReduceOnly *bool   `json:"reduceOnly,omitempty"`
}

type OrderStatus

type OrderStatus string
const (
	OrderStatusLive            OrderStatus = "live"
	OrderStatusPartiallyFilled OrderStatus = "partially_filled"
	OrderStatusFilled          OrderStatus = "filled"
	OrderStatusCanceled        OrderStatus = "canceled"
	OrderStatusMmpCanceled     OrderStatus = "mmp_canceled" // 做市商保护机制的自动撤单
)

type OrderType

type OrderType string
const (
	OrderTypeLimit           OrderType = "limit"
	OrderTypeMarket          OrderType = "market"
	OrderTypePostOnly        OrderType = "post_only"
	OrderTypeFok             OrderType = "fok"
	OrderTypeIoc             OrderType = "ioc"
	OrderTypeOptimalLimitIoc OrderType = "optimal_limit_ioc"
)

type PendingRequest

type PendingRequest struct {
	Success chan []byte
	Error   chan []byte
}

PendingRequest holds channels for success and error responses

type PosSide

type PosSide string
const (
	PosSideLong  PosSide = "long"
	PosSideShort PosSide = "short"
	PosSideNet   PosSide = "net" // 在单向持仓模式下填这个
)

type Position

type Position struct {
	Adl                    string        `json:"adl"`
	AvailPos               string        `json:"availPos"`
	AvgPx                  string        `json:"avgPx"`
	BaseBal                string        `json:"baseBal"`
	BaseBorrowed           string        `json:"baseBorrowed"`
	BaseInterest           string        `json:"baseInterest"`
	BePx                   string        `json:"bePx"`
	BizRefId               string        `json:"bizRefId"`
	BizRefType             string        `json:"bizRefType"`
	CTime                  string        `json:"cTime"`
	Ccy                    string        `json:"ccy"`
	ClSpotInUseAmt         string        `json:"clSpotInUseAmt"`
	CloseOrderAlgo         []interface{} `json:"closeOrderAlgo"`
	DeltaBS                string        `json:"deltaBS"`
	DeltaPA                string        `json:"deltaPA"`
	Fee                    string        `json:"fee"`
	FundingFee             string        `json:"fundingFee"`
	GammaBS                string        `json:"gammaBS"`
	GammaPA                string        `json:"gammaPA"`
	HedgedPos              string        `json:"hedgedPos"`
	IdxPx                  string        `json:"idxPx"`
	Imr                    string        `json:"imr"`
	InstId                 string        `json:"instId"`
	InstType               string        `json:"instType"`
	Interest               string        `json:"interest"`
	Last                   string        `json:"last"`
	Lever                  string        `json:"lever"`
	Liab                   string        `json:"liab"`
	LiabCcy                string        `json:"liabCcy"`
	LiqPenalty             string        `json:"liqPenalty"`
	LiqPx                  string        `json:"liqPx"`
	Margin                 string        `json:"margin"`
	MarkPx                 string        `json:"markPx"`
	MaxSpotInUseAmt        string        `json:"maxSpotInUseAmt"`
	MgnMode                MgnMode       `json:"mgnMode"`
	MgnRatio               string        `json:"mgnRatio"`
	Mmr                    string        `json:"mmr"`
	NotionalUsd            string        `json:"notionalUsd"`
	OptVal                 string        `json:"optVal"`
	PendingCloseOrdLiabVal string        `json:"pendingCloseOrdLiabVal"`
	Pnl                    string        `json:"pnl"`
	Pos                    string        `json:"pos"`
	PosCcy                 string        `json:"posCcy"`
	PosId                  string        `json:"posId"`
	PosSide                PosSide       `json:"posSide"`
	QuoteBal               string        `json:"quoteBal"`
	QuoteBorrowed          string        `json:"quoteBorrowed"`
	QuoteInterest          string        `json:"quoteInterest"`
	RealizedPnl            string        `json:"realizedPnl"`
	SpotInUseAmt           string        `json:"spotInUseAmt"`
	SpotInUseCcy           string        `json:"spotInUseCcy"`
	ThetaBS                string        `json:"thetaBS"`
	ThetaPA                string        `json:"thetaPA"`
	TradeId                string        `json:"tradeId"`
	UTime                  string        `json:"uTime"`
	Upl                    string        `json:"upl"`
	UplLastPx              string        `json:"uplLastPx"`
	UplRatio               string        `json:"uplRatio"`
	UplRatioLastPx         string        `json:"uplRatioLastPx"`
	UsdPx                  string        `json:"usdPx"`
	VegaBS                 string        `json:"vegaBS"`
	VegaPA                 string        `json:"vegaPA"`
	NonSettleAvgPx         string        `json:"nonSettleAvgPx"`
	SettledPnl             string        `json:"settledPnl"`
}

type PositionMode

type PositionMode struct {
	PosMode string `json:"posMode"`
}

type PublicTrade

type PublicTrade struct {
	InstId  string `json:"instId"`
	TradeId string `json:"tradeId"`
	Px      string `json:"px"`
	Sz      string `json:"sz"`
	Side    string `json:"side"`
	Ts      string `json:"ts"`
}

type SetLeverage

type SetLeverage struct {
	Lever   int    `json:"lever"`
	MgnMode string `json:"mgnMode"`
	InstId  string `json:"instId"`
	PosSide string `json:"posSide"`
}

type Side

type Side string
const (
	SideBuy  Side = "buy"
	SideSell Side = "sell"
)

type Signer

type Signer struct {
	SecretKey string
}

Signer handles OKX API signature generation.

func NewSigner

func NewSigner(secretKey string) *Signer

func (*Signer) SignRequest

func (s *Signer) SignRequest(req *http.Request, method, path, body string, apiKey, passphrase string)

SignRequest adds necessary authentication headers to the request. OKX requires: OK-ACCESS-KEY OK-ACCESS-SIGN OK-ACCESS-TIMESTAMP OK-ACCESS-PASSPHRASE OK-ACCESS-SIMULATED-TRADING (if demo)

type TdMode

type TdMode string // 交易模式
const (
	TdModeCross    TdMode = "cross"
	TdModeIsolated TdMode = "isolated"
	TdModeCash     TdMode = "cash"
)

type Ticker

type Ticker struct {
	InstType  string `json:"instType"`
	InstId    string `json:"instId"`
	Last      string `json:"last"`
	LastSz    string `json:"lastSz"`
	AskPx     string `json:"askPx"`
	AskSz     string `json:"askSz"`
	BidPx     string `json:"bidPx"`
	BidSz     string `json:"bidSz"`
	Open24h   string `json:"open24h"`
	High24h   string `json:"high24h"`
	Low24h    string `json:"low24h"`
	VolCcy24h string `json:"volCcy24h"` // base volume, 以币为单位
	Vol24h    string `json:"vol24h"`    // not quote, 张数
	Ts        string `json:"ts"`
	SodUtc0   string `json:"sodUtc0"`
	SodUtc8   string `json:"sodUtc8"`
}

type TradeFee

type TradeFee struct {
	Category  string     `json:"category"`
	InstType  string     `json:"instType"`
	FeeGroups []FeeGroup `json:"feeGroup"`
	Ts        string     `json:"ts"`
}

type WSClient

type WSClient struct {
	Conn *websocket.Conn

	WriteMu     sync.Mutex
	IsPrivate   bool
	URL         string
	ApiKey      string
	SecretKey   string
	Passphrase  string
	Subs        map[WsSubscribeArgs]func([]byte)
	PendingReqs map[int64]*PendingRequest
	Dialer      *websocket.Dialer

	Connected chan bool // for private connection
	Logger    *zap.SugaredLogger
	// contains filtered or unexported fields
}

func NewWSClient

func NewWSClient(ctx context.Context) *WSClient

func NewWsClient

func NewWsClient(ctx context.Context) *WSClient

func (*WSClient) AddPendingRequest

func (c *WSClient) AddPendingRequest(id int64) (chan []byte, chan []byte)

AddPendingRequest adds a channel for a specific ID

func (*WSClient) CancelOrderWS

func (c *WSClient) CancelOrderWS(instIdCode int64, ordId, clOrdId *string) (*OrderId, error)

CancelOrderWS cancels an order via WebSocket.

func (*WSClient) CancelOrdersWS

func (c *WSClient) CancelOrdersWS(reqs []CancelOrderRequest) ([]OrderId, error)

CancelOrdersWS cancels a batch of orders via WebSocket.

func (*WSClient) Connect

func (c *WSClient) Connect() error

func (*WSClient) Login

func (c *WSClient) Login() error

func (*WSClient) ModifyOrderWS

func (c *WSClient) ModifyOrderWS(req *ModifyOrderRequest) (*OrderId, error)

ModifyOrderWS amends an order via WebSocket.

func (*WSClient) PlaceOrderWS

func (c *WSClient) PlaceOrderWS(req *OrderRequest) (*OrderId, error)

PlaceOrderWS places an order via WebSocket.

func (*WSClient) RemovePendingRequest

func (c *WSClient) RemovePendingRequest(id int64)

RemovePendingRequest removes the channel for a specific ID

func (*WSClient) Subscribe

func (c *WSClient) Subscribe(args WsSubscribeArgs, handler func(data []byte)) error

func (*WSClient) SubscribeCandles

func (c *WSClient) SubscribeCandles(instId string, channel string, handler func(Candle)) error

SubscribeCandles subscribes to a public candle channel such as candle1m.

func (*WSClient) SubscribeOrderBook

func (c *WSClient) SubscribeOrderBook(instId string, handler func(*OrderBook, string)) error

SubscribeOrderBook subscribes to books channel. Default depth is 400

func (*WSClient) SubscribeOrders

func (c *WSClient) SubscribeOrders(instType string, instId *string, handler func(*Order)) error

SubscribeOrders subscribes to orders channel.

func (*WSClient) SubscribePositions

func (c *WSClient) SubscribePositions(instType string, handler func(*Position)) error

SubscribePositions subscribes to positions channel.

func (*WSClient) SubscribeTicker

func (c *WSClient) SubscribeTicker(instId string, handler func(*Ticker)) error

SubscribeTicker subscribes to ticker channel.

func (*WSClient) SubscribeTrades

func (c *WSClient) SubscribeTrades(instId string, handler func(*PublicTrade)) error

SubscribeTrades subscribes to public trades channel.

func (*WSClient) Unsubscribe

func (c *WSClient) Unsubscribe(args WsSubscribeArgs) error

func (*WSClient) WithCredentials

func (c *WSClient) WithCredentials(apiKey, secretKey, passphrase string) *WSClient

type WsClient

type WsClient = WSClient

type WsEvent

type WsEvent struct {
	Event string `json:"event"`
	Code  string `json:"code"`
	Msg   string `json:"msg"`
}

WsEvent represents standard websocket event messages (login, subscribe).

type WsOrderData

type WsOrderData struct {
	// Reusing OrderDetails from types.go if possible or defining new
	// OKX WS Order push structure is very similar to REST
	Order
}

WsOrder push data structure is same as OrderDetails

type WsOrderOp

type WsOrderOp struct {
	Id   string        `json:"id"` // Request ID
	Op   string        `json:"op"` // "order", "batch-orders", "cancel-order", "batch-cancel-orders"
	Args []interface{} `json:"args"`
}

WsOrderRequest represents the structure for placing/cancelling orders via WS.

type WsPositionData

type WsPositionData struct {
	Position
}

WsPosition push data

type WsPushData

type WsPushData[T any] struct {
	Arg    map[string]string `json:"arg"`
	Data   []T               `json:"data"`
	Action string            `json:"action,omitempty"` // for order updates: snapshot/update? Actually OKX doesn't use action field much for orders but for depth.
}

WsPushData generic struct for pushed data.

type WsSubscribeArgs

type WsSubscribeArgs struct {
	Channel  string `json:"channel"`
	InstType string `json:"instType,omitempty"`
	InstId   string `json:"instId,omitempty"`
}

WsSubscribeReq is used for subscribe requests

type WsSubscribeRes

type WsSubscribeRes struct {
	// request/response map by id
	ID    *string          `json:"id,omitempty"`
	Event *string          `json:"event,omitempty"`
	Arg   *WsSubscribeArgs `json:"arg,omitempty"`
	// if code not nil, throw error
	Code *string `json:"code,omitempty"`
	Msg  *string `json:"msg,omitempty"`
	// push data
	Data *json.RawMessage `json:"data,omitempty"`
}

WsSubscribeRes is used for subscribe responses

Jump to

Keyboard shortcuts

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