quotes

package
v0.0.17 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2024 License: GPL-3.0 Imports: 18 Imported by: 0

README

Quotes service

The Quotes Service is a centralized system responsible for recording and disseminating real-time trade data from various trading platforms.

Available drivers:

  • Binance
  • Kraken
  • Opendax
  • Bitfaker
  • Uniswap V3

Interface to connect

type Driver interface {
	Subscribe(market Market) error
	Start(markets []Market) error
	Stop() error
}

Type of price source

Top Tier CEX Altcoins CEX FIAT DEX
BitFinex Gate UpBit Sushi
OKX MEXC Kraken PancakeSwap
Binance KuCoin Coinbase Uniswap
weight: 20 weight: 5 weight: 15 weight: 50

Last Price

For candle sticks, Recent trade, tickers last price is calculated as follows:

last_price = price

Index Price

Used mainly in risk management for portfolio evaluation:

index_price = EMA20(price x ( trade_size x weight / active_weights ))
# active_weight being the sum of weight where this market exists (ex: KuCoin:5 + uniswap:50)
# EMA20 is likely 20 at 1 min scale

How Uniswap adapter calculates swap price

Method 1: from sqrtPriceX96
Motivation

Uniswap V3 uses Q notation, which is a type of fixed-point arithmetics, to encode swap price.

Q notation allows variables to remain integers, but function similarly to floating point numbers. Additionally piping the price through square root allows to reduce dimentionality of the number. Predictable size of the number encoded this way enables efficient caching and fast retrieval of data from chain.

How to calculate price?

Actually this is a two step process:

  1. Decode price
  2. Convert the price into wei/wei ratio
Step 1

Here's the formula:

sqrtPrice = sqrtPriceX96 / (2^96)
price = sqrtPrice^2
Step 2

ERC20 tokens have built in decimal values. For example, 1 WETH actually represents WETH in the contract whereas USDC is 10^6. USDC has 6 decimals and WETH has 18. So the price calculated on step 1 actually depicts [wei of token0] / [unit token of token1]. Now let's convert that into [wei] / [wei] ratio:

price0 = price / (10^(decimal1-decimal0))
price1 = 1 / price0
Method 2: ticks

This method requires a different set of inputs to calculate.

Motivation

Ticks are related directly to price and enable simpler calculations compared to [[#Method 1]]. This requires just a tick value and a one-shot formula.

How to calculate price?

To convert from tick t, to price, take 1.0001^t to get the corresponding price.

price  = 1.0001^tick
price0 = price / (10^(decimal1-decimal0))
price1 = 1 / price0

It's also possible to convert sqrtPriceX96 to tick:

tick = floor[ log((sqrtPriceX96 / (2^96))^2) / log(1.0001) ]

TODO:

  • remove Finex dependencies
  • add specs or amendments to current interface

Documentation

Overview

Package quotes implements multiple price feed adapters.

Index

Constants

This section is empty.

Variables

View Source
var (
	DriverBinance   = DriverType{"binance"}
	DriverKraken    = DriverType{"kraken"}
	DriverOpendax   = DriverType{"opendax"}
	DriverBitfaker  = DriverType{"bitfaker"}
	DriverUniswapV3 = DriverType{"uniswap_v3"}
)
View Source
var (
	TakerTypeUnknown = TakerType{""}
	TakerTypeBuy     = TakerType{"sell"}
	TakerTypeSell    = TakerType{"buy"}
)
View Source
var (
	ErrNotSubbed     = errors.New("market not subscribed")
	ErrAlreadySubbed = errors.New("market already subscribed")
	ErrFailedSub     = errors.New("failed to subscribe to market")
	ErrFailedUnsub   = errors.New("failed to unsubscribe from market")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	URL             string             `yaml:"url" env:"QUOTES_URL" env-default:""`
	Driver          DriverType         `yaml:"driver" env:"QUOTES_DRIVER" env-default:"binance"`
	ReconnectPeriod time.Duration      `yaml:"period" env:"QUOTES_RECONNECT_PERIOD" env-default:"5s"`
	TradeSampler    TradeSamplerConfig `yaml:"trade_sampler"`
}

type Driver

type Driver interface {
	Start() error
	Stop() error
	Subscribe(market Market) error
	Unsubscribe(market Market) error
}

func NewDriver

func NewDriver(config Config, outbox chan<- TradeEvent) (Driver, error)

type DriverType

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

DriverType is enum that represents all available quotes providers.

func ToDriverType

func ToDriverType(raw string) (DriverType, error)

func (DriverType) MarshalJSON

func (t DriverType) MarshalJSON() ([]byte, error)

func (DriverType) MarshalYAML

func (t DriverType) MarshalYAML() (any, error)

func (*DriverType) String

func (d *DriverType) String() string

func (*DriverType) UnmarshalJSON

func (t *DriverType) UnmarshalJSON(raw []byte) error

func (*DriverType) UnmarshalYAML

func (t *DriverType) UnmarshalYAML(value *yaml.Node) error

type Market

type Market struct {
	BaseUnit  string // e.g. `btc` in `btcusdt`
	QuoteUnit string // e.g. `usdt` in `btcusdt`
}

type TakerType

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

TakerType is enum that represents the side of taker in a trade.

func ToTakerType

func ToTakerType(raw string) (TakerType, error)

func (TakerType) MarshalJSON

func (t TakerType) MarshalJSON() ([]byte, error)

func (TakerType) MarshalYAML

func (t TakerType) MarshalYAML() (any, error)

func (*TakerType) String

func (t *TakerType) String() string

func (*TakerType) UnmarshalJSON

func (t *TakerType) UnmarshalJSON(raw []byte) error

func (*TakerType) UnmarshalYAML

func (t *TakerType) UnmarshalYAML(value *yaml.Node) error

type TradeEvent

type TradeEvent struct {
	Source    DriverType
	Market    string // e.g. `btcusdt`
	Price     decimal.Decimal
	Amount    decimal.Decimal
	Total     decimal.Decimal
	TakerType TakerType
	CreatedAt time.Time
}

TradeEvent is a generic container for trades received from providers.

type TradeSamplerConfig

type TradeSamplerConfig struct {
	Enabled           bool `yaml:"enabled" env:"QUOTES_TRADE_SAMPLER_ENABLED"`
	DefaultPercentage int  `yaml:"default_percentage" env:"QUOTES_TRADE_SAMPLER_DEFAULT_PERCENTAGE"`
}

Directories

Path Synopsis
Types and helpers for easy formatting and parsing open-finance protocol messages.
Types and helpers for easy formatting and parsing open-finance protocol messages.

Jump to

Keyboard shortcuts

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