deribit

package
v0.0.0-...-ae86ed1 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2022 License: MIT Imports: 31 Imported by: 0

README

GoCryptoTrader package Deribit

Build Status Software License GoDoc Coverage Status Go Report Card

This deribit package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Exmo Exchange

Current Features
  • REST Support
  • Websocket Support
  • FIX Support
How to enable
  // Exchanges will be abstracted out in further updates and examples will be
  // supplied then
How to do REST public/private calls
  • If enabled via "configuration".json file the exchange will be added to the IBotExchange array in the go var bot Bot and you will only be able to use the wrapper interface functions for accessing exchange data. View routines.go for an example of integration usage with GoCryptoTrader. Rudimentary example below:

main.go

var d exchange.IBotExchange

for i := range bot.Exchanges {
  if bot.Exchanges[i].GetName() == "Deribit" {
    d = bot.Exchanges[i]
  }
}

// Public calls - wrapper functions

// Fetches current ticker information
tick, err := d.FetchTicker()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := d.FetchOrderbook()
if err != nil {
  // Handle error
}

// Private calls - wrapper functions - make sure your APIKEY and APISECRET are
// set and AuthenticatedAPISupport is set to true

// Fetches current account information
accountInfo, err := d.GetAccountInfo()
if err != nil {
  // Handle error
}
  • If enabled via individually importing package, rudimentary example below:
// Public calls

// Fetches current ticker information
ticker, err := d.GetTicker()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := d.GetOrderBook()
if err != nil {
  // Handle error
}

// Private calls - make sure your APIKEY and APISECRET are set and
// AuthenticatedAPISupport is set to true

// GetUserInfo returns account info
accountInfo, err := d.GetUserInfo(...)
if err != nil {
  // Handle error
}

// Submits an order and the exchange and returns its tradeID
tradeID, err := d.Trade(...)
if err != nil {
  // Handle error
}
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

View Source
const (

	// Public endpoints
	PublicAuth                             = "/public/auth"
	PublicExchangeToken                    = "/public/exchange_token"
	PublicForkToken                        = "/public/fork_token"
	PublicSetHeartbeat                     = "/public/set_heartbeat"
	PublicDisableHeartbeat                 = "/public/disable_heartbeat"
	PublicGetTime                          = "/public/get_time"
	PublicHello                            = "/public/hello"
	PublicTest                             = "/public/test"
	PublicSubscribe                        = "/public/subscribe"
	PublicUnsubscribe                      = "/public/unsubscribe"
	PublicGetAnnouncements                 = "/public/get_announcements"
	PublicGetBookSummaryByCurrency         = "/public/get_book_summary_by_currency"
	PublicGetBookSummaryByInstrument       = "/public/get_book_summary_by_instrument"
	PublicGetContractSize                  = "/public/get_contract_size"
	PublicGetCurrencies                    = "/public/get_currencies"
	PublicGetFundingChartData              = "/public/get_funding_chart_data"
	PublicGetFundingRateHistory            = "/public/get_funding_rate_history"
	PublicGetFundingRateValue              = "/public/get_funding_rate_value"
	PublicGetHistoricalVolatility          = "/public/get_historical_volatility"
	PublicGetIndex                         = "/public/get_index"
	PublicGetInstruments                   = "/public/get_instruments"
	PublicGetLastSettlementsByCurrency     = "/public/get_last_settlements_by_currency"
	PublicGetLastSettlementsByInstrument   = "/public/get_last_settlements_by_instrument"
	PublicGetLastTradesByCurrency          = "/public/get_last_trades_by_currency"
	PublicGetLastTradesByCurrencyAndTime   = "/public/get_last_trades_by_currency_and_time"
	PublicGetLastTradesByInstrument        = "/public/get_last_trades_by_instrument"
	PublicGetLastTradesByInstrumentAndTime = "/public/get_last_trades_by_instrument_and_time"
	PublicGetOrderBook                     = "/public/get_order_book"
	PublicGetTradeVolumes                  = "/public/get_trade_volumes"
	PublicGetTradingviewChartData          = "/public/get_tradingview_chart_data"
	PublicTicker                           = "/public/ticker"

	// Authenticated endpoints
	PrivateLogout                            = "/private/logout"
	PrivateEnableCancelOnDisconnect          = "/private/enable_cancel_on_disconnect"
	PrivateDisableCancelOnDisconnect         = "/private/disable_cancel_on_disconnect"
	PrivateGetCancelOnDisconnect             = "/private/get_cancel_on_disconnect"
	PrivateSubscribe                         = "/private/subscribe"
	PrivateUnsubscribe                       = "/private/unsubscribe"
	PrivateChangeApiKeyName                  = "/private/change_api_key_name"
	PrivateChangeScopeInApiKey               = "/private/change_scope_in_api_key"
	PrivateChangeSubaccountName              = "/private/change_subaccount_name"
	PrivateCreateApiKey                      = "/private/create_api_key"
	PrivateCreateSubaccount                  = "/private/create_subaccount"
	PrivateDisableApiKey                     = "/private/disable_api_key"
	PrivateDisableTfaForSubaccount           = "/private/disable_tfa_for_subaccount"
	PrivateEnableAffiliateProgram            = "/private/enable_affiliate_program"
	PrivateEnableApiKey                      = "/private/enable_api_key"
	PrivateGetAccountSummary                 = "/private/get_account_summary"
	PrivateGetAffiliateProgramInfo           = "/private/get_affiliate_program_info"
	PrivateGetEmailLanguage                  = "/private/get_email_language"
	PrivateGetNewAnnouncements               = "/private/get_new_announcements"
	PrivateGetPosition                       = "/private/get_position"
	PrivateGetPositions                      = "/private/get_positions"
	PrivateGetSubaccounts                    = "/private/get_subaccounts"
	PrivateListApiKeys                       = "/private/list_api_keys"
	PrivateRemoveApiKey                      = "/private/remove_api_key"
	PrivateRemoveSubaccount                  = "/private/remove_subaccount"
	PrivateResetApiKey                       = "/private/reset_api_key"
	PrivateSetAnnouncementAsRead             = "/private/set_announcement_as_read"
	PrivateSetApiKeyAsDefault                = "/private/set_api_key_as_default"
	PrivateSetEmailForSubaccount             = "/private/set_email_for_subaccount"
	PrivateSetEmailLanguage                  = "/private/set_email_language"
	PrivateSetPasswordForSubaccount          = "/private/set_password_for_subaccount"
	PrivateToggleNotificationsFromSubaccount = "/private/toggle_notifications_from_subaccount"
	PrivateToggleSubaccountLogin             = "/private/toggle_subaccount_login"
	PrivateExecuteBlockTrade                 = "/private/execute_block_trade"
	PrivateGetBlockTrade                     = "/private/get_block_trade"
	PrivateGetLastBlockTradesByCurrency      = "/private/get_last_block_trades_by_currency"
	PrivateInvalidateBlockTradeSignature     = "/private/invalidate_block_trade_signature"
	PrivateVerifyBlockTrade                  = "/private/verify_block_trade"
	PrivateBuy                               = "/private/buy"
	PrivateSell                              = "/private/sell"
	PrivateEdit                              = "/private/edit"
	PrivateCancel                            = "/private/cancel"
	PrivateCancelAll                         = "/private/cancel_all"
	PrivateCancelAllByCurrency               = "/private/cancel_all_by_currency"
	PrivateCancelAllByInstrument             = "/private/cancel_all_by_instrument"
	PrivateCancelByLabel                     = "/private/cancel_by_label"
	PrivateClosePosition                     = "/private/close_position"
	PrivateGetMargins                        = "/private/get_margins"
	PrivateGetMmpConfig                      = "/private/get_mmp_config"
	PrivateGetOpenOrdersByCurrency           = "/private/get_open_orders_by_currency"
	PrivateGetOpenOrdersByInstrument         = "/private/get_open_orders_by_instrument"
	PrivateGetOrderHistoryByCurrency         = "/private/get_order_history_by_currency"
	PrivateGetOrderHistoryByInstrument       = "/private/get_order_history_by_instrument"
	PrivateGetOrderMarginByIds               = "/private/get_order_margin_by_ids"
	PrivateGetOrderState                     = "/private/get_order_state"
	PrivateGetStopOrderHistory               = "/private/get_stop_order_history"
	PrivateGetUserTradesByCurrency           = "/private/get_user_trades_by_currency"
	PrivateGetUserTradesByCurrencyAndTime    = "/private/get_user_trades_by_currency_and_time"
	PrivateGetUserTradesByInstrument         = "/private/get_user_trades_by_instrument"
	PrivateGetUserTradesByInstrumentAndTime  = "/private/get_user_trades_by_instrument_and_time"
	PrivateGetUserTradesByOrder              = "/private/get_user_trades_by_order"
	PrivateResetMmp                          = "/private/reset_mmp"
	PrivateSetMmpConfig                      = "/private/set_mmp_config"
	PrivateGetSettlementHistoryByInstrument  = "/private/get_settlement_history_by_instrument"
	PrivateGetSettlementHistoryByCurrency    = "/private/get_settlement_history_by_currency"
	PrivateCancelTransferById                = "/private/cancel_transfer_by_id"
	PrivateCancelWithdrawal                  = "/private/cancel_withdrawal"
	PrivateCreateDepositAddress              = "/private/create_deposit_address"
	PrivateGetCurrentDepositAddress          = "/private/get_current_deposit_address"
	PrivateGetDeposits                       = "/private/get_deposits"
	PrivateGetTransfers                      = "/private/get_transfers"
	PrivateGetWithdrawals                    = "/private/get_withdrawals"
	PrivateSubmitTransferToSubaccount        = "/private/submit_transfer_to_subaccount"
	PrivateSubmitTransferToUser              = "/private/submit_transfer_to_user"
	PrivateWithdraw                          = "/private/withdraw"
)
View Source
const (
	Future Kind = "future"
	Option      = "option"
	NA          = ""
)

Variables

This section is empty.

Functions

func StreamName

func StreamName(name string, params StreamParams) (string, error)

Types

type Deribit

type Deribit struct {
	exchange.Base
}

Deribit is the overarching type across this package

func (*Deribit) CancelAllOrders

func (de *Deribit) CancelAllOrders(orderCancellation *order.Cancel) (order.CancelAllResponse, error)

CancelAllOrders cancels all orders associated with a currency pair

func (*Deribit) CancelBatchOrders

func (de *Deribit) CancelBatchOrders(o []order.Cancel) (order.CancelBatchResponse, error)

func (*Deribit) CancelOrder

func (de *Deribit) CancelOrder(order *order.Cancel) error

CancelOrder cancels an order by its corresponding ID number

func (*Deribit) FetchAccountInfo

func (de *Deribit) FetchAccountInfo(assetType asset.Item) (account.Holdings, error)

FetchAccountInfo retrieves balances for all enabled currencies

func (*Deribit) FetchOrderbook

func (de *Deribit) FetchOrderbook(currency currency.Pair, assetType asset.Item) (*orderbook.Base, error)

FetchOrderbook returns orderbook base on the currency pair

func (*Deribit) FetchTicker

func (de *Deribit) FetchTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error)

FetchTicker returns the ticker for a currency pair

func (*Deribit) FetchTradablePairs

func (de *Deribit) FetchTradablePairs(asset asset.Item) ([]string, error)

FetchTradablePairs returns a list of the exchanges tradable pairs

func (*Deribit) GenerateDefaultSubscriptions

func (de *Deribit) GenerateDefaultSubscriptions() ([]stream.ChannelSubscription, error)

GenerateDefaultSubscriptions generates default subscription

func (*Deribit) GetActiveOrders

func (de *Deribit) GetActiveOrders(getOrdersRequest *order.GetOrdersRequest) ([]order.Detail, error)

GetActiveOrders retrieves any orders that are active/open

func (*Deribit) GetDefaultConfig

func (de *Deribit) GetDefaultConfig() (*config.ExchangeConfig, error)

GetDefaultConfig returns a default exchange config

func (*Deribit) GetDepositAddress

func (de *Deribit) GetDepositAddress(cryptocurrency currency.Code, accountID string) (string, error)

GetDepositAddress returns a deposit address for a specified currency

func (*Deribit) GetFeeByType

func (de *Deribit) GetFeeByType(feeBuilder *exchange.FeeBuilder) (float64, error)

GetFeeByType returns an estimate of fee based on the type of transaction

func (*Deribit) GetFundingHistory

func (de *Deribit) GetFundingHistory() ([]exchange.FundHistory, error)

GetFundingHistory returns funding history, deposits and withdrawals

func (*Deribit) GetHistoricCandles

func (de *Deribit) GetHistoricCandles(pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error)

GetHistoricCandles returns candles between a time period for a set time interval

func (*Deribit) GetHistoricCandlesExtended

func (de *Deribit) GetHistoricCandlesExtended(pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error)

GetHistoricCandlesExtended returns candles between a time period for a set time interval

func (*Deribit) GetHistoricTrades

func (de *Deribit) GetHistoricTrades(p currency.Pair, a asset.Item, startTime, endTime time.Time) ([]trade.Data, error)

func (*Deribit) GetInstruments

func (d *Deribit) GetInstruments(currency string, kind Kind, expired bool) ([]Instrument, error)

func (*Deribit) GetOrderHistory

func (de *Deribit) GetOrderHistory(getOrdersRequest *order.GetOrdersRequest) ([]order.Detail, error)

GetOrderHistory retrieves account order information Can Limit response to specific order status

func (*Deribit) GetOrderInfo

func (de *Deribit) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error)

GetOrderInfo returns information on a current open order

func (*Deribit) GetRecentTrades

func (de *Deribit) GetRecentTrades(p currency.Pair, a asset.Item) ([]trade.Data, error)

func (*Deribit) GetWithdrawalsHistory

func (de *Deribit) GetWithdrawalsHistory(code currency.Code) ([]exchange.WithdrawalHistory, error)

func (*Deribit) ModifyOrder

func (de *Deribit) ModifyOrder(action *order.Modify) (string, error)

ModifyOrder will allow of changing orderbook placement and limit to market conversion

func (*Deribit) Run

func (de *Deribit) Run()

Run implements the Deribit wrapper

func (*Deribit) SendAuthHTTPRequest

func (b *Deribit) SendAuthHTTPRequest(method, path string, params url.Values, f request.EndpointLimit, result interface{}) error

TODO: SendAuthHTTPRequest sends an authenticated HTTP request

func (*Deribit) SendHTTPRequest

func (b *Deribit) SendHTTPRequest(ep exchange.URL, path string, result interface{}) error

SendHTTPRequest sends an unauthenticated request

func (*Deribit) SetDefaults

func (de *Deribit) SetDefaults()

SetDefaults sets the basic defaults for Deribit

func (*Deribit) Setup

func (de *Deribit) Setup(exch *config.ExchangeConfig) error

Setup takes in the supplied exchange configuration details and sets params

func (*Deribit) Start

func (de *Deribit) Start(wg *sync.WaitGroup)

Start starts the Deribit go routine

func (*Deribit) SubmitOrder

func (de *Deribit) SubmitOrder(s *order.Submit) (order.SubmitResponse, error)

SubmitOrder submits a new order

func (*Deribit) Subscribe

func (de *Deribit) Subscribe(channelsToSubscribe []stream.ChannelSubscription) error

Subscribe sends a websocket message to receive data from the channel

func (*Deribit) Unsubscribe

func (de *Deribit) Unsubscribe(channelsToUnsubscribe []stream.ChannelSubscription) error

Unsubscribe sends a websocket message to stop receiving data from the channel

func (*Deribit) UpdateAccountInfo

func (de *Deribit) UpdateAccountInfo(assetType asset.Item) (account.Holdings, error)

UpdateAccountInfo retrieves balances for all enabled currencies

func (*Deribit) UpdateOrderbook

func (de *Deribit) UpdateOrderbook(p currency.Pair, assetType asset.Item) (*orderbook.Base, error)

UpdateOrderbook updates and returns the orderbook for a currency pair

func (*Deribit) UpdateTicker

func (de *Deribit) UpdateTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error)

UpdateTicker updates and returns the ticker for a currency pair

func (*Deribit) UpdateTradablePairs

func (de *Deribit) UpdateTradablePairs(forceUpdate bool) error

UpdateTradablePairs updates the exchanges available pairs and stores them in the exchanges config

func (*Deribit) ValidateCredentials

func (de *Deribit) ValidateCredentials(assetType asset.Item) error

ValidateCredentials validates current credentials used for wrapper

func (*Deribit) WithdrawCryptocurrencyFunds

func (de *Deribit) WithdrawCryptocurrencyFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error)

WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is submitted

func (*Deribit) WithdrawFiatFunds

func (de *Deribit) WithdrawFiatFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error)

WithdrawFiatFunds returns a withdrawal ID when a withdrawal is submitted

func (*Deribit) WithdrawFiatFundsToInternationalBank

func (de *Deribit) WithdrawFiatFundsToInternationalBank(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error)

WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a withdrawal is submitted

func (*Deribit) WsAuth

func (de *Deribit) WsAuth() error

WsAuth sends an authentication message to receive auth data

func (*Deribit) WsConnect

func (de *Deribit) WsConnect() error

type Instrument

type Instrument struct {
	TickSize             float64 `json:"tick_size"`
	TakerCommission      float64 `json:"taker_commission"`
	Strike               float64 `json:"strike"`
	SettlementPeriod     string  `json:"settlement_period"`
	QuoteCurrency        string  `json:"quote_currency"`
	OptionType           string  `json:"option_type"`
	MinTradeAmount       float64 `json:"min_trade_amount"`
	MakerCommission      float64 `json:"maker_commission"`
	Kind                 string  `json:"kind"`
	IsActive             bool    `json:"is_active"`
	InstrumentName       string  `json:"instrument_name"`
	ExpirationTimestamp  int64   `json:"expiration_timestamp"`
	CreationTimestamp    int64   `json:"creation_timestamp"`
	ContractSize         float64 `json:"contract_size"`
	BlockTradeCommission float64 `json:"block_trade_commission"`
	BaseCurrency         string  `json:"base_currency"`
}

type Instruments

type Instruments struct {
	Jsonrpc string       `json:"jsonrpc"`
	ID      int          `json:"id"`
	Result  []Instrument `json:"result"`
}

remove 'kind' for options and futures and perp etc /public/get_instruments {"method":"public/get_instruments","params":{"currency":"BTC","kind":"future","expired":false},"jsonrpc":"2.0","id":0} {"method":"public/get_instruments","params":{"currency":"ETH","kind":"future","expired":false},"jsonrpc":"2.0","id":0}

type Kind

type Kind string

type StreamParams

type StreamParams struct {
	InstrumentName string
	Group          string
	Depth          string
	Interval       string
	Resolution     string
	IndexName      string
	Kind           string
	Currency       string
}

type SubscribeWrapper

type SubscribeWrapper struct {
	Method string `json:"method"`
	Params struct {
		Channel string          `json:"channel"`
		Data    json.RawMessage `json:"data"`
	} `json:"params"`
	Error struct {
		Message string `json:"message"`
		Code    int    `json:"code"`
	} `json:"error"`
}

type Ticker

type Ticker struct {
	UnderlyingPrice float64 `json:"underlying_price"`
	UnderlyingIndex string  `json:"underlying_index"`
	Timestamp       int64   `json:"timestamp"`
	Stats           struct {
		Volume      float64 `json:"volume"`
		PriceChange float64 `json:"price_change"`
		Low         float64 `json:"low"`
		High        float64 `json:"high"`
	} `json:"stats"`
	State           string  `json:"state"`
	SettlementPrice float64 `json:"settlement_price"`
	OpenInterest    float64 `json:"open_interest"`
	MinPrice        float64 `json:"min_price"`
	MaxPrice        float64 `json:"max_price"`
	MarkPrice       float64 `json:"mark_price"`
	MarkIv          float64 `json:"mark_iv"`
	LastPrice       float64 `json:"last_price"`
	InterestRate    float64 `json:"interest_rate"`
	InstrumentName  string  `json:"instrument_name"`
	IndexPrice      float64 `json:"index_price"`
	Greeks          struct {
		Vega  float64 `json:"vega"`
		Theta float64 `json:"theta"`
		Rho   float64 `json:"rho"`
		Gamma float64 `json:"gamma"`
		Delta float64 `json:"delta"`
	} `json:"greeks"`
	EstimatedDeliveryPrice float64 `json:"estimated_delivery_price"`
	BidIv                  float64 `json:"bid_iv"`
	BestBidPrice           float64 `json:"best_bid_price"`
	BestBidAmount          float64 `json:"best_bid_amount"`
	BestAskPrice           float64 `json:"best_ask_price"`
	BestAskAmount          float64 `json:"best_ask_amount"`
	AskIv                  float64 `json:"ask_iv"`
}

/public/ticker //get ticker for an instrument subscribe ticker.{instrument_name}.{interval} Key info about the instrument

type WsSub

type WsSub struct {
	Method string `json:"method"`
	Params struct {
		Channels []string `json:"channels"`
	} `json:"params"`
}

WsSub stores subscription data

Jump to

Keyboard shortcuts

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