common

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2020 License: BSD-2-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package common provides data structures used throughout the Cryptowatch SDK.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSeqNumMismatch is returned from OrderBookSnapshot.ApplyDelta... family
	// when new squence number isn't exactly the old one plus 1.
	ErrSeqNumMismatch = errors.New("seq num mismatch")
)
View Source
var FundingTypeNames = map[FundingType]string{
	SpotFunding:    "spot",
	MarginFunding:  "margin",
	FuturesFunding: "futures",
}

FundingTypeNames contains human-readable names for FundingType.

View Source
var OrderSideNames = map[OrderSide]string{
	OrderSideSell:    "sell",
	OrderSideBuy:     "buy",
	OrderSideUnknown: "unknown",
}

OrderSideNames contains human-readable names for OrderSide.

View Source
var OrderTypeNames = map[OrderType]string{
	MarketOrder:                  "market",
	LimitOrder:                   "limit",
	StopLossOrder:                "stop-loss",
	TakeProfitOrder:              "take-profit",
	TakeProfitLimitOrder:         "take-profit-limit",
	StopLossTakeProfitOrder:      "stop-loss-take-profit",
	StopLossTakeProfitLimitOrder: "stop-loss-take-profit-limit",
	TrailingStopLossOrder:        "trailing-stop-loss",
	TrailingStopLossLimitOrder:   "trailing-stop-loss-limit",
	StopLossAndLimitOrder:        "stop-loss-and-limit",
	FillOrKillOrder:              "fill-or-kill",
	SettlePositionOrder:          "settle-position",
}

OrderTypeNames contains human-readable names for OrderType.

View Source
var PeriodNames = map[Period]string{
	Period1M:         "1m",
	Period3M:         "3m",
	Period5M:         "5m",
	Period15M:        "15m",
	Period30M:        "30m",
	Period1H:         "1h",
	Period2H:         "2h",
	Period4H:         "4h",
	Period6H:         "6h",
	Period12H:        "12h",
	Period1D:         "1d",
	Period3D:         "3d",
	Period1WMonday:   "1w",
	Period1WThursday: "1w",
}

PeriodNames contains human-readable names for Period. e.g. Period1M = 60 (seconds) = "1m".

Functions

This section is empty.

Types

type Asset

type Asset struct {
	ID     AssetID     `json:"id"`
	Symbol AssetSymbol `json:"symbol"`
}

An asset represents an asset on Cryptowatch. Assets are the building blocks for instruments. Examples: btc, usd, eth

func (Asset) String

func (a Asset) String() string

type AssetID

type AssetID int

func (AssetID) String

func (a AssetID) String() string

type AssetSymbol

type AssetSymbol string

func (AssetSymbol) String

func (as AssetSymbol) String() string

type Balance

type Balance struct {
	FundingType FundingType
	Asset       Asset
	Amount      decimal.Decimal
}

Balance is the amount you have of a particular asset.

type Balances

type Balances map[Exchange][]Balance

func (Balances) All

func (b Balances) All() []Balance

All returns a slice of all balances combined based on funding type + asset

type CancelOrderParams

type CancelOrderParams struct {
	MarketID MarketID
	OrderID  string
}

CancelOrderParams contains the necessary options for canceling an existing order with the trade client. See TradeClient.CancelOrder.

type Exchange

type Exchange struct {
	ID     ExchangeID     `json:"id"`
	Symbol ExchangeSymbol `json:"symbol"`
}

Exchange represents an exchange on Cryptowatch. Examples: kraken, bitfinex, coinbase-pro

type ExchangeID

type ExchangeID int

type ExchangeSymbol

type ExchangeSymbol string

type FundingType

type FundingType int32

FundingType represents the funding type for an order; e.g. "spot" or "margin". The funding types available depend on the exchange, as well as your account's permissions on the exchange.

const (
	SpotFunding FundingType = iota
	MarginFunding
	FuturesFunding
)

The following constants define every possible funding type.

type GetAssetParams

type GetAssetParams struct {
	ID     AssetID
	Symbol AssetSymbol
}

type Instrument

type Instrument struct {
	ID    InstrumentID `json:"id"`
	Base  Asset        `json:"base"`
	Quote Asset        `json:"quote"`
}

Instrument represents an instrument on Cryptowatch, which is essentially a base+quote, or if it is a futures market, a settlement frequency as well. Examples: btcusd, ethusd, btcusdt

type InstrumentID

type InstrumentID int

type Interval

type Interval struct {
	Period Period
	OHLC   OHLC

	// CloseTime is the time at which the Interval ended.
	CloseTime time.Time

	// VolumeBase is the amount of volume traded over this Interval, represented
	// in the base currency.
	VolumeBase decimal.Decimal

	// VolumeQuote is the amount of volume traded over this Interval, represented
	// in the quote currency.
	VolumeQuote decimal.Decimal
}

An interval represetns OHLC data for a particular Period and CloseTime.

type IntervalsUpdate

type IntervalsUpdate struct {
	Intervals []Interval
}

IntervalsUpdate represents an update for OHLC data, at all relevant periods. Intervals is represented as a slice because more than one interval update can occur at the same time for different periods. For example, Period1M and Period3M will overlap every 3 minutes, so that IntervalsUpdate will contain both intervals.

type Market

type Market struct {
	ID         MarketID   `json:"id"`
	Exchange   Exchange   `json:"exchange"`
	Instrument Instrument `json:"instrument"`
}

Market represents a market on Cryptowatch. A market consists of an exchange and currency pair. For example, Kraken BTC/USD. IDs are used instead of names to avoid inconsistencies associated with name changes. Example: kraken:btcusd, bitfinex:btcusd

func (Market) String

func (m Market) String() string

func (Market) Symbol

func (m Market) Symbol() MarketSymbol

type MarketID

type MarketID int

func (MarketID) String

func (m MarketID) String() string

type MarketParams

type MarketParams struct {
	Symbol MarketSymbol
	ID     MarketID
}

type MarketSymbol

type MarketSymbol struct {
	Exchange ExchangeSymbol
	Base     AssetSymbol
	Quote    AssetSymbol
}

func (MarketSymbol) String

func (ms MarketSymbol) String() string

type MarketUpdate

type MarketUpdate struct {
	OrderBookSnapshot     *OrderBookSnapshot     `json:"OrderBookSnapshot,omitempty"`
	OrderBookDelta        *OrderBookDelta        `json:"OrderBookDelta,omitempty"`
	OrderBookSpreadUpdate *OrderBookSpreadUpdate `json:"OrderBookSpreadUpdate,omitempty"`
	TradesUpdate          *TradesUpdate          `json:"TradesUpdate,omitempty"`
	IntervalsUpdate       *IntervalsUpdate       `json:"IntervalsUpdate,omitempty"`
	SummaryUpdate         *SummaryUpdate         `json:"SummaryUpdate,omitempty"`
	SparklineUpdate       *SparklineUpdate       `json:"SparklineUpdate,omitempty"`
}

MarketUpdate is a container for all market data callbacks. For any MarketUpdate intance, it will only ever have one of its properties non-null. See OnMarketUpdate.

func (MarketUpdate) String

func (v MarketUpdate) String() string

type OHLC

type OHLC struct {
	Open  decimal.Decimal
	High  decimal.Decimal
	Low   decimal.Decimal
	Close decimal.Decimal
}

OHLC contains the open, low, high, and close prices for a given Interval.

type OrderBookDelta

type OrderBookDelta struct {
	// SeqNum is used to make sure deltas are processed in order.
	// See the SeqNum definition for more information.
	SeqNum SeqNum

	Bids OrderDeltas
	Asks OrderDeltas
}

OrderBookDelta represents an order book delta update, which is the minimum amount of data necessary to keep a local order book up to date. Since order book snapshots are throttled at 1 per minute, subscribing to the delta updates is the best way to keep an order book up to date.

func (OrderBookDelta) Empty

func (delta OrderBookDelta) Empty() bool

Empty returns whether OrderBookDelta doesn't contain any deltas for bids and asks.

type OrderBookSnapshot

type OrderBookSnapshot struct {
	// SeqNum	is the sequence number of the last order book delta received.
	// Since snapshots are broadcast on a 1-minute interval regardless of updates,
	// it's possible this value doesn't change.
	// See the SeqNum definition for more information.
	SeqNum SeqNum

	Bids []PublicOrder
	Asks []PublicOrder
}

OrderBookSnapshot represents a full order book snapshot.

func (*OrderBookSnapshot) ApplyDelta

func (*OrderBookSnapshot) ApplyDeltaOpt

func (s *OrderBookSnapshot) ApplyDeltaOpt(obd OrderBookDelta, ignoreSeqNum bool) (OrderBookSnapshot, error)

func (*OrderBookSnapshot) Copy

func (*OrderBookSnapshot) Empty

func (s *OrderBookSnapshot) Empty() bool

func (*OrderBookSnapshot) GetDeltasAgainst

func (s *OrderBookSnapshot) GetDeltasAgainst(oldSnapshot OrderBookSnapshot) OrderBookDelta

GetDeltasAgainst creates deltas which would have to be applied to oldSnapshot to get s.

func (*OrderBookSnapshot) IsValid

func (s *OrderBookSnapshot) IsValid() bool

type OrderBookSpreadUpdate

type OrderBookSpreadUpdate struct {
	Timestamp time.Time
	Bid       PublicOrder
	Ask       PublicOrder
}

OrderBookSpreadUpdate represents the most recent order book spread. It consists of the best current bid and as price.

type OrderDeltas

type OrderDeltas struct {
	// Set is a list of orders used to add or replace orders on an order book.
	// Each order in Set is guaranteed to be a different price. For each of them,
	// if the order at that price exists on the book, replace it. If an order
	// at that price does not exist, add it to the book.
	Set []PublicOrder

	// Remove is a list of prices. To apply to an order book, remove all orders
	// of that price from that book.
	Remove []decimal.Decimal
}

OrderDeltas are used to update an order book, either by setting (adding) new PublicOrders, or removing orders at specific prices.

func GetDeltasAgainst

func GetDeltasAgainst(oldOrders, newOrders []PublicOrder, reversed bool) OrderDeltas

func (OrderDeltas) Empty

func (d OrderDeltas) Empty() bool

Empty returns whether the OrderDeltas doesn't contain any deltas.

type OrderSide

type OrderSide int32

OrderSide represents the order side; e.g. "buy" or "sell".

const (
	OrderSideUnknown OrderSide = iota
	OrderSideBuy
	OrderSideSell
)

func (OrderSide) String

func (os OrderSide) String() string

type OrderType

type OrderType int32

OrderType represents the type of order; e.g. "market" or "limit". There are 13 different types of orders. Those available depend on the exchange. Refer to the exchange's documentation for what order types are available.

const (
	MarketOrder OrderType = iota
	LimitOrder
	StopLossOrder
	StopLossLimitOrder
	TakeProfitOrder
	TakeProfitLimitOrder
	StopLossTakeProfitOrder
	StopLossTakeProfitLimitOrder
	TrailingStopLossOrder
	TrailingStopLossLimitOrder
	StopLossAndLimitOrder
	FillOrKillOrder
	SettlePositionOrder
)

The following constants define all possible order types.

type Pair

type Pair struct {
	ID PairID
}

Pair represents the currency pair as defined by the Cryptowatch API: https://api.cryptowat.ch/pairs

type PairID

type PairID string

type PairUpdate

type PairUpdate struct {
	VWAPUpdate        *VWAPUpdate        `json:"VWAPUpdate,omitempty"`
	PerformanceUpdate *PerformanceUpdate `json:"PerformanceUpdate,omitempty"`
	TrendlineUpdate   *TrendlineUpdate   `json:"TrendlineUpdate,omitempty"`
}

PairUpdate is a container for all pair data callbacks. For any PairUpdate instance, it will only ever have one of its properties non-null. See OnPairUpdate.

func (PairUpdate) String

func (v PairUpdate) String() string

type PerformanceUpdate

type PerformanceUpdate struct {
	Window      PerformanceWindow
	Performance decimal.Decimal
}

PerformanceUpdate represents the most recent performance update for a market over a particular window. TODO explain calculation

type PerformanceWindow

type PerformanceWindow string

PerformanceWindow represents the time window over which performance is calculated.

const (
	PerfWindow24h PerformanceWindow = "24h"
	PerfWindow1w  PerformanceWindow = "1w"
	PerfWindow1m  PerformanceWindow = "1m"
	PerfWindow3m  PerformanceWindow = "3m"
	PerfWindow6m  PerformanceWindow = "6m"
	PerfWindowYTD PerformanceWindow = "ytd"
	PerfWindow1y  PerformanceWindow = "1y"
	PerfWindow2y  PerformanceWindow = "2y"
	PerfWindow3y  PerformanceWindow = "3y"
	PerfWindow4y  PerformanceWindow = "4y"
	PerfWindow5y  PerformanceWindow = "5y"
)

The following constants represent every possible PerformanceWindow.

type Period

type Period string

Period is the number of seconds in an Interval.

const (
	Period1M         Period = "60"
	Period3M         Period = "180"
	Period5M         Period = "300"
	Period15M        Period = "900"
	Period30M        Period = "1800"
	Period1H         Period = "3600"
	Period2H         Period = "7200"
	Period4H         Period = "14400"
	Period6H         Period = "21600"
	Period12H        Period = "43200"
	Period1D         Period = "86400"
	Period3D         Period = "259200"
	Period1WThursday Period = "604800"
	Period1WMonday   Period = "604800_Monday"
)

The following constants are all available Period values for IntervalsUpdate.

func (Period) Duration

func (p Period) Duration() time.Duration

type PlaceOrderParams

type PlaceOrderParams struct {
	MarketID    MarketID
	PriceParams PriceParams
	Amount      string
	OrderSide   OrderSide
	OrderType   OrderType
	FundingType FundingType
	Leverage    string
	ExpireTime  time.Time
}

PlaceOrderParams contains the necessary options for creating a new order with the trade client. See TradeClient.PlaceOrder.

type PriceParam

type PriceParam struct {
	Value string
	Type  PriceParamType
}

PriceParam is used as input for an Order.

type PriceParamType

type PriceParamType int32

PriceParamType represents the type of price parameter used in PriceParams.

const (
	AbsoluteValuePrice PriceParamType = iota
	RelativeValuePrice
	RelativePercentValuePrice
)

The following constants define every possible PriceParamType

type PriceParams

type PriceParams []*PriceParam

PriceParams is a list of price parameters that define the input to an order. Usually you will just need one PriceParam input, but some order types take multiple PriceParam inputs, such as TrailingStopLossOrder. TODO document different PriceParam uses

type PrivateOrder

type PrivateOrder struct {
	PriceParams PriceParams
	Amount      string
	OrderSide   OrderSide
	OrderType   OrderType
	FundingType FundingType
	ExpireTime  time.Time

	// Set by server and updated internally by client.
	// ID previously was ExternalID.
	ID           string
	Timestamp    time.Time
	Leverage     string
	CurrentStop  string
	InitialStop  string
	AmountFilled string

	// Broker error code; 0 if successful
	Error int32
}

PrivateOrder represents an order you have placed on an exchange, either through the TradeClient, or on the exchange itself.

func (PrivateOrder) CacheKey

func (o PrivateOrder) CacheKey(mID MarketID) string

CacheKey returns the key composed by joining the market ID with the ID.

func (PrivateOrder) String

func (o PrivateOrder) String() string

String implmements the fmt.Stringer interface for PrivateOrder.

type PrivateOrders

type PrivateOrders []PrivateOrder

func (PrivateOrders) Len

func (os PrivateOrders) Len() int

func (PrivateOrders) Less

func (os PrivateOrders) Less(i, j int) bool

func (PrivateOrders) Swap

func (os PrivateOrders) Swap(i, j int)

type PrivatePosition

type PrivatePosition struct {
	ExternalID   string
	Timestamp    time.Time
	OrderSide    OrderSide
	AvgPrice     string
	AmountOpen   string
	AmountClosed string
	OrderIDs     []string
	TradeIDs     []string
}

PrivatePosition represents one of your positions on an exchange.

type PrivatePositions

type PrivatePositions []PrivatePosition

func (PrivatePositions) Len

func (ps PrivatePositions) Len() int

func (PrivatePositions) Less

func (ps PrivatePositions) Less(i, j int) bool

func (PrivatePositions) Swap

func (ps PrivatePositions) Swap(i, j int)

type PrivateTrade

type PrivateTrade struct {
	ExternalID string
	OrderID    string
	Timestamp  time.Time
	Price      string
	Amount     string
	OrderSide  OrderSide
}

PrivateTrade represents a trade made on your account.

type PrivateTrades

type PrivateTrades []PrivateTrade

func (PrivateTrades) Len

func (ts PrivateTrades) Len() int

func (PrivateTrades) Less

func (ts PrivateTrades) Less(i, j int) bool

func (PrivateTrades) Swap

func (ts PrivateTrades) Swap(i, j int)

type PublicOrder

type PublicOrder struct {
	Price  decimal.Decimal
	Amount decimal.Decimal
}

PublicOrder represents a public order placed on an exchange. They often come as a slice of PublicOrder, which come with order book updates.

func ApplyDeltas

func ApplyDeltas(orders []PublicOrder, deltas *OrderDeltas, reverse bool) []PublicOrder

ApplyDeltas applies given deltas to the slice of orders, and returns a newly allocated slice of orders, sorted by price accordingly to reverse argument.

type PublicTrade

type PublicTrade struct {
	// ExternalID is given by the exchange, and not Cryptowatch. NOTE some of
	// these may be "0" since we still use int64 on the back end to represent
	// these IDs, and some are strings.
	ExternalID string
	Timestamp  time.Time
	Price      decimal.Decimal
	Amount     decimal.Decimal
	OrderSide  OrderSide
}

PublicTrade represents a trade made on an exchange. See TradesUpdate and OnTradesUpdate.

type SeqNum

type SeqNum uint32

SeqNum is used to make sure order book deltas are processed in order. Each order book delta update has the sequence number incremented by 1. Sometimes sequence numbers reset to a smaller value (this happens when we deploy or restart our back end for whatever reason). In those cases, the first broadcasted update is a snapshot, so clients should not assume they are out of sync when they receive a snapshot with a lower seq number.

type SparklineUpdate

type SparklineUpdate struct {
	Timestamp time.Time
	Price     decimal.Decimal
}

SparklineUpdate represents the sparkline update for a market at a particular time. A sparkline is a very small line chart, typically drawn without axes or coordinates. It presents the general shape of the variation in price. https://en.wikipedia.org/wiki/Sparkline

type SummaryUpdate

type SummaryUpdate struct {
	Last           decimal.Decimal
	High           decimal.Decimal
	Low            decimal.Decimal
	VolumeBase     decimal.Decimal
	VolumeQuote    decimal.Decimal
	ChangeAbsolute decimal.Decimal
	ChangePercent  decimal.Decimal
	NumTrades      int32
}

SummaryUpdate represents recent summary information for a particular market.

type TradesUpdate

type TradesUpdate struct {
	Trades []PublicTrade
}

TradesUpdate represents the most recent trades that have occurred for a particular market.

type TrendlineUpdate

type TrendlineUpdate struct {
	Window    PerformanceWindow
	Timestamp time.Time
	Price     decimal.Decimal
	Volume    decimal.Decimal
}

TrendlineUpdate represents the trendline update for a market for a particular window. TODO explain calculation

type VWAPUpdate

type VWAPUpdate struct {
	VWAP      decimal.Decimal
	Timestamp time.Time
}

VWAPUpdate represents the most recent volume weighted average price update for a market at a given time. TODO explain calculation

Jump to

Keyboard shortcuts

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