api

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2020 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProdBaseURL = "wss://www.deribit.com/ws/api/v2/"
	TestBaseURL = "wss://test.deribit.com/ws/api/v2/"
)

Test and Production URLs

View Source
const (
	BIG           = OneMillion * OneMillion
	Bit           = 100 * Satoshi
	BP            = PCT * PCT // one basis point
	BTC           = "BTC"
	Edp           = "edp"
	ETH           = "ETH"
	HUGE          = BIG * BIG
	OneMillion    = OneThousand * OneThousand
	OneThousand   = 1000
	PCT           = 0.01
	Satoshi       = 1.0 / (100 * OneMillion)
	SecondsInDay  = 3600 * 24
	SecondsInYear = 365 * SecondsInDay
	SMALL         = 1.0 / BIG
	BTCSWAP       = "BTC-PERPETUAL"
	TINY          = 1.0 / HUGE
)

Various constants

View Source
const (
	DrctnBuy  = "buy"
	DrctnSell = "sell"
)

Direction direction, `buy` or `sell`

View Source
const (
	OrdrStateOpen        = "open"
	OrdrStateFilled      = "filled"
	OrdrStateRejected    = "rejected"
	OrdrStateCancelled   = "cancelled"
	OrdrStateTriggered   = "triggered"
	OrdrStateUntriggered = "untriggered"
)

OrderState order state, `"open"`, `"filled"`, `"rejected"`, `"cancelled"`, `"untriggered"`

View Source
const (
	OrdrTypeLmt     = "limit"
	OrdrTypeMkt     = "market"
	OrdrTypeStopLmt = "stop_limit"
	OrdrTypeStopMkt = "stop_market"
)

OrderType order type, `"limit"`, `"market"`, `"stop_limit"`, `"stop_market"`

View Source
const (
	TriggerTypeIdxPrc = "index_price"
	TriggerTypeMrkPrc = "mark_price"
	TriggerTypeLstPrc = "last_price"
)

TriggerType trigger type, `"index_price"`, `"mark_price"`, `"last_price"`

View Source
const BookDepth = 50

BookDepth specifies the book depth for queries

View Source
const MaxTries = 10

MaxTries is the max number of reconnect attempts

View Source
const (
	TmInFrcIOC = "immediate_or_cancel"
)

Variables

View Source
var (
	// ErrAuthRequired is an error value corresponding to authorization
	// being required for a request
	ErrAuthRequired = errors.New("AUTHENTICATION IS REQUIRED")
)
View Source
var TimeZero = time.Date(1970, 1, 1, 0, 0, 0, 0, time.FixedZone("utc", 0))

Functions

func ConvertSymbol

func ConvertSymbol(s string) string

ConvertSymbol converts the exchange contract symbol to one resembling a more traditional format

func Float32Pointer

func Float32Pointer(value float32) *float32

Float32Pointer returns a float32 pointer to value

func Float64Pointer

func Float64Pointer(value float64) *float64

Float64Pointer returns a float64 pointer to value

func InitBook

func InitBook(ob *Book)

InitBook sets Bids and Asks fields

func Int32Pointer

func Int32Pointer(value int32) *int32

Int32Pointer returns an int32 pointer to value

func Int64Pointer

func Int64Pointer(value int64) *int64

Int64Pointer returns an int64 pointer to value

func IntPointer

func IntPointer(value int) *int

IntPointer returns an int pointer to value

func Inverse

func Inverse(x float64) float64

Inverse returns 1/x expect when abs(x) is <= Small in which case it returns +/- Big

func PruneUsrOrdrsFromQuts

func PruneUsrOrdrsFromQuts(quotes []float64, orders *[]inout.Order, maxdiff float64)

PruneUsrOrdrsFromQuts is used to remove user orders from the order book

func StringPointer

func StringPointer(value string) *string

StringPointer returns a string pointer to value

Types

type AccountBalance

type AccountBalance struct {
	Crnt struct {
		Mrkt Balance
		Theo Balance
	}
	Init struct {
		Mrkt Balance
		Theo Balance
	}
}

AccountBalance contains the current and initial mark to market and theoretical account balances in both USD and BTC

type Balance

type Balance struct {
	USD float64
	Ccy float64
}

Balance contains balance data for USD and BTC

type Book

type Book struct {
	Time    time.Time `json:"time"`
	BestBid Quote     `json:"best_bid"`
	BestAsk Quote     `json:"best_ask"`
	Bids    []Quote   `json:"bids"`
	Asks    []Quote   `json:"asks"`
}

Book contains orderbook bids, asks with user orders pruned out

type Client

type Client struct {
	Acct      inout.AcctSummaryOut
	Config    *Configuration
	Logger    *log.Logger
	SG        *syncgrp.SyncGrp
	StartTime time.Time
	Sub       *Subordinate
	// contains filtered or unexported fields
}

Client is the base client for connecting to the exchange

func New

func New(cfg *Configuration) (*Client, error)

New returns pointer to new Client

func NewMinimal

func NewMinimal(cfg *Configuration) (*Client, error)

func (*Client) Auth

func (c *Client) Auth(key string, secret string) (err error)

Auth requests authorization

func (*Client) AutoRefillRqsts

func (c *Client) AutoRefillRqsts()

AutoRefillRqsts automatically refills rate limit if request counts are above certain threshold

func (*Client) Buy

func (c *Client) Buy(params *inout.OrderIn, result *inout.OrderOut) error

Buy posts a buy order to the exchange

func (*Client) Call

func (c *Client) Call(method string, params interface{}, result interface{}) (err error)

Call issues JSONRPC v2 calls

func (*Client) Cancel

func (c *Client) Cancel(oid string, result *inout.Order) error

Cancel submits a cancel request

func (*Client) CancelAll

func (c *Client) CancelAll() (result int, err error)

CancelAll requests to cancel all open orders

func (*Client) CancelAllByCurrency

func (c *Client) CancelAllByCurrency(
	params *inout.CancelAllByCcyIn) (result int, err error)

CancelAllByCurrency requests to cancell all orders for a given currency

func (*Client) CancelAllByInstrument

func (c *Client) CancelAllByInstrument(
	params *inout.CancelAllByInstrmtIn) (result int, err error)

CancelAllByInstrument requests to cancel all orders for a given instrument/contract

func (*Client) Connect

func (c *Client) Connect() (*websocket.Conn, *http.Response, error)

func (*Client) ConvertExchStmp

func (c *Client) ConvertExchStmp(ts int64) time.Time

ConvertExchStmp converts an exchange time stamp to a client-side time.Time

func (*Client) CreateLogger

func (c *Client) CreateLogger() error

func (*Client) DebugPrintf

func (c *Client) DebugPrintf(format string, a ...interface{})

func (*Client) DebugPrintln

func (c *Client) DebugPrintln(a ...interface{})

func (*Client) DisableCancelOnDisconnect

func (c *Client) DisableCancelOnDisconnect() (result string, err error)

func (*Client) DisableHeartbeat

func (c *Client) DisableHeartbeat() (result string, err error)

func (*Client) Done

func (c *Client) Done() chan bool

func (*Client) Edit

func (c *Client) Edit(params *inout.EditIn, result *inout.OrderOut) error

Edit posts an edit request

func (*Client) Emit

func (c *Client) Emit(event interface{}, arguments ...interface{}) *emission.Emitter

Emit emits an event

func (*Client) EnableCancelOnDisconnect

func (c *Client) EnableCancelOnDisconnect() (result string, err error)

func (*Client) Error

func (c *Client) Error() chan error

func (*Client) ExchangeTime

func (c *Client) ExchangeTime() (time.Time, error)

ExchangeTime returns the exchange time as a client-side time.Time

func (*Client) GetAccountSummary

func (c *Client) GetAccountSummary(ccy string, extended bool, result *inout.AcctSummaryOut) error

GetAccountSummary requests "private/get_account_summary"

func (*Client) GetBook

func (c *Client) GetBook(
	contract string, depth int, result *inout.BookOut) error

GetBook returns the order book for a given contract

func (*Client) GetBookSummaryByCurrency

func (c *Client) GetBookSummaryByCurrency(
	params *inout.BkSummaryByCcyIn) (result []inout.BkSummaryOut, err error)

GetBkSummaryByCurrency gets a book summary

func (*Client) GetBookSummaryByInstrument

func (c *Client) GetBookSummaryByInstrument(
	params *inout.BkSummaryByInstrmtIn) (result []inout.BkSummaryOut, err error)

GetBkSummaryByInstrument gets book summary for given instrument

func (*Client) GetContractSize

func (c *Client) GetContractSize(contract string) (float64, error)

GetContractSize gets contract size for an instrument

func (*Client) GetCurrencies

func (c *Client) GetCurrencies() (result []inout.Currency, err error)

GetCurrencies gets spot currencies/indices on exchange

func (*Client) GetHistoricalVolatility added in v1.3.0

func (c *Client) GetHistoricalVolatility(currency string) (vols [][]float64, err error)

GetHistoricalVolatility returns slice of []float64 where each []float64 is of length 2 with the first element being the exchange time stamp and the 2nd the historical vol in percent points as measured at the time stamp

func (*Client) GetIndex

func (c *Client) GetIndex(currency string) (float64, error)

GetIndex returns index value

func (*Client) GetInstruments

func (c *Client) GetInstruments(
	params *inout.InstrumentIn) (result []inout.InstrumentOut, err error)

GetInstruments returns instruments/contracts traded on exchange various related data

func (*Client) GetLastTradesByCurrency

func (c *Client) GetLastTradesByCurrency(
	params *inout.TradesByCcyIn) (result *inout.LastTradesOut, err error)

func (*Client) GetLastTradesByCurrencyAndTime

func (c *Client) GetLastTradesByCurrencyAndTime(
	params *inout.TradesByCcyAndTmIn) (result *inout.LastTradesOut, err error)

func (*Client) GetLastTradesByInstrument

func (c *Client) GetLastTradesByInstrument(
	params *inout.TradesByInstrmtIn) (result *inout.LastTradesOut, err error)

func (*Client) GetLastTradesByInstrumentAndTime

func (c *Client) GetLastTradesByInstrumentAndTime(
	params *inout.TradesByInstrmtAndTmIn) (result *inout.LastTradesOut, err error)

func (*Client) GetOpenOrdersByCurrency

func (c *Client) GetOpenOrdersByCurrency(
	params *inout.OpnOrdrsByCcyIn) (result []inout.Order, err error)

func (*Client) GetOpenOrdersByInstrument

func (c *Client) GetOpenOrdersByInstrument(
	params *inout.OpnOrdrsByInstrmtIn) (result []inout.Order, err error)

func (*Client) GetPositionCurrency

func (c *Client) GetPositionCurrency(
	params *inout.PosnCcyIn) (result []inout.PosnOut, err error)

GetPositionCurrency requests "private/get_positions"

func (*Client) GetPositionInstrument

func (c *Client) GetPositionInstrument(contract string, result *inout.PosnOut) error

GetPositionInstrument requests "private/get_position"

func (*Client) GetStopOrderHistory added in v1.2.0

func (c *Client) GetStopOrderHistory(
	params *inout.StopOrderHistoryIn, result *inout.StopOrderHistoryOut) (err error)

func (*Client) GetTckr

func (c *Client) GetTckr(contract string, result *inout.TckrOut) error

GetTckr gets the ticker data for a given contract

func (*Client) GetTime

func (c *Client) GetTime() (result int64, err error)

GetTime retrieves the exchange server time

func (*Client) GetUserTradesByCurrency

func (c *Client) GetUserTradesByCurrency(
	params *inout.TradesByCcyIn, result *inout.UserTradesOut) error

func (*Client) GetUserTradesByCurrencyAndTime

func (c *Client) GetUserTradesByCurrencyAndTime(
	params *inout.TradesByCcyAndTmIn, result *inout.UserTradesOut) error

func (*Client) GetUserTradesByInstrument

func (c *Client) GetUserTradesByInstrument(
	params *inout.TradesByInstrmtIn, result *inout.UserTradesOut) error

func (*Client) GetUserTradesByInstrumentAndTime

func (c *Client) GetUserTradesByInstrumentAndTime(
	params *inout.TradesByInstrmtAndTmIn, result *inout.UserTradesOut) error

func (*Client) GetUserTradesByInstrumentAndTimeExt added in v1.3.0

func (c *Client) GetUserTradesByInstrumentAndTimeExt(
	instrument string, start, end time.Time) (trades []inout.UserTrade, err error)

func (*Client) Handle

func (c *Client) Handle(
	ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request)

Handle implements jsonrpc2.Handler

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns the WebSocket connection state

func (*Client) IsProduction

func (c *Client) IsProduction() bool

IsProduction returns whether the client is connected to the production server

func (*Client) Logout

func (c *Client) Logout() (err error)

Logout logs out

func (*Client) New

func (c *Client) New(cfg *Configuration) (err error)

func (*Client) NewMinimal

func (c *Client) NewMinimal(cfg *Configuration) (err error)

func (*Client) Off

func (c *Client) Off(event interface{}, listener interface{}) *emission.Emitter

Off removes a listener for an event

func (*Client) On

func (c *Client) On(event interface{}, listener interface{}) *emission.Emitter

On adds a listener to a specific event

func (*Client) PrivateSubscribe

func (c *Client) PrivateSubscribe(
	params *inout.SubscribeIn) (result inout.SubscribeOut, err error)

PrivateSubscribe subscribes to a private channel

func (*Client) PrivateUnsubscribe

func (c *Client) PrivateUnsubscribe(
	params *inout.SubscribeIn) (result inout.SubscribeOut, err error)

PrivateUnsubscribe unsubscribes to a private channel

func (*Client) PublicSubscribe

func (c *Client) PublicSubscribe(
	params *inout.SubscribeIn) (result inout.SubscribeOut, err error)

PublicSubscribe subscribes to a public channel

func (*Client) PublicUnsubscribe

func (c *Client) PublicUnsubscribe(
	params *inout.SubscribeIn) (result inout.SubscribeOut, err error)

PublicUnsubscribe unsubscribes from a public channel

func (*Client) Reconnect

func (c *Client) Reconnect()

func (*Client) RefillRqsts

func (c *Client) RefillRqsts()

RefillRqsts will sleep long enough to refill all rate limits

func (*Client) RefillRqstsCndtnl

func (c *Client) RefillRqstsCndtnl(match int, nonmatch int)

RefillRqstsCndtnl refills requests if request count are above given amounts

func (*Client) RqstCnts

func (c *Client) RqstCnts() (cntMch, cntNon int)

RqstCnts returns the number of requsts accumulated

func (*Client) Sell

func (c *Client) Sell(params *inout.OrderIn, result *inout.OrderOut) error

Sell posts a sell order

func (*Client) SetHeartbeat

func (c *Client) SetHeartbeat(params *inout.Heartbeat) (result string, err error)

func (*Client) Start

func (c *Client) Start() (err error)

func (*Client) SubPblc

func (c *Client) SubPblc(channels []string) ([]string, error)

SubPblc subscribes to given public channels

func (*Client) SubPrvt

func (c *Client) SubPrvt(channels []string) ([]string, error)

SubPrvt subscribes to given private channels

func (*Client) SubmitTransfer

func (c *Client) SubmitTransfer(
	amt string, ccy string, dst int, result *inout.XferSubAcctOut) error

SubmitTransfer posts a transfer request between (sub) accounts

func (*Client) Subscribe

func (c *Client) Subscribe(channels []string, mode SubscribeMode) ([]string, error)

Subscribe subscribes to given channels

func (*Client) SubscribeToChannels

func (c *Client) SubscribeToChannels(channels []string) (e error)

SubscribeToChannels subscribes to channels

func (*Client) Test

func (c *Client) Test() (result inout.TestOut, err error)

Test call "public/test"

func (*Client) Trade

func (c *Client) Trade(params *inout.OrderIn, result *inout.OrderOut) (e error)

Trade posts a buy or sell depending on the sign of amount Buy for positive, sell for negative

func (*Client) UnsubPblc

func (c *Client) UnsubPblc(channels []string) ([]string, error)

UnsubPblc unsubscribes from public channels

func (*Client) UnsubPrvt

func (c *Client) UnsubPrvt(channels []string) ([]string, error)

UnsubPrvt unsubscribes from private channels

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(channels []string, mode SubscribeMode) ([]string, error)

Unsubscribe unsubscribes from given channels

func (*Client) UnsubscribeFromChannels

func (c *Client) UnsubscribeFromChannels(channels []string)

UnsubscribeFromChannels unsubscribes from channels

func (*Client) WaitTime

func (c *Client) WaitTime() time.Duration

type ClientExtended

type ClientExtended struct {
	*Client
	Blnc      AccountBalance
	BkSummary map[string]inout.BkSummaryOut
	Buffer    *bytes.Buffer
	ConSz     map[string]float64
	Contracts []string
	Deltas    map[string]float64
	Filepath  struct {
		Base   string
		Dir    string
		TmStmp time.Time
		Path   string
	}
	Futures     map[string]FuturesData
	Instruments []inout.InstrumentOut
	IsSwap      map[string]bool
	ObAdj       map[string]Book
	ObRaw       map[string]inout.BookOut
	OpnOrdrs    map[string][]inout.Order
	PctDelta    float64
	Posn        map[string]inout.PosnOut
	Spot        float64
	SymbolMap   struct {
		Fwd map[string]string
		Inv map[string]string
	}
	Symbols    []string
	Tckr       map[string]inout.TckrOut
	TckSz      map[string]float64
	TmClnt     time.Time
	TmExch     time.Time
	UserTrades map[string][]inout.UserTrade
}

ClientExtended extendes the base Client

func NewClientExtended

func NewClientExtended(cfg *Configuration) (*ClientExtended, error)

NewClientExtended returns pointer to a new ClientExtended

func NewClientMin

func NewClientMin(cfg *Configuration) (*ClientExtended, error)

NewClientMin makes a pointer to a new ClientExtended with a minimum of initiatialization

func (*ClientExtended) CreateSymbols

func (c *ClientExtended) CreateSymbols()

CreateSymbols creates the Symbols, Contracts and SymbolMap fields

func (*ClientExtended) MakeSubscriptions

func (c *ClientExtended) MakeSubscriptions() []string

MakeSubscriptions makes the slice of channels to subscribe to

func (*ClientExtended) UpdtAcct

func (c *ClientExtended) UpdtAcct() error

UpdtAcct updates account summary

func (*ClientExtended) UpdtBalance

func (c *ClientExtended) UpdtBalance() error

UpdtBalance updates balance in BTC and USD terms

func (*ClientExtended) UpdtBkSummary

func (c *ClientExtended) UpdtBkSummary(contract string) error

UpdtBkSummary updates book summary for contract

func (*ClientExtended) UpdtBookRaw

func (c *ClientExtended) UpdtBookRaw(contract string) (e error)

UpdtBookRaw updates client's copy of order book

func (*ClientExtended) UpdtFutures

func (c *ClientExtended) UpdtFutures() (err error)

UpdtFutures updates futures info map

func (*ClientExtended) UpdtOpnOrdrs

func (c *ClientExtended) UpdtOpnOrdrs(contract string) error

UpdtOpnOrdrs updates the Client's field of open orders

func (*ClientExtended) UpdtOrdrBkAdj

func (c *ClientExtended) UpdtOrdrBkAdj(contract string) error

UpdtOrdrBkAdj updates the order book and prunes user orders

func (*ClientExtended) UpdtPctDelta

func (c *ClientExtended) UpdtPctDelta() error

UpdtPctDelta computes the % delta and updates corresponding field

func (*ClientExtended) UpdtPosition

func (c *ClientExtended) UpdtPosition(contract string) (e error)

UpdtPosition updates the position info for the contract

func (*ClientExtended) UpdtSpot

func (c *ClientExtended) UpdtSpot() (e error)

UpdtSpot updates spot price and corresponding field

func (*ClientExtended) UpdtStatus

func (c *ClientExtended) UpdtStatus() (e error)

UpdtStatus updates most of the client fields

func (*ClientExtended) UpdtTckr

func (c *ClientExtended) UpdtTckr(contract string) (e error)

UpdtTckr updates ticker info for the contract

func (*ClientExtended) UpdtUserTrades

func (c *ClientExtended) UpdtUserTrades(
	contract string, count int) error

UpdtUserTrades updates user trades

type Configuration

type Configuration struct {
	Ctx                context.Context
	Address            string  `json:"address"`
	AutoReconnect      bool    `json:"autoReconnect"`
	AutoRefillMatch    float64 `json:"auto_refill_match"`
	AutoRefillNonmatch float64 `json:"auto_refill_nonmatch"`
	Currency           string  `json:"currency"`
	DebugMode          bool    `json:"debugMode"`
	Key                string  `json:"api_key"`
	Production         bool    `json:"production"`
	Secret             string  `json:"secret_key"`
	UseLogFile         bool    `json:"use_log_file"`
}

Configuration contains data for creating a client

func DfltCnfg

func DfltCnfg() *Configuration

DfltCnfg returns a default Configuration

type Event

type Event struct {
	Channel string          `json:"channel"`
	Data    json.RawMessage `json:"data"`
}

Event is wrapper of received event

type FuturesData

type FuturesData struct {
	inout.InstrumentOut
	TimeToExpiry time.Duration
	IsSwap       bool
}

FuturesData embeds struct inout.InstrumentOut as well as time to expiration and IsSwap

type ObjectStream

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

A ObjectStream is a jsonrpc2.ObjectStream that uses a WebSocket to send and receive JSON-RPC 2.0 objects.

func NewObjectStream

func NewObjectStream(conn *websocket.Conn) ObjectStream

NewObjectStream creates a new jsonrpc2.ObjectStream for sending and receiving JSON-RPC 2.0 objects over a WebSocket.

func (ObjectStream) Close

func (t ObjectStream) Close() error

Close implements jsonrpc2.ObjectStream.

func (ObjectStream) ReadObject

func (t ObjectStream) ReadObject(v interface{}) error

ReadObject implements jsonrpc2.ObjectStream.

func (ObjectStream) WriteObject

func (t ObjectStream) WriteObject(obj interface{}) error

WriteObject implements jsonrpc2.ObjectStream.

type Quote

type Quote struct {
	Prc   float64 `json:"price"`
	Amt   float64 `json:"amount"`
	Drctn string  `json:"direction"`
}

Quote has fields prc, amt and direction corresonding to an order book quote

type Subordinate

type Subordinate struct {
	ChError chan error
	ChDone  chan bool
	Wait    time.Duration
}

func NewSubordinate

func NewSubordinate() *Subordinate

type SubscribeMode

type SubscribeMode bool

SubscribeMode is a bool parametrizing whether a subscription is public or private

const (
	SubPblc SubscribeMode = false
	SubPrvt SubscribeMode = true
)

Enumeration of valid SubscribeMode

type Token

type Token struct {
	AccessToken string `json:"access_token"`
}

Token is used to embedded in params for private methods

Jump to

Keyboard shortcuts

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