deribit

package module
v3.2.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2021 License: MIT Imports: 18 Imported by: 0

README

Build Status Go Report Card codebeat badge

go-deribit

Status

This code has been forked from scancel/go-deribit fantastic original code. Maintenance is now taken over on this fork (as of 20201216). This code adds encapsulated functions which allow a more trader-friendly use of the original API.

Here is a sample code:

package main

import (
	"fmt"
	"log"

	flag "github.com/spf13/pflag"
	"github.com/scancel/go-deribit/v3"
	"github.com/scancel/go-deribit/v3/client/public"
)

func main() {
	key := flag.String("access-key", "", "Access key")
	secret := flag.String("secret-key", "", "Secret access key")
	flag.Parse()
	errs := make(chan error)
	stop := make(chan bool)
	realExchange := false
	exchange, err := deribit.NewExchange(realExchange, errs, stop)

	if err != nil {
		log.Fatalf("Error creating connection: %s", err)
	}
	if err := exchange.Connect(); err != nil {
		log.Fatalf("Error connecting to exchange: %s", err)
	}
	go func() {
		err := <-errs
		stop <- true
		log.Fatalf("RPC error: %s", err)
	}()
	client := exchange.Client()
	// Step #1 : Hit the test public RPC endpoint
	res, err := client.Public.GetPublicTest(&public.GetPublicTestParams{})
	if err != nil {
		log.Fatalf("Error testing connection: %s", err)
	}
	log.Printf("Connected to Deribit API v%s", *res.Payload.Result.Version)
	// Step #2 : Actually authenticate on private account
	if err := exchange.Authenticate(*key, *secret); err != nil {
		log.Fatalf("Error authenticating: %s", err)
	}

	// --------------------
	// 1. Account Summary
	// --------------------

	fmt.Println("---------------")
	fmt.Println("Account summary BTC")
	fmt.Println("---------------")
	BtcAccount, errAcctBtc := deribit.GetAccountSummary(client, "BTC")
	if errAcctBtc != nil {
		log.Fatalf("Error getting account summary: %s", errAcctBtc)
	}
	BtcAccount.Sprintf()
	fmt.Println("---------------")
	fmt.Println("Account summary ETH")
	fmt.Println("---------------")
	EthAccount, errAcctEth := deribit.GetAccountSummary(client, "ETH")
	if errAcctEth != nil {
		log.Fatalf("Error getting account summary: %s", errAcctEth)
	}
	EthAccount.Sprintf()

	// --------------------
	// 2. Referential
	// --------------------
	btcReferential, _ := deribit.GetReferential(client, "BTC")
	ethReferential, _ := deribit.GetReferential(client, "ETH")

	fmt.Println("---------------")
	fmt.Println("Referential BTC")
	fmt.Println("---------------")
	for key, value := range btcReferential {
		fmt.Println("#", key, ":\n", value.Sprintf())
	}
	fmt.Println("---------------")
	fmt.Println("Referential ETH")
	fmt.Println("---------------")
	for key, value := range ethReferential {
		fmt.Println("# ", key, ":\n", value.Sprintf())
	}

	// --------------------
	// 3. Book Summary
	// Makes a snapshot of prices on all derivatives
	// --------------------

	currency := "BTC"
	fmt.Println("Book Summary ", currency)
	fmt.Println("------------------")
	bookSummaries, _ := deribit.GetBookSummary(client, currency)

	for key, value := range bookSummaries {
		fmt.Println("Book summary :", key, " ", value.Sprintf())
	}

	// --------------------
	// 4. Account position for a specific underlying
	// --------------------
	// see v3/models/position.go && v3/client/private/private_client.go
	fmt.Println("Account Position")
	fmt.Println("------------------")
	pInstrumentName := "BTC-PERPETUAL"
	accountPosition, _ := deribit.GetAccountPosition(client, pInstrumentName)

	fmt.Println("Position of ", pInstrumentName)
	accountPosition.Sprintf()

	// --------------------
	// 5. Account positions for a kind of underlyings
	// --------------------
	fmt.Println("Account Positions")
	fmt.Println("------------------")
	futureType := "FUTURE" // option
	optionType := "OPTION" // option
	futuresPositions, _ := deribit.GetAccountPositions(client, currency, futureType)
	optionPositions, _ := deribit.GetAccountPositions(client, currency, optionType)

	for key, value := range futuresPositions {
		fmt.Println("FUTURES Position: #", key, " ", value.Sprintf())
	}

	for key, value := range optionPositions {
		fmt.Println("OPTION Position: #", key, " ", value.Sprintf())
	}

	// --------------------
	// 6. Order book subscription (market data)
	// --------------------
	depth := "1"
	interval := "100ms"
	book, err := exchange.SubscribeBookGroup("BTC-PERPETUAL", "none", depth, interval)
	if err != nil {
		log.Fatalf("Error subscribing to the book: %s", err)
	}
	for b := range book {
		fmt.Printf("Top bid: %f Top ask: %f\n", b.Bids[0][0], b.Asks[0][0])
	}

	// --------------------
	// 7. Transaction
	// --------------------
	// This has not been tried yet
	// amount := 0.0001
	// instrumentName := "BTC-PERPETUAL"
	// price := 12532.0
	// orderType := "limit" // "market"
	// buy, err := deribit.Buy(client, amount, instrumentName, price, orderType)

	exchange.Close()
}

V3

This project is now using go1.13 with Go Modules, but should remain compatible with dep. Also, as there are some breaking changes introduced by the latest schema changes from the remote API, I have decided to carry on development in the new v3 namespace with the project root containing the code tagged v2.x.

import "github.com/scancel/go-deribit/v3"

We now have the latest API methods which were recently released such as public/get_tradingview_chart_data.

Only thev3 directory will benefit from onward development.`

GoDoc API Documentation

Overview

Go library for using the Deribit's v2 Websocket API.

Deribit is a modern, fast BitCoin derivatives exchange.

This library is a port of the official wrapper libraries to Go.

If you wish to try it out, be kind and use my affiliate link https://www.deribit.com/reg-3027.8327

p.s. If you want a good BitMEX client library then try go-bitmex

V2 API Documentation

Example Usage

Look at v3/cmd/example/main.go

go build main.go
./main --access-key XXX --secret-key YYYYYY

Reconnect Behaviour

There is a heartbeat which triggers every 10 seconds to keep the websocket connection alive. In the event of a connection error, the library will automatically attempt to reconnect, re-authenticate and reestablish subscriptions.

This behaviour is overrideable with the SetDisconnectHandler method.

// Example reconnect code
exchange.SetDisconnectHandler(func (core *deribit.RPCCore) {
    exg := &deribit.NewExchangeFromCore(true, core)
	log.Warn("Disconnected from exchange. Attempting reconnection...")
	if err := exg.Connect(); err != nil {
		log.Fatalf("Error re-connecting to exchange: %s", err)
	}
	log.Info("Reconnected")
})

Logging

The standard logger has been used within the library. You can plug this into your own application's logger by overriding the output io.Writer.

logger := logrus.New()
exchange.SetLogOutput(logger.Writer())

Development

The models and client directories are where all the requests and responses are stored. The contents is automatically generated from the schema directory by go-swagger.

If you need to rebuild these use make generate-models.

The RPC subscriptions are also auto-generated. Use make generate-methods to rebuild these. They are in rpc_subscriptions.go.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTimeout = errors.New("timed out waiting for a response")

ErrTimeout - request timed out

Functions

This section is empty.

Types

type Exchange

type Exchange struct {
	OnDisconnect func(*Exchange) // triggers on a failed read from connection
	// contains filtered or unexported fields
}

Exchange is an API wrapper with the exchange

func NewExchange

func NewExchange(test bool, errs chan error, stop chan bool) (*Exchange, error)

NewExchange creates a new API wrapper key and secret can be ignored if you are only calling public endpoints

func (*Exchange) Authenticate

func (e *Exchange) Authenticate(key, secret string) error

func (*Exchange) Client

func (e *Exchange) Client() *operations.Client

Client returns an initialised API client

func (*Exchange) Close

func (e *Exchange) Close() error

Close the websocket connection

func (*Exchange) Connect

func (e *Exchange) Connect() error

Connect to the websocket API

func (*Exchange) Submit

func (e *Exchange) Submit(operation *runtime.ClientOperation) (interface{}, error)

Submit satisfies the runtime.ClientTransport interface

func (*Exchange) SubscribeAnnouncements

func (e *Exchange) SubscribeAnnouncements(instrument_name, interval string) (chan *models.AnnouncementNotification, error)

SubscribeAnnouncements subscribes to the announcements channel

func (*Exchange) SubscribeBookGroup

func (e *Exchange) SubscribeBookGroup(instrument_name, group, depth, interval string) (chan *models.BookNotification, error)

SubscribeBookGroup subscribes to the book.{instrument_name}.{group}.{depth}.{interval} channel

func (*Exchange) SubscribeBookInterval

func (e *Exchange) SubscribeBookInterval(instrument_name, interval string) (chan *models.BookNotificationRaw, error)

SubscribeBookInterval subscribes to the book.{instrument_name}.{interval} channel

func (*Exchange) SubscribeDeribitPriceIndex

func (e *Exchange) SubscribeDeribitPriceIndex(index_name string) (chan *models.DeribitPriceIndexNotification, error)

SubscribeDeribitPriceIndex subscribes to the deribit_price_index.{index_name} channel

func (*Exchange) SubscribeDeribitPriceRanking

func (e *Exchange) SubscribeDeribitPriceRanking(index_name string) (chan *models.DeribitPriceRankingNotification, error)

SubscribeDeribitPriceRanking subscribes to the deribit_price_ranking.{index_name} channel

func (*Exchange) SubscribeEstimatedExpirationPrice

func (e *Exchange) SubscribeEstimatedExpirationPrice(index_name string) (chan *models.EstimatedExpirationPriceNotification, error)

SubscribeEstimatedExpirationPrice subscribes to the estimated_expiration_price.{index_name} channel

func (*Exchange) SubscribeMarkPriceOptions

func (e *Exchange) SubscribeMarkPriceOptions(index_name string) (chan *models.MarkpriceOptionsNotification, error)

SubscribeMarkPriceOptions subscribes to the markprice.options.{index_name} channel

func (*Exchange) SubscribePerpetual

func (e *Exchange) SubscribePerpetual(instrument_name, interval string) (chan *models.PerpetualNotification, error)

SubscribePerpetual subscribes to the perpetual.{instrument_name}.{interval} channel

func (*Exchange) SubscribeQuote

func (e *Exchange) SubscribeQuote(instrument_name string) (chan *models.QuoteNotification, error)

SubscribeQuote subscribes to the quote.{instrument_name} channel

func (*Exchange) SubscribeTicker

func (e *Exchange) SubscribeTicker(instrument_name, interval string) (chan *models.TickerNotification, error)

SubscribeTicker subscribes to the ticker.{instrument_name}.{interval} channel

func (*Exchange) SubscribeTrades

func (e *Exchange) SubscribeTrades(instrument_name, interval string) (chan *models.PublicTrade, error)

SubscribeTrades subscribes to the trades.{instrument_name}.{interval} channel

func (*Exchange) SubscribeUserOrdersInstrumentName

func (e *Exchange) SubscribeUserOrdersInstrumentName(instrument_name, interval string) (chan *models.Order, error)

SubscribeUserOrdersInstrumentName subscribes to the user.orders.{instrument_name}.{interval} channel

func (*Exchange) SubscribeUserOrdersKind

func (e *Exchange) SubscribeUserOrdersKind(kind, currency, interval string) (chan *models.Order, error)

SubscribeUserOrdersKind subscribes to the user.orders.{kind}.{currency}.{interval} channel

func (*Exchange) SubscribeUserPortfolio

func (e *Exchange) SubscribeUserPortfolio(currency string) (chan *models.UserPortfolioNotification, error)

SubscribeUserPortfolio subscribes to the user.portfolio.{currency} channel

func (*Exchange) SubscribeUserTradesInstrument

func (e *Exchange) SubscribeUserTradesInstrument(instrument_name, interval string) (chan *models.UserTrade, error)

SubscribeUserTradesInstrument subscribes to the user.trades.{instrument_name}.{interval} channel

func (*Exchange) SubscribeUserTradesKind

func (e *Exchange) SubscribeUserTradesKind(kind, currency, interval string) (chan *models.UserTrade, error)

SubscribeUserTradesKind subscribes to the user.trades.{kind}.{currency}.{interval} channel

type RPCCall

type RPCCall struct {
	Req   *RPCRequest
	Res   *RPCResponse
	Error error
	Done  chan bool
}

RPCCall represents the entire call from request to response

func NewRPCCall

func NewRPCCall(req *RPCRequest) *RPCCall

NewRPCCall returns a new RPCCall initialised with a done channel and request

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

RPCError error object

type RPCNotification

type RPCNotification struct {
	JsonRpc string
	Method  string `json:"method"`
	Params  struct {
		Data    json.RawMessage `json:"data"`
		Channel string          `json:"channel"`
	} `json:"params,omitempty"`
}

RPCNotification is a notification which we have subscribed to

type RPCRequest

type RPCRequest struct {
	JsonRpc string                 `json:"jsonrpc"`
	Method  string                 `json:"method"`
	ID      uint64                 `json:"id"`
	Params  map[string]interface{} `json:"params,omitempty"`
}

RPCRequest is what we send to the remote Implements runtime.ClientRequest

func NewRPCRequest

func NewRPCRequest(method string) *RPCRequest

func (RPCRequest) GetBody

func (RPCRequest) GetBody() []byte

func (RPCRequest) GetBodyParam

func (RPCRequest) GetBodyParam() interface{}

func (RPCRequest) GetFileParam

func (RPCRequest) GetFileParam() map[string][]runtime.NamedReadCloser

func (RPCRequest) GetHeaderParams

func (RPCRequest) GetHeaderParams() http.Header

func (RPCRequest) GetMethod

func (RPCRequest) GetMethod() string

func (*RPCRequest) GetPath

func (r *RPCRequest) GetPath() string

func (RPCRequest) GetQueryParams

func (RPCRequest) GetQueryParams() url.Values

func (RPCRequest) SetBodyParam

func (RPCRequest) SetBodyParam(interface{}) error

func (RPCRequest) SetFileParam

func (RPCRequest) SetFileParam(string, ...runtime.NamedReadCloser) error

func (RPCRequest) SetFormParam

func (RPCRequest) SetFormParam(string, ...string) error

func (RPCRequest) SetHeaderParam

func (RPCRequest) SetHeaderParam(string, ...string) error

func (RPCRequest) SetPathParam

func (RPCRequest) SetPathParam(string, string) error

func (*RPCRequest) SetQueryParam

func (r *RPCRequest) SetQueryParam(key string, vals ...string) error

func (RPCRequest) SetTimeout

func (RPCRequest) SetTimeout(time.Duration) error

type RPCResponse

type RPCResponse struct {
	JsonRpc string          `json:"jsonrpc"`
	ID      uint64          `json:"id,omitempty"`
	Result  json.RawMessage `json:"result"`
	Error   *RPCError       `json:"error,omitempty"`
}

RPCResponse is what we receive from the remote Implements runtime.ClientResponse

func (*RPCResponse) Body

func (r *RPCResponse) Body() io.ReadCloser

func (*RPCResponse) Code

func (r *RPCResponse) Code() int

func (RPCResponse) GetHeader

func (RPCResponse) GetHeader(string) string

func (*RPCResponse) Message

func (r *RPCResponse) Message() string

type RPCSubscription

type RPCSubscription struct {
	Data    chan *RPCNotification
	Channel string
}

RPCSubscription is a subscription to an event type to receive notifications about

Directories

Path Synopsis
cmd
gen

Jump to

Keyboard shortcuts

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