okx

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

OKX SDK 使用指南与核心概念

本文档旨在介绍 OKX V5 API 的核心概念,帮助开发者快速理解 instId、tdMode 等关键参数,以及如何将通用代币符号(如 BTC)转化为 OKX 可识别的交易代码。

1. 核心概念:产品 ID (Instrument ID - instId)

在 OKX V5 API 中,所有的交易标的(币对、合约)都通过 instId 唯一标识。这是你调用 GetTicker, GetOrderBook, PlaceOrder 等接口时必须传入的参数。

格式规则

OKX 的 instId 遵循特定的命名格式,取决于产品类型:

产品类型 (Product) 格式规则 示例 (Example) 说明
币币 (Spot) 币种-计价货币 BTC-USDT 现货交易,BTC 为币种,USDT 为计价货币。
永续合约 (Swap) 币种-计价货币-SWAP BTC-USDT-SWAP USDT 本位永续合约。
币种-USD-SWAP BTC-USD-SWAP 币本位永续合约 (反向合约)。
交割合约 (Futures) 币种-计价货币-日期 BTC-USDT-250328 USDT 本位交割合约,后6位为到期日(YYMMDD)。
期权 (Option) 币种-USD-日期-行权价-类型 BTC-USD-250328-100000-C BTC 期权,C 代表 Call (看涨),P 代表 Put (看跌)。
常见问题:如何将 "BTC" 转化为 instId?

在程序化交易中,用户通常只输入 "BTC"。你需要根据交易场景来构建 instId。

场景 1:我想买 BTC 现货 你需要确定计价货币(通常是 USDT 或 USDC)。

  • 转化公式: Symbol + - + QuoteCurrency
  • 结果: BTC -> BTC-USDT

场景 2:我想做多 BTC 永续合约 你需要确定是 U 本位 (USDT Margin) 还是 币本位 (Coin Margin)。

  • U 本位转化: Symbol + - + USDT-SWAP -> BTC-USDT-SWAP
  • 币本位转化: Symbol + - + USD-SWAP -> BTC-USD-SWAP

提示: 可以通过 client.GetInstruments(ctx, "SWAP") 获取所有支持的合约列表,建立本地缓存来辅助查找。

2. 核心概念:交易模式 (Trade Mode - tdMode)

下单 (PlaceOrder) 时,tdMode 决定了保证金的使用方式。

  • cash: 非保证金模式 (现货默认)。

    • 仅用于非杠杆的现货交易 (instType=SPOT)。
    • 账户里有多少币就买多少,无爆仓风险。
  • cross: 全仓模式。

    • 保证金由账户内所有资产共享。风险共担。
    • 适用于合约及杠杆交易。
  • isolated: 逐仓模式。

    • 保证金独立于该仓位,亏损仅限于该仓位分配的资金。
    • 下单时较为常用,便于风险控制。

3. 核心概念:持仓方向 (Position Side - posSide)

在合约交易(特别是 双向持仓 模式下)中,必须指定 posSide。

  • long: 开多 / 平多
  • short: 开空 / 平空
  • net: 单向持仓模式 (默认或现货)。
    • 现货交易 (cash) 只有 net 概念(实际上 API 请求时如果不传,默认为买卖币本身)。
    • 如果你的账户配置为“单向持仓模式”,合约也使用 net。

4. 快速开始示例

1. 查询 BTC 价格
// 确定你要查的是现货还是合约
instId := "BTC-USDT" // 现货
// instId := "BTC-USDT-SWAP" // 永续

ticker, err := client.GetTicker(ctx, instId)
fmt.Println("最新价:", ticker[0].Last)
2. 下一笔 BTC 现货买单
req := &okx.OrderRequest{
    InstId:  "BTC-USDT",
    TdMode:  "cash",    // 现货非杠杆一定要用 cash
    Side:    "buy",
    OrdType: "limit",   // 限价单
    Px:      "95000",   // 价格
    Sz:      "0.1",     // 数量 (BTC)
}
resp, err := client.PlaceOrder(ctx, req)
3. 下一笔 BTC 永续合约开多单 (逐仓)
req := &okx.OrderRequest{
    InstId:  "BTC-USDT-SWAP",
    TdMode:  "isolated", // 逐仓
    Side:    "buy",      // 买入
    PosSide: "long",     // 开多 (双向持仓模式必填)
    OrdType: "market",   // 市价单
    Sz:      "1",        // 数量 (张数,注意:合约通常是按"张"计算,1张=0.01 BTC 或 0.001 BTC,需查询 Instrument info)
}
resp, err := client.PlaceOrder(ctx, req)

5. 单位换算注意 (Size/Quantity)

OKX 的数量 (Sz) 含义随产品不同而不同:

  • 现货: 交易币种的数量(例如 1 代表 1 BTC)。
  • 合约: “张” (Contracts)。
    • 你需要通过 GetInstruments 接口查询 ctVal (合约面值) 和 ctMult (乘数)。
    • 例如 BTC-USDT-SWAP,1 张可能等于 0.01 BTC。如果你想开 1 BTC 的仓位,Sz 应该传 100。

6. 进阶概念:产品类型 (instType) vs 交易品种 (instFamily)

在调用 GetTickers 或查询公共数据时,经常会遇到这两个参数。

产品类型 (instType)

这是最顶层的分类,决定了你是在哪个"市场"交易。

  • 常见值:SPOT (现货), SWAP (永续合约), FUTURES (交割合约), OPTION (期权), MARGIN (币币杠杆)。
  • 当你调用接口时,instType 通常是必填项或核心过滤条件。
  • 例子:我想看所有永续合约的行情 -> instType = SWAP
交易品种 (instFamily)

这是在 instType 之下的二级分类,通常指标的资产 (Underlying)。

  • 常见值:BTC-USD (币本位及其合约), BTC-USDT (U本位及其合约), ETH-USD 等。
  • instFamily 将同一标的下的不同到期日合约(如当周、次周、季度)归纳在一起,方便聚合查询。
  • 例子:我想看所有 BTC U本位永续合约 的行情 -> instType = SWAP, instFamily = BTC-USDT

总结区别:

  • instType 决定了玩法(是买现货还是玩合约)。
  • instFamily 决定了标的物(是玩 BTC 还是 ETH)。
  • instId 是最终具体的那个交易对/合约(例如 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"`
}

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"`
	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
}

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 Returns per-hour funding rates (standardized)

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 Returns per-hour funding rate (standardized)

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) 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) 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

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"`          // Per-hour funding rate (standardized)
	FundingIntervalHours int64  `json:"fundingIntervalHours"` // Calculated from time difference
	FundingTime          string `json:"fundingTime"`
	NextFundingTime      string `json:"nextFundingTime"`
}

FundingRateData contains standardized funding rate information

type Instrument

type Instrument struct {
	InstId   string `json:"instId"`
	Uly      string `json:"uly"`
	BaseCcy  string `json:"baseCcy"`
	QuoteCcy string `json:"quoteCcy"`
	SettCcy  string `json:"settCcy"`
	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"`
	State    string `json:"state"`
}

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"`
	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 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"`
	Fee                string          `json:"fee"`
	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"`
	Ts      string  `json:"ts"`
}

type OrderRequest

type OrderRequest struct {
	InstId     string  `json:"instId"`
	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 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 added in v0.2.0

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 added in v0.2.0

func NewWSClient(ctx context.Context) *WSClient

func NewWsClient

func NewWsClient(ctx context.Context) *WSClient

func (*WSClient) AddPendingRequest added in v0.2.0

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

AddPendingRequest adds a channel for a specific ID

func (*WSClient) CancelOrderWS added in v0.2.0

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

CancelOrderWS cancels an order via WebSocket.

func (*WSClient) CancelOrdersWS added in v0.2.0

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

CancelOrdersWS cancels a batch of orders via WebSocket.

func (*WSClient) Connect added in v0.2.0

func (c *WSClient) Connect() error

func (*WSClient) Login added in v0.2.0

func (c *WSClient) Login() error

func (*WSClient) ModifyOrderWS added in v0.2.0

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

ModifyOrderWS amends an order via WebSocket.

func (*WSClient) PlaceOrderWS added in v0.2.0

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

PlaceOrderWS places an order via WebSocket.

func (*WSClient) RemovePendingRequest added in v0.2.0

func (c *WSClient) RemovePendingRequest(id int64)

RemovePendingRequest removes the channel for a specific ID

func (*WSClient) Subscribe added in v0.2.0

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

func (*WSClient) SubscribeOrderBook added in v0.2.0

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

SubscribeOrderBook subscribes to books channel. Default depth is 400

func (*WSClient) SubscribeOrders added in v0.2.0

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

SubscribeOrders subscribes to orders channel.

func (*WSClient) SubscribePositions added in v0.2.0

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

SubscribePositions subscribes to positions channel.

func (*WSClient) SubscribeTicker added in v0.2.0

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

SubscribeTicker subscribes to ticker channel.

func (*WSClient) Unsubscribe added in v0.2.0

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

func (*WSClient) WithCredentials added in v0.2.0

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