okex

package
v1.63.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2025 License: AGPL-3.0 Imports: 22 Imported by: 2

Documentation

Overview

Code generated by go generate; DO NOT EDIT.

Index

Constants

View Source
const (
	ID = "okex"

	// PlatformToken is the platform currency of OKEx, pre-allocate static string here
	PlatformToken = "OKB"
)

Variables

View Source
var (
	// below are supported UTC timezone interval for okex
	SupportedIntervals = map[types.Interval]int{
		types.Interval1m:  1 * 60,
		types.Interval3m:  3 * 60,
		types.Interval5m:  5 * 60,
		types.Interval15m: 15 * 60,
		types.Interval30m: 30 * 60,
		types.Interval1h:  60 * 60,
		types.Interval2h:  60 * 60 * 2,
		types.Interval4h:  60 * 60 * 4,
		types.Interval6h:  60 * 60 * 6,
		types.Interval12h: 60 * 60 * 12,
		types.Interval1d:  60 * 60 * 24,
		types.Interval3d:  60 * 60 * 24 * 3,
		types.Interval1w:  60 * 60 * 24 * 7,
		types.Interval1mo: 60 * 60 * 24 * 30,
	}

	ToLocalInterval = map[types.Interval]string{
		types.Interval1m:  "1m",
		types.Interval3m:  "3m",
		types.Interval5m:  "5m",
		types.Interval15m: "15m",
		types.Interval30m: "30m",
		types.Interval1h:  "1H",
		types.Interval2h:  "2H",
		types.Interval4h:  "4H",
		types.Interval6h:  "6Hutc",
		types.Interval12h: "12Hutc",
		types.Interval1d:  "1Dutc",
		types.Interval3d:  "3Dutc",
		types.Interval1w:  "1Wutc",
		types.Interval1mo: "1Mutc",
	}
)
View Source
var CandleChannels = []string{
	"candle1Y",
	"candle6M", "candle3M", "candle1M",
	"candle1W",
	"candle1D", "candle2D", "candle3D", "candle5D",
	"candle12H", "candle6H", "candle4H", "candle2H", "candle1H",
	"candle30m", "candle15m", "candle5m", "candle3m", "candle1m",
}
View Source
var ErrSymbolRequired = errors.New("symbol is a required parameter")

Functions

This section is empty.

Types

type ActionType added in v1.56.0

type ActionType string
const (
	ActionTypeSnapshot ActionType = "snapshot"
	ActionTypeUpdate   ActionType = "update"
)

type BookEvent added in v1.23.0

type BookEvent struct {
	InstrumentID string
	Symbol       string
	Action       ActionType

	Data []struct {
		Bids                 PriceVolumeOrderSlice      `json:"bids"`
		Asks                 PriceVolumeOrderSlice      `json:"asks"`
		MillisecondTimestamp types.MillisecondTimestamp `json:"ts"`
		Checksum             int                        `json:"checksum"`
	}
	// contains filtered or unexported fields
}

func (*BookEvent) Book added in v1.23.0

func (event *BookEvent) Book() types.SliceOrderBook

func (*BookEvent) BookTicker added in v1.23.0

func (event *BookEvent) BookTicker() types.BookTicker

type Channel added in v1.56.0

type Channel string
const (
	// books: 400 depth levels will be pushed in the initial full snapshot.
	// Incremental data will be pushed every 100 ms for the changes in the order book during that period of time.
	ChannelBooks Channel = "books"

	// ChannelBooks5 is books5
	// 5 depth levels snapshot will be pushed every time.
	// Snapshot data will be pushed every 100 ms when there are changes in the 5 depth levels snapshot.
	ChannelBooks5 Channel = "books5"

	// ChannelBooks50 is books50-l2-tbt:
	// 50 depth levels will be pushed in the initial full snapshot.
	// Incremental data will be pushed every 10 ms for the changes in the order book during that period of time.
	ChannelBooks50 Channel = "books50-l2-tbt"

	// ChannelBooks1 is bbo-tbt
	// 1 depth level snapshot will be pushed every time.
	// Snapshot data will be pushed every 10 ms when there are changes in the 1 depth level snapshot.
	ChannelBooks1 Channel = "bbo-tbt"

	ChannelCandlePrefix Channel = "candle"
	ChannelAccount      Channel = "account"
	ChannelMarketTrades Channel = "trades"
	ChannelOrderTrades  Channel = "orders"
)

type ConnectionInfoEvent added in v1.60.0

type ConnectionInfoEvent struct {
	Event     string  `json:"event"`
	Channel   Channel `json:"channel"`
	ConnCount string  `json:"connCount"`
	ConnId    string  `json:"connId"`
}

type Exchange

type Exchange struct {
	types.MarginSettings
	types.FuturesSettings
	// contains filtered or unexported fields
}

func New

func New(key, secret, passphrase string, opts ...Option) *Exchange

func (*Exchange) BorrowMarginAsset added in v1.62.0

func (e *Exchange) BorrowMarginAsset(ctx context.Context, asset string, amount fixedpoint.Value) error

func (*Exchange) CancelOrders

func (e *Exchange) CancelOrders(ctx context.Context, orders ...types.Order) error

func (*Exchange) GetClient added in v1.62.0

func (e *Exchange) GetClient() *okexapi.RestClient

func (*Exchange) IsSupportedInterval added in v1.53.0

func (e *Exchange) IsSupportedInterval(interval types.Interval) bool

func (*Exchange) Name

func (e *Exchange) Name() types.ExchangeName

func (*Exchange) NewStream

func (e *Exchange) NewStream() types.Stream

func (*Exchange) PlatformFeeCurrency

func (e *Exchange) PlatformFeeCurrency() string

func (*Exchange) QueryAccount

func (e *Exchange) QueryAccount(ctx context.Context) (*types.Account, error)

func (*Exchange) QueryAccountBalances

func (e *Exchange) QueryAccountBalances(ctx context.Context) (types.BalanceMap, error)

func (*Exchange) QueryClosedOrders added in v1.53.0

func (e *Exchange) QueryClosedOrders(
	ctx context.Context, symbol string, since, until time.Time, lastOrderID uint64,
) (orders []types.Order, err error)

QueryClosedOrders can query closed orders in last 3 months, there are no time interval limitations, as long as until >= since. Please Use lastOrderID as cursor, only return orders later than that order, that order is not included. If you want to query all orders within a large time range (e.g. total orders > 100), we recommend using batch.ClosedOrderBatchQuery.

** since and until are inclusive, you can include the lastTradeId as well. **

func (*Exchange) QueryDepositHistory added in v1.62.0

func (e *Exchange) QueryDepositHistory(
	ctx context.Context, asset string, startTime, endTime *time.Time,
) ([]types.Deposit, error)

func (*Exchange) QueryFuturesAccount added in v1.62.0

func (e *Exchange) QueryFuturesAccount(ctx context.Context) (*types.Account, error)

func (*Exchange) QueryInterestHistory added in v1.62.0

func (e *Exchange) QueryInterestHistory(
	ctx context.Context, asset string, startTime, endTime *time.Time,
) ([]types.MarginInterest, error)

func (*Exchange) QueryKLines

func (e *Exchange) QueryKLines(
	ctx context.Context, symbol string, interval types.Interval, options types.KLineQueryOptions,
) ([]types.KLine, error)

func (*Exchange) QueryLiquidationHistory added in v1.62.0

func (e *Exchange) QueryLiquidationHistory(
	ctx context.Context, startTime, endTime *time.Time,
) ([]types.MarginLiquidation, error)

func (*Exchange) QueryLoanHistory added in v1.62.0

func (e *Exchange) QueryLoanHistory(
	ctx context.Context, asset string, startTime, endTime *time.Time,
) ([]types.MarginLoan, error)

func (*Exchange) QueryMarginAssetMaxBorrowable added in v1.62.0

func (e *Exchange) QueryMarginAssetMaxBorrowable(ctx context.Context, asset string) (fixedpoint.Value, error)

func (*Exchange) QueryMarkets

func (e *Exchange) QueryMarkets(ctx context.Context) (types.MarketMap, error)

func (*Exchange) QueryOpenOrders

func (e *Exchange) QueryOpenOrders(ctx context.Context, symbol string) (orders []types.Order, err error)

QueryOpenOrders retrieves the pending orders. The data returned is ordered by createdTime, and we utilized the `After` parameter to acquire all orders.

func (*Exchange) QueryOrder added in v1.52.0

func (e *Exchange) QueryOrder(ctx context.Context, q types.OrderQuery) (*types.Order, error)

func (*Exchange) QueryOrderTrades added in v1.52.0

func (e *Exchange) QueryOrderTrades(ctx context.Context, q types.OrderQuery) (trades []types.Trade, err error)

QueryOrderTrades quires order trades can query trades in last 3 days.

func (*Exchange) QueryPositionRisk added in v1.63.0

func (e *Exchange) QueryPositionRisk(ctx context.Context, symbol ...string) ([]types.PositionRisk, error)

func (*Exchange) QueryRepayHistory added in v1.62.0

func (e *Exchange) QueryRepayHistory(
	ctx context.Context, asset string, startTime, endTime *time.Time,
) ([]types.MarginRepay, error)

func (*Exchange) QueryTicker

func (e *Exchange) QueryTicker(ctx context.Context, symbol string) (*types.Ticker, error)

func (*Exchange) QueryTickers

func (e *Exchange) QueryTickers(ctx context.Context, symbols ...string) (map[string]types.Ticker, error)

func (*Exchange) QueryTrades added in v1.53.0

func (e *Exchange) QueryTrades(
	ctx context.Context, symbol string, options *types.TradeQueryOptions,
) (trades []types.Trade, err error)

QueryTrades can query trades in last 3 months, there are no time interval limitations, as long as end_time >= start_time. okx does not provide an API to query by trade ID, so we use the bill ID to do it. The trades result is ordered by timestamp.

REMARK: If your start time is 90 days earlier, we will update it to now - 90 days. ** StartTime and EndTime are inclusive. ** ** StartTime and EndTime cannot exceed 90 days. ** ** StartTime, EndTime, FromTradeId can be used together. **

If you want to query all trades within a large time range (e.g. total orders > 100), we recommend using batch.TradeBatchQuery. We don't support the last trade id as a filter because okx supports bill ID only.

func (*Exchange) RepayMarginAsset added in v1.62.0

func (e *Exchange) RepayMarginAsset(ctx context.Context, asset string, amount fixedpoint.Value) error

func (*Exchange) SetLeverage added in v1.63.0

func (e *Exchange) SetLeverage(ctx context.Context, symbol string, leverage int) error

func (*Exchange) SubmitOrder added in v1.40.3

func (e *Exchange) SubmitOrder(ctx context.Context, order types.SubmitOrder) (*types.Order, error)

Market order behaviors under different account mode:

OKX Spot mode: - Market order + TradeModeCash + TargetCurrencyBase ✅ (order history shows the order under "Spot") - Market order + TradeModeCash + TargetCurrencyQuote ✅ (order history shows the order under "Spot") - Market order + TradeModeCross + TargetCurrencyBase ❌ (You can't complete this request under your current account mode) - Market order + TradeModeCross + TargetCurrencyQuote ❌ (You can't complete this request under your current account mode) OKX Spot & Futures mode: - Market order + TradeModeCash + TargetCurrencyBase ✅ (fallback to Spot mode, order history shows the order under "Spot") - Market order + TradeModeCash + TargetCurrencyQuote ✅ (order history shows the order under "Spot") - Market order + TradeModeCross + TargetCurrencyBase ❌ (The instrument corresponding to this BTC-USDT does not support the tgtCcy parameter) - Market order + TradeModeCross + CurrencyQuote=USDT ✅ (order history shows the order under "Margin")

This affects the behavior of syncing order history.

Under OKX’s margin mode (specifically spot & futures mode), it’s possible to place orders using the cash mode. However, if you try to query order history using the margin mode, you won’t be able to find those orders placed via cash mode, because they’re categorized under “Spot”.

When using OKX margin, it seems that operating in Spot mode is generally easier—mainly because market orders can specify size using the base currency instead of the quote.

That said, when syncing, we’ll need a workaround to handle this edge case: the query for order history should be forced to use “spot” instead of “margin”.

func (*Exchange) SupportedInterval added in v1.53.0

func (e *Exchange) SupportedInterval() map[types.Interval]int

type KLineEvent added in v1.56.0

type KLineEvent struct {
	Events okexapi.KLineSlice

	InstrumentID string
	Symbol       string
	Interval     string
	Channel      Channel
}

type KLineStream added in v1.57.0

type KLineStream struct {
	types.StandardStream
	// contains filtered or unexported fields
}

func NewKLineStream added in v1.57.0

func NewKLineStream(exchange *Exchange) *KLineStream

func (*KLineStream) Connect added in v1.57.0

func (s *KLineStream) Connect(ctx context.Context) error

func (*KLineStream) EmitKLineEvent added in v1.57.0

func (K *KLineStream) EmitKLineEvent(candle KLineEvent)

func (*KLineStream) OnKLineEvent added in v1.57.0

func (K *KLineStream) OnKLineEvent(cb func(candle KLineEvent))

func (*KLineStream) Unsubscribe added in v1.57.0

func (s *KLineStream) Unsubscribe()

type KLineStreamEventHub added in v1.57.0

type KLineStreamEventHub interface {
	OnKLineEvent(cb func(candle KLineEvent))
}

type MarketTradeEvent added in v1.56.0

type MarketTradeEvent struct {
	InstId    string                     `json:"instId"`
	TradeId   strint.Int64               `json:"tradeId"`
	Px        fixedpoint.Value           `json:"px"`
	Sz        fixedpoint.Value           `json:"sz"`
	Side      okexapi.SideType           `json:"side"`
	Timestamp types.MillisecondTimestamp `json:"ts"`
	Count     strint.Int64               `json:"count"`
}

type Option added in v1.61.0

type Option func(exchange *Exchange)

func WithBrokerId added in v1.61.0

func WithBrokerId(id string) Option

type OrderTradeEvent added in v1.56.0

type OrderTradeEvent struct {
	okexapi.OrderDetail

	Code          strint.Int64          `json:"code"`
	Msg           string                `json:"msg"`
	AmendResult   string                `json:"amendResult"`
	ExecutionType okexapi.LiquidityType `json:"execType"`

	// FillFee last filled fee amount or rebate amount:
	// Negative number represents the user transaction fee charged by the platform;
	// Positive number represents rebate
	FillFee fixedpoint.Value `json:"fillFee"`

	// FillFeeCurrency last filled fee currency or rebate currency.
	// It is fee currency when fillFee is less than 0; It is rebate currency when fillFee>=0.
	FillFeeCurrency string `json:"fillFeeCcy"`

	// FillNotionalUsd Filled notional value in USD of order
	FillNotionalUsd fixedpoint.Value `json:"fillNotionalUsd"`
	FillPnl         fixedpoint.Value `json:"fillPnl"`

	// NotionalUsd Estimated national value in USD of order
	NotionalUsd fixedpoint.Value `json:"notionalUsd"`

	// ReqId Client Request ID as assigned by the client for order amendment. "" will be returned if there is no order amendment.
	ReqId     string           `json:"reqId"`
	LastPrice fixedpoint.Value `json:"lastPx"`

	// QuickMgnType Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
	// manual, auto_borrow, auto_repay
	QuickMgnType string `json:"quickMgnType"`

	// AmendSource Source of the order amendation.
	AmendSource string `json:"amendSource"`
	// CancelSource Source of the order cancellation.
	CancelSource string `json:"cancelSource"`

	// Only applicable to options; return "" for other instrument types
	FillPriceVolume string `json:"fillPxVol"`
	FillPriceUsd    string `json:"fillPxUsd"`
	FillMarkVolume  string `json:"fillMarkVol"`
	FillFwdPrice    string `json:"fillFwdPx"`
	FillMarkPrice   string `json:"fillMarkPx"`
}

type PriceVolumeOrder added in v1.56.0

type PriceVolumeOrder struct {
	types.PriceVolume
	// NumLiquidated is part of a deprecated feature and it is always "0"
	NumLiquidated int
	// NumOrders is the number of orders at the price.
	NumOrders int
}

type PriceVolumeOrderSlice added in v1.56.0

type PriceVolumeOrderSlice []PriceVolumeOrder

func ParsePriceVolumeOrderSliceJSON added in v1.56.0

func ParsePriceVolumeOrderSliceJSON(b []byte) (slice PriceVolumeOrderSlice, err error)

ParsePriceVolumeOrderSliceJSON tries to parse a 2 dimensional string array into a PriceVolumeOrderSlice

[["8476.98", "415", "0", "13"], ["8477", "7", "0", "2"], ... ]

func (*PriceVolumeOrderSlice) UnmarshalJSON added in v1.56.0

func (slice *PriceVolumeOrderSlice) UnmarshalJSON(b []byte) error

type Stream

type Stream struct {
	types.StandardStream
	// contains filtered or unexported fields
}

func NewStream

func NewStream(client *okexapi.RestClient, exchange *Exchange) *Stream

func (*Stream) Connect

func (s *Stream) Connect(ctx context.Context) error

func (*Stream) EmitAccountEvent added in v1.23.0

func (s *Stream) EmitAccountEvent(account okexapi.Account)

func (*Stream) EmitBookEvent added in v1.23.0

func (s *Stream) EmitBookEvent(book BookEvent)

func (*Stream) EmitKLineEvent added in v1.56.0

func (s *Stream) EmitKLineEvent(candle KLineEvent)

func (*Stream) EmitMarketTradeEvent added in v1.56.0

func (s *Stream) EmitMarketTradeEvent(tradeDetail []MarketTradeEvent)

func (*Stream) EmitOrderTradesEvent added in v1.56.0

func (s *Stream) EmitOrderTradesEvent(orderTrades []OrderTradeEvent)

func (*Stream) OnAccountEvent added in v1.23.0

func (s *Stream) OnAccountEvent(cb func(account okexapi.Account))

func (*Stream) OnBookEvent added in v1.23.0

func (s *Stream) OnBookEvent(cb func(book BookEvent))

func (*Stream) OnKLineEvent added in v1.56.0

func (s *Stream) OnKLineEvent(cb func(candle KLineEvent))

func (*Stream) OnMarketTradeEvent added in v1.56.0

func (s *Stream) OnMarketTradeEvent(cb func(tradeDetail []MarketTradeEvent))

func (*Stream) OnOrderTradesEvent added in v1.56.0

func (s *Stream) OnOrderTradesEvent(cb func(orderTrades []OrderTradeEvent))

func (*Stream) Subscribe added in v1.57.0

func (s *Stream) Subscribe(channel types.Channel, symbol string, options types.SubscribeOptions)

func (*Stream) Unsubscribe added in v1.56.0

func (s *Stream) Unsubscribe()

type StreamEventHub

type StreamEventHub interface {
	OnKLineEvent(cb func(candle KLineEvent))

	OnBookEvent(cb func(book BookEvent))

	OnAccountEvent(cb func(account okexapi.Account))

	OnOrderTradesEvent(cb func(orderTrades []OrderTradeEvent))

	OnMarketTradeEvent(cb func(tradeDetail []MarketTradeEvent))
}

type WebSocketEvent

type WebSocketEvent struct {
	Event   WsEventType `json:"event"`
	Code    string      `json:"code,omitempty"`
	Message string      `json:"msg,omitempty"`
	Arg     struct {
		Channel Channel `json:"channel"`
		InstId  string  `json:"instId"`
	} `json:"arg,omitempty"`
	Data       json.RawMessage `json:"data"`
	ActionType ActionType      `json:"action"`
	Channel    Channel         `json:"channel"`
	ConnCount  string          `json:"connCount"`
}

func (*WebSocketEvent) IsAuthenticated added in v1.56.0

func (w *WebSocketEvent) IsAuthenticated() bool

func (*WebSocketEvent) IsValid added in v1.56.0

func (w *WebSocketEvent) IsValid() error

type WebsocketLogin

type WebsocketLogin struct {
	Key        string `json:"apiKey"`
	Passphrase string `json:"passphrase"`
	Timestamp  string `json:"timestamp"`
	Sign       string `json:"sign"`
}

type WebsocketOp

type WebsocketOp struct {
	Op   WsEventType `json:"op"`
	Args interface{} `json:"args"`
}

type WebsocketSubscription

type WebsocketSubscription struct {
	Channel        Channel `json:"channel"`
	InstrumentID   string  `json:"instId,omitempty"`
	InstrumentType string  `json:"instType,omitempty"`
}

type WsEventType added in v1.56.0

type WsEventType string
const (
	WsEventTypeLogin           WsEventType = "login"
	WsEventTypeError           WsEventType = "error"
	WsEventTypeSubscribe       WsEventType = "subscribe"
	WsEventTypeUnsubscribe     WsEventType = "unsubscribe"
	WsEventTypeConnectionInfo  WsEventType = "channel-conn-count"
	WsEventTypeConnectionError WsEventType = "channel-conn-count-error"
	WsEventTypeNotice          WsEventType = "notice"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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