quotes

package
v0.0.25 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2024 License: GPL-3.0 Imports: 30 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
    • based on Subgraph API
    • based on go-ethereum
  • Syncswap

Interface to connect

type Driver interface {
	Start() error
	Stop() error
	Subscribe(market Market) error
	Unsubscribe(market Market) 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:

  • 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"}
	DriverUniswapV3Api  = DriverType{"uniswap_v3_api"}
	DriverUniswapV3Geth = DriverType{"uniswap_v3_geth"}
	DriverSyncswap      = DriverType{"syncswap"}
)
View Source
var (
	TakerTypeUnknown = TakerType{""}
	TakerTypeBuy     = TakerType{"sell"}
	TakerTypeSell    = TakerType{"buy"}
)

Functions

This section is empty.

Types

type BinanceConfig added in v0.0.23

type BinanceConfig struct {
	TradeSampler TradeSamplerConfig `yaml:"trade_sampler"`
}

type BitfakerConfig added in v0.0.23

type BitfakerConfig struct {
	Period       time.Duration      `yaml:"period" env:"QUOTES_BITFAKER_PERIOD" env-default:"5s"`
	TradeSampler TradeSamplerConfig `yaml:"trade_sampler"`
}

type Config

type Config struct {
	Driver DriverType `yaml:"driver" env:"QUOTES_DRIVER" env-default:"binance"`

	Binance       BinanceConfig       `yaml:"binance"`
	Kraken        KrakenConfig        `yaml:"kraken"`
	Opendax       OpendaxConfig       `yaml:"opendax"`
	Bitfaker      BitfakerConfig      `yaml:"bitfaker"`
	UniswapV3Api  UniswapV3ApiConfig  `yaml:"uniswap_v3_api"`
	UniswapV3Geth UniswapV3GethConfig `yaml:"uniswap_v3_geth"`
	Syncswap      SyncswapConfig      `yaml:"syncswap"`
}

func NewConfigFromEnv added in v0.0.22

func NewConfigFromEnv() (Config, error)

func NewConfigFromFile added in v0.0.24

func NewConfigFromFile(path string) (Config, error)

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 KrakenConfig added in v0.0.23

type KrakenConfig struct {
	URL             string             `yaml:"url" env:"QUOTES_KRAKEN_URL" env-default:"wss://ws.kraken.com"`
	ReconnectPeriod time.Duration      `yaml:"period" env:"QUOTES_KRAKEN_RECONNECT_PERIOD" env-default:"5s"`
	TradeSampler    TradeSamplerConfig `yaml:"trade_sampler"`
}

type Market

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

type OpendaxConfig added in v0.0.23

type OpendaxConfig struct {
	URL             string             `yaml:"url" env:"QUOTES_OPENDAX_URL" env-default:"wss://alpha.yellow.org/api/v1/finex/ws"`
	ReconnectPeriod time.Duration      `yaml:"period" env:"QUOTES_OPENDAX_RECONNECT_PERIOD" env-default:"5s"`
	TradeSampler    TradeSamplerConfig `yaml:"trade_sampler"`
}

type SyncswapConfig added in v0.0.23

type SyncswapConfig struct {
	URL                       string             `yaml:"url" env:"QUOTES_SYNCSWAP_URL" env-default:""`
	AssetsURL                 string             `` /* 152-byte string literal not displayed */
	ClassicPoolFactoryAddress string             `` /* 143-byte string literal not displayed */
	TradeSampler              TradeSamplerConfig `yaml:"trade_sampler"`
}

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. `btc/usdt`
	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"`
}

type UniswapV3ApiConfig added in v0.0.23

type UniswapV3ApiConfig struct {
	URL          string             `yaml:"url" env:"QUOTES_UNISWAP_V3_API_URL" env-default:"https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3"`
	WindowSize   time.Duration      `yaml:"window_size" env:"QUOTES_UNISWAP_V3_API_WINDOW_SIZE" env-default:"2s"`
	TradeSampler TradeSamplerConfig `yaml:"trade_sampler"`
}

type UniswapV3GethConfig added in v0.0.23

type UniswapV3GethConfig struct {
	URL            string             `yaml:"url" env:"QUOTES_UNISWAP_V3_GETH_URL" env-default:""`
	AssetsURL      string             `` /* 159-byte string literal not displayed */
	FactoryAddress string             `yaml:"factory_address" env:"QUOTES_UNISWAP_V3_GETH_FACTORY_ADDRESS" env-default:"0x1F98431c8aD98523631AE4a59f267346ea31F984"`
	TradeSampler   TradeSamplerConfig `yaml:"trade_sampler"`
}

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.
App for testing quotes drivers.
App for testing quotes drivers.

Jump to

Keyboard shortcuts

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