types

package
v1.22.3 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2021 License: MIT Imports: 21 Imported by: 161

Documentation

Index

Constants

View Source
const (
	AccountTypeFutures = AccountType("futures")
	AccountTypeSpot    = AccountType("spot")
)
View Source
const (
	DepositPending = DepositStatus("pending")

	DepositRejected = DepositStatus("rejected")

	DepositSuccess = DepositStatus("success")

	DepositCancelled = DepositStatus("canceled")

	// created but can not withdraw
	DepositCredited = DepositStatus("credited")
)
View Source
const (
	ExchangeMax      = ExchangeName("max")
	ExchangeBinance  = ExchangeName("binance")
	ExchangeFTX      = ExchangeName("ftx")
	ExchangeOKEx     = ExchangeName("okex")
	ExchangeKucoin   = ExchangeName("kucoin")
	ExchangeBacktest = ExchangeName("backtest")
)
View Source
const (
	Red   = Color(false)
	Black = Color(true)
)
View Source
const (
	RewardAirdrop    = RewardType("airdrop")
	RewardCommission = RewardType("commission")
	RewardHolding    = RewardType("holding")
	RewardMining     = RewardType("mining")
	RewardTrading    = RewardType("trading")
	RewardVipRebate  = RewardType("vip_rebate")
)
View Source
const (
	SideTypeBuy  = SideType("BUY")
	SideTypeSell = SideType("SELL")
	SideTypeSelf = SideType("SELF")

	// SideTypeBoth is only used for the configuration context
	SideTypeBoth = SideType("BOTH")
)
View Source
const DateFormat = "2006-01-02"
View Source
const DirectionDown = -1
View Source
const DirectionNone = 0
View Source
const DirectionUp = 1
View Source
const GrayColor = "#f0f0f0"
View Source
const GreenColor = "#228B22"
View Source
const NoClientOrderID = "0"
View Source
const RedColor = "#800000"

Variables

View Source
var BNB = accounting.Accounting{Symbol: "BNB ", Precision: 4}
View Source
var BTC = accounting.Accounting{Symbol: "BTC ", Precision: 8}
View Source
var BookChannel = Channel("book")
View Source
var BookTickerChannel = Channel("bookticker")
View Source
var ErrInvalidSideType = errors.New("invalid side type")
View Source
var FiatCurrencies = []string{"USDC", "USDT", "USD", "TWD", "EUR", "GBP", "BUSD"}
View Source
var Interval12h = Interval("12h")
View Source
var Interval15m = Interval("15m")
View Source
var Interval1d = Interval("1d")
View Source
var Interval1h = Interval("1h")
View Source
var Interval1m = Interval("1m")
View Source
var Interval2h = Interval("2h")
View Source
var Interval30m = Interval("30m")
View Source
var Interval3d = Interval("3d")
View Source
var Interval4h = Interval("4h")
View Source
var Interval5m = Interval("5m")
View Source
var Interval6h = Interval("6h")
View Source
var KLineChannel = Channel("kline")
View Source
var SupportedExchanges = []ExchangeName{"binance", "max", "ftx", "okex", "kucoin"}
View Source
var SupportedIntervals = map[Interval]int{
	Interval1m:  1,
	Interval5m:  5,
	Interval15m: 15,
	Interval30m: 30,
	Interval1h:  60,
	Interval2h:  60 * 2,
	Interval4h:  60 * 4,
	Interval6h:  60 * 6,
	Interval12h: 60 * 12,
	Interval1d:  60 * 24,
	Interval3d:  60 * 24 * 3,
}
View Source
var USD = accounting.Accounting{Symbol: "$ ", Precision: 2}

Functions

func IsFiatCurrency added in v1.18.1

func IsFiatCurrency(currency string) bool

func MustParseUnixTimestamp added in v1.21.0

func MustParseUnixTimestamp(a string) time.Time

func SideToColorName

func SideToColorName(side SideType) string

Types

type Account

type Account struct {
	sync.Mutex `json:"-"`

	AccountType AccountType `json:"accountType,omitempty"`
	FuturesInfo *FuturesAccountInfo

	MakerFeeRate fixedpoint.Value `json:"makerFeeRate,omitempty"`
	TakerFeeRate fixedpoint.Value `json:"takerFeeRate,omitempty"`

	// bps. 0.15% fee will be 15.
	MakerCommission fixedpoint.Value `json:"makerCommission,omitempty"`
	TakerCommission fixedpoint.Value `json:"takerCommission,omitempty"`

	TotalAccountValue fixedpoint.Value `json:"totalAccountValue,omitempty"`

	CanDeposit  bool `json:"canDeposit"`
	CanTrade    bool `json:"canTrade"`
	CanWithdraw bool `json:"canWithdraw"`
	// contains filtered or unexported fields
}

func NewAccount

func NewAccount() *Account

func (*Account) AddBalance

func (a *Account) AddBalance(currency string, fund fixedpoint.Value)

func (*Account) Balance

func (a *Account) Balance(currency string) (balance Balance, ok bool)

func (*Account) Balances

func (a *Account) Balances() (d BalanceMap)

Balances lock the balances and returned the copied balances

func (*Account) BindStream

func (a *Account) BindStream(stream Stream)

func (*Account) LockBalance

func (a *Account) LockBalance(currency string, locked fixedpoint.Value) error

func (*Account) Print

func (a *Account) Print()

func (*Account) UnlockBalance

func (a *Account) UnlockBalance(currency string, unlocked fixedpoint.Value) error

func (*Account) UpdateBalances

func (a *Account) UpdateBalances(balances BalanceMap)

func (*Account) UseLockedBalance

func (a *Account) UseLockedBalance(currency string, fund fixedpoint.Value) error

type AccountType added in v1.18.5

type AccountType string

type Asset added in v1.11.0

type Asset struct {
	Currency  string           `json:"currency" db:"currency"`
	Total     fixedpoint.Value `json:"total" db:"total"`
	InUSD     fixedpoint.Value `json:"inUSD" db:"inUSD"`
	InBTC     fixedpoint.Value `json:"inBTC" db:"inBTC"`
	Time      time.Time        `json:"time" db:"time"`
	Locked    fixedpoint.Value `json:"lock" db:"lock" `
	Available fixedpoint.Value `json:"available"  db:"available"`
}

type AssetMap added in v1.11.0

type AssetMap map[string]Asset

func (AssetMap) PlainText added in v1.18.0

func (m AssetMap) PlainText() (o string)

func (AssetMap) SlackAttachment added in v1.18.0

func (m AssetMap) SlackAttachment() slack.Attachment

func (AssetMap) Slice added in v1.18.0

func (m AssetMap) Slice() (assets []Asset)

type Balance

type Balance struct {
	Currency  string           `json:"currency"`
	Available fixedpoint.Value `json:"available"`
	Locked    fixedpoint.Value `json:"locked"`
}

func (Balance) String added in v1.2.0

func (b Balance) String() string

func (Balance) Total added in v1.11.1

func (b Balance) Total() fixedpoint.Value

type BalanceMap

type BalanceMap map[string]Balance

func (BalanceMap) Assets added in v1.11.0

func (m BalanceMap) Assets(prices map[string]float64) AssetMap

func (BalanceMap) Copy added in v1.18.0

func (m BalanceMap) Copy() (d BalanceMap)

func (BalanceMap) Print

func (m BalanceMap) Print()

func (BalanceMap) String added in v1.2.0

func (m BalanceMap) String() string

type BookTicker added in v1.21.0

type BookTicker struct {
	//Time     time.Time
	Symbol   string
	Buy      fixedpoint.Value // `buy` from Max, `bidPrice` from binance
	BuySize  fixedpoint.Value
	Sell     fixedpoint.Value // `sell` from Max, `askPrice` from binance
	SellSize fixedpoint.Value
}

BookTicker time exists in ftx, not in binance last exists in ftx, not in binance

func (BookTicker) String added in v1.21.0

func (b BookTicker) String() string

type Channel

type Channel string

type Color added in v1.17.0

type Color bool

Color is the RB Tree color

type CustomIntervalProvider added in v1.21.0

type CustomIntervalProvider interface {
	SupportedInterval() map[Interval]int
	IsSupportedInterval(interval Interval) bool
}

type Deposit

type Deposit struct {
	GID           int64         `json:"gid" db:"gid"`
	Exchange      ExchangeName  `json:"exchange" db:"exchange"`
	Time          Time          `json:"time" db:"time"`
	Amount        float64       `json:"amount" db:"amount"`
	Asset         string        `json:"asset" db:"asset"`
	Address       string        `json:"address" db:"address"`
	AddressTag    string        `json:"addressTag"`
	TransactionID string        `json:"transactionID" db:"txn_id"`
	Status        DepositStatus `json:"status"`
}

func (Deposit) EffectiveTime

func (d Deposit) EffectiveTime() time.Time

type DepositStatus

type DepositStatus string

type Direction added in v1.2.1

type Direction int

type Duration added in v1.3.1

type Duration time.Duration

func (Duration) Duration added in v1.3.1

func (d Duration) Duration() time.Duration

func (*Duration) UnmarshalJSON added in v1.3.1

func (d *Duration) UnmarshalJSON(data []byte) error

type Exchange

type Exchange interface {
	Name() ExchangeName

	PlatformFeeCurrency() string

	ExchangeMarketDataService

	ExchangeTradeService
}

type ExchangeFee added in v1.21.0

type ExchangeFee struct {
	MakerFeeRate fixedpoint.Value
	TakerFeeRate fixedpoint.Value
}

type ExchangeMarketDataService added in v1.14.0

type ExchangeMarketDataService interface {
	NewStream() Stream

	QueryMarkets(ctx context.Context) (MarketMap, error)

	QueryTicker(ctx context.Context, symbol string) (*Ticker, error)

	QueryTickers(ctx context.Context, symbol ...string) (map[string]Ticker, error)

	QueryKLines(ctx context.Context, symbol string, interval Interval, options KLineQueryOptions) ([]KLine, error)
}

type ExchangeName

type ExchangeName string

func ValidExchangeName

func ValidExchangeName(a string) (ExchangeName, error)

func (ExchangeName) String

func (n ExchangeName) String() string

func (*ExchangeName) UnmarshalJSON added in v1.11.1

func (n *ExchangeName) UnmarshalJSON(data []byte) error

func (*ExchangeName) Value added in v1.14.0

func (n *ExchangeName) Value() (driver.Value, error)

type ExchangeRewardService added in v1.13.0

type ExchangeRewardService interface {
	QueryRewards(ctx context.Context, startTime time.Time) ([]Reward, error)
}

type ExchangeTradeHistoryService added in v1.17.0

type ExchangeTradeHistoryService interface {
	QueryTrades(ctx context.Context, symbol string, options *TradeQueryOptions) ([]Trade, error)
	QueryClosedOrders(ctx context.Context, symbol string, since, until time.Time, lastOrderID uint64) (orders []Order, err error)
}

type ExchangeTradeService added in v1.17.0

type ExchangeTradeService interface {
	QueryAccount(ctx context.Context) (*Account, error)

	QueryAccountBalances(ctx context.Context) (BalanceMap, error)

	SubmitOrders(ctx context.Context, orders ...SubmitOrder) (createdOrders OrderSlice, err error)

	QueryOpenOrders(ctx context.Context, symbol string) (orders []Order, err error)

	CancelOrders(ctx context.Context, orders ...Order) error
}

type ExchangeTransferService added in v1.14.0

type ExchangeTransferService interface {
	QueryDepositHistory(ctx context.Context, asset string, since, until time.Time) (allDeposits []Deposit, err error)
	QueryWithdrawHistory(ctx context.Context, asset string, since, until time.Time) (allWithdraws []Withdraw, err error)
}

type ExchangeWithdrawalService added in v1.16.0

type ExchangeWithdrawalService interface {
	Withdrawal(ctx context.Context, asset string, amount fixedpoint.Value, address string, options *WithdrawalOptions) error
}

type Float64Indicator added in v1.17.1

type Float64Indicator interface {
	Last() float64
}

Float64Indicator is the indicators (SMA and EWMA) that we want to use are returning float64 data.

type Float64Slice added in v1.17.0

type Float64Slice []float64

func (Float64Slice) Max added in v1.17.0

func (s Float64Slice) Max() float64

func (Float64Slice) Mean added in v1.17.0

func (s Float64Slice) Mean() (mean float64)

func (Float64Slice) Min added in v1.17.0

func (s Float64Slice) Min() float64

func (*Float64Slice) Pop added in v1.17.0

func (s *Float64Slice) Pop(i int64) (v float64)

func (*Float64Slice) Push added in v1.17.0

func (s *Float64Slice) Push(v float64)

func (Float64Slice) Sum added in v1.17.0

func (s Float64Slice) Sum() (sum float64)

func (Float64Slice) Tail added in v1.17.0

func (s Float64Slice) Tail(size int) Float64Slice

type FundingRate added in v1.21.0

type FundingRate struct {
	FundingRate fixedpoint.Value
	FundingTime time.Time
	Time        time.Time
}

type FuturesAccountInfo added in v1.21.0

type FuturesAccountInfo struct {
	// Futures fields
	Assets                      map[Asset]FuturesUserAsset `json:"assets"`
	FeeTier                     int                        `json:"feeTier"`
	MaxWithdrawAmount           fixedpoint.Value           `json:"maxWithdrawAmount"`
	Positions                   FuturesPositionMap         `json:"positions"`
	TotalInitialMargin          fixedpoint.Value           `json:"totalInitialMargin"`
	TotalMaintMargin            fixedpoint.Value           `json:"totalMaintMargin"`
	TotalMarginBalance          fixedpoint.Value           `json:"totalMarginBalance"`
	TotalOpenOrderInitialMargin fixedpoint.Value           `json:"totalOpenOrderInitialMargin"`
	TotalPositionInitialMargin  fixedpoint.Value           `json:"totalPositionInitialMargin"`
	TotalUnrealizedProfit       fixedpoint.Value           `json:"totalUnrealizedProfit"`
	TotalWalletBalance          fixedpoint.Value           `json:"totalWalletBalance"`
	UpdateTime                  int64                      `json:"updateTime"`
}

type FuturesExchange added in v1.18.0

type FuturesExchange interface {
	UseFutures()
	UseIsolatedFutures(symbol string)
	GetFuturesSettings() FuturesSettings
}

type FuturesPosition added in v1.22.0

type FuturesPosition struct {
	Symbol        string `json:"symbol"`
	BaseCurrency  string `json:"baseCurrency"`
	QuoteCurrency string `json:"quoteCurrency"`

	Market Market `json:"market"`

	Base        fixedpoint.Value `json:"base"`
	Quote       fixedpoint.Value `json:"quote"`
	AverageCost fixedpoint.Value `json:"averageCost"`

	// ApproximateAverageCost adds the computed fee in quote in the average cost
	// This is used for calculating net profit
	ApproximateAverageCost fixedpoint.Value `json:"approximateAverageCost"`

	FeeRate          *ExchangeFee                 `json:"feeRate,omitempty"`
	ExchangeFeeRates map[ExchangeName]ExchangeFee `json:"exchangeFeeRates"`

	// Futures data fields
	Isolated     bool  `json:"isolated"`
	UpdateTime   int64 `json:"updateTime"`
	PositionRisk *PositionRisk

	sync.Mutex
}

type FuturesPositionMap added in v1.22.0

type FuturesPositionMap map[string]FuturesPosition

type FuturesSettings added in v1.18.0

type FuturesSettings struct {
	IsFutures             bool
	IsIsolatedFutures     bool
	IsolatedFuturesSymbol string
}

func (FuturesSettings) GetFuturesSettings added in v1.18.0

func (s FuturesSettings) GetFuturesSettings() FuturesSettings

func (*FuturesSettings) UseFutures added in v1.18.0

func (s *FuturesSettings) UseFutures()

func (*FuturesSettings) UseIsolatedFutures added in v1.18.5

func (s *FuturesSettings) UseIsolatedFutures(symbol string)

type FuturesUserAsset added in v1.21.0

type FuturesUserAsset struct {
	Asset                  string           `json:"asset"`
	InitialMargin          fixedpoint.Value `json:"initialMargin"`
	MaintMargin            fixedpoint.Value `json:"maintMargin"`
	MarginBalance          fixedpoint.Value `json:"marginBalance"`
	MaxWithdrawAmount      fixedpoint.Value `json:"maxWithdrawAmount"`
	OpenOrderInitialMargin fixedpoint.Value `json:"openOrderInitialMargin"`
	PositionInitialMargin  fixedpoint.Value `json:"positionInitialMargin"`
	UnrealizedProfit       fixedpoint.Value `json:"unrealizedProfit"`
	WalletBalance          fixedpoint.Value `json:"walletBalance"`
}

FuturesUserAsset define cross/isolated futures account asset

type Interval

type Interval string

func (Interval) Duration

func (i Interval) Duration() time.Duration

func (Interval) Minutes

func (i Interval) Minutes() int

func (Interval) String

func (i Interval) String() string

func (*Interval) UnmarshalJSON

func (i *Interval) UnmarshalJSON(b []byte) (err error)

type IntervalSlice

type IntervalSlice []Interval

func (IntervalSlice) StringSlice

func (s IntervalSlice) StringSlice() (slice []string)

type IntervalWindow

type IntervalWindow struct {
	// The interval of kline
	Interval Interval `json:"interval"`

	// The windows size of the indicator (EWMA and SMA)
	Window int `json:"window"`
}

IntervalWindow is used by the indicators

func (IntervalWindow) String added in v1.4.0

func (iw IntervalWindow) String() string

type IsolatedMarginAccount added in v1.13.0

type IsolatedMarginAccount struct {
	TotalAssetOfBTC     fixedpoint.Value      `json:"totalAssetOfBtc"`
	TotalLiabilityOfBTC fixedpoint.Value      `json:"totalLiabilityOfBtc"`
	TotalNetAssetOfBTC  fixedpoint.Value      `json:"totalNetAssetOfBtc"`
	Assets              []IsolatedMarginAsset `json:"assets"`
}

IsolatedMarginAccount defines isolated user assets of margin account

type IsolatedMarginAsset added in v1.13.0

type IsolatedMarginAsset struct {
	Symbol     string            `json:"symbol"`
	QuoteAsset IsolatedUserAsset `json:"quoteAsset"`
	BaseAsset  IsolatedUserAsset `json:"baseAsset"`

	IsolatedCreated   bool             `json:"isolatedCreated"`
	MarginLevel       fixedpoint.Value `json:"marginLevel"`
	MarginLevelStatus string           `json:"marginLevelStatus"`

	MarginRatio    fixedpoint.Value `json:"marginRatio"`
	IndexPrice     fixedpoint.Value `json:"indexPrice"`
	LiquidatePrice fixedpoint.Value `json:"liquidatePrice"`
	LiquidateRate  fixedpoint.Value `json:"liquidateRate"`

	TradeEnabled bool `json:"tradeEnabled"`
}

IsolatedMarginAsset defines isolated margin asset information, like margin level, liquidation price... etc

type IsolatedUserAsset added in v1.13.0

type IsolatedUserAsset struct {
	Asset         string           `json:"asset"`
	Borrowed      fixedpoint.Value `json:"borrowed"`
	Free          fixedpoint.Value `json:"free"`
	Interest      fixedpoint.Value `json:"interest"`
	Locked        fixedpoint.Value `json:"locked"`
	NetAsset      fixedpoint.Value `json:"netAsset"`
	NetAssetOfBtc fixedpoint.Value `json:"netAssetOfBtc"`

	BorrowEnabled bool             `json:"borrowEnabled"`
	RepayEnabled  bool             `json:"repayEnabled"`
	TotalAsset    fixedpoint.Value `json:"totalAsset"`
}

IsolatedUserAsset defines isolated user assets of the margin account

type KLine

type KLine struct {
	GID      uint64       `json:"gid" db:"gid"`
	Exchange ExchangeName `json:"exchange" db:"exchange"`

	Symbol string `json:"symbol" db:"symbol"`

	StartTime Time `json:"startTime" db:"start_time"`
	EndTime   Time `json:"endTime" db:"end_time"`

	Interval Interval `json:"interval" db:"interval"`

	Open                     float64 `json:"open" db:"open"`
	Close                    float64 `json:"close" db:"close"`
	High                     float64 `json:"high" db:"high"`
	Low                      float64 `json:"low" db:"low"`
	Volume                   float64 `json:"volume" db:"volume"`
	QuoteVolume              float64 `json:"quoteVolume" db:"quote_volume"`
	TakerBuyBaseAssetVolume  float64 `json:"takerBuyBaseAssetVolume" db:"taker_buy_base_volume"`
	TakerBuyQuoteAssetVolume float64 `json:"takerBuyQuoteAssetVolume" db:"taker_buy_quote_volume"`

	LastTradeID    uint64 `json:"lastTradeID" db:"last_trade_id"`
	NumberOfTrades uint64 `json:"numberOfTrades" db:"num_trades"`
	Closed         bool   `json:"closed" db:"closed"`
}

KLine uses binance's kline as the standard structure

func (KLine) BounceDown

func (k KLine) BounceDown() bool

red candle with open and close near low price

func (KLine) BounceUp

func (k KLine) BounceUp() bool

green candle with open and close near high price

func (KLine) Color

func (k KLine) Color() string

func (KLine) Direction added in v1.2.1

func (k KLine) Direction() Direction

func (KLine) GetBody

func (k KLine) GetBody() float64

GetBody returns the height of the candle real body

func (KLine) GetChange

func (k KLine) GetChange() float64

GetChange returns Close price - Open price.

func (KLine) GetClose

func (k KLine) GetClose() float64

func (KLine) GetEndTime

func (k KLine) GetEndTime() Time

func (KLine) GetHigh

func (k KLine) GetHigh() float64

func (KLine) GetInterval

func (k KLine) GetInterval() Interval

func (KLine) GetLow

func (k KLine) GetLow() float64

func (KLine) GetLowerShadowHeight

func (k KLine) GetLowerShadowHeight() float64

func (KLine) GetLowerShadowRatio

func (k KLine) GetLowerShadowRatio() float64

func (KLine) GetMaxChange

func (k KLine) GetMaxChange() float64

func (KLine) GetOpen

func (k KLine) GetOpen() float64

func (KLine) GetStartTime

func (k KLine) GetStartTime() Time

func (KLine) GetThickness

func (k KLine) GetThickness() float64

GetThickness returns the thickness of the kline. 1 => thick, 0.1 => thin

func (KLine) GetUpperShadowHeight

func (k KLine) GetUpperShadowHeight() float64

func (KLine) GetUpperShadowRatio

func (k KLine) GetUpperShadowRatio() float64

func (KLine) Mid

func (k KLine) Mid() float64

func (KLine) PlainText added in v1.18.0

func (k KLine) PlainText() string

func (KLine) SlackAttachment

func (k KLine) SlackAttachment() slack.Attachment

func (KLine) String

func (k KLine) String() string

type KLineCallback

type KLineCallback func(kline KLine)

type KLineOrWindow

type KLineOrWindow interface {
	GetInterval() string
	Direction() Direction
	GetChange() float64
	GetMaxChange() float64
	GetThickness() float64

	Mid() float64
	GetOpen() float64
	GetClose() float64
	GetHigh() float64
	GetLow() float64

	BounceUp() bool
	BounceDown() bool
	GetUpperShadowRatio() float64
	GetLowerShadowRatio() float64

	SlackAttachment() slack.Attachment
}

type KLineQueryOptions

type KLineQueryOptions struct {
	Limit     int
	StartTime *time.Time
	EndTime   *time.Time
}

type KLineWindow

type KLineWindow []KLine

func (*KLineWindow) Add

func (k *KLineWindow) Add(line KLine)

func (KLineWindow) AllDrop

func (k KLineWindow) AllDrop() bool

func (KLineWindow) AllRise

func (k KLineWindow) AllRise() bool

func (KLineWindow) BounceDown

func (k KLineWindow) BounceDown() bool

BounceDown returns true red candle with open and close near low price

func (KLineWindow) BounceUp

func (k KLineWindow) BounceUp() bool

BounceUp returns true if it's green candle with open and close near high price

func (KLineWindow) Color

func (k KLineWindow) Color() string

func (KLineWindow) First

func (k KLineWindow) First() KLine

func (KLineWindow) GetBody

func (k KLineWindow) GetBody() float64

func (KLineWindow) GetChange

func (k KLineWindow) GetChange() float64

func (KLineWindow) GetClose

func (k KLineWindow) GetClose() float64

func (KLineWindow) GetHigh

func (k KLineWindow) GetHigh() float64

func (KLineWindow) GetInterval

func (k KLineWindow) GetInterval() Interval

func (KLineWindow) GetLow

func (k KLineWindow) GetLow() float64

func (KLineWindow) GetLowerShadowHeight

func (k KLineWindow) GetLowerShadowHeight() float64

func (KLineWindow) GetLowerShadowRatio

func (k KLineWindow) GetLowerShadowRatio() float64

func (KLineWindow) GetMaxChange

func (k KLineWindow) GetMaxChange() float64

func (KLineWindow) GetOpen

func (k KLineWindow) GetOpen() float64

func (KLineWindow) GetThickness

func (k KLineWindow) GetThickness() float64

func (KLineWindow) GetTrend

func (k KLineWindow) GetTrend() int

func (KLineWindow) GetUpperShadowHeight

func (k KLineWindow) GetUpperShadowHeight() float64

func (KLineWindow) GetUpperShadowRatio

func (k KLineWindow) GetUpperShadowRatio() float64

func (KLineWindow) Last

func (k KLineWindow) Last() KLine

func (KLineWindow) Len

func (k KLineWindow) Len() int

func (KLineWindow) Mid

func (k KLineWindow) Mid() float64

Mid price

func (KLineWindow) ReduceClose

func (k KLineWindow) ReduceClose() float64

ReduceClose reduces the closed prices

func (KLineWindow) SlackAttachment

func (k KLineWindow) SlackAttachment() slack.Attachment

func (KLineWindow) Tail

func (k KLineWindow) Tail(size int) KLineWindow

func (KLineWindow) Take

func (k KLineWindow) Take(size int) KLineWindow

func (*KLineWindow) Truncate

func (k *KLineWindow) Truncate(size int)

Truncate removes the old klines from the window

type MarginAccount added in v1.13.0

type MarginAccount struct {
	BorrowEnabled       bool              `json:"borrowEnabled"`
	MarginLevel         fixedpoint.Value  `json:"marginLevel"`
	TotalAssetOfBTC     fixedpoint.Value  `json:"totalAssetOfBtc"`
	TotalLiabilityOfBTC fixedpoint.Value  `json:"totalLiabilityOfBtc"`
	TotalNetAssetOfBTC  fixedpoint.Value  `json:"totalNetAssetOfBtc"`
	TradeEnabled        bool              `json:"tradeEnabled"`
	TransferEnabled     bool              `json:"transferEnabled"`
	UserAssets          []MarginUserAsset `json:"userAssets"`
}

MarginAccount is for the cross margin account

type MarginExchange added in v1.8.0

type MarginExchange interface {
	UseMargin()
	UseIsolatedMargin(symbol string)
	GetMarginSettings() MarginSettings
}

type MarginOrderSideEffectType added in v1.8.0

type MarginOrderSideEffectType string

MarginOrderSideEffectType define side effect type for orders

var (
	SideEffectTypeNoSideEffect MarginOrderSideEffectType = "NO_SIDE_EFFECT"
	SideEffectTypeMarginBuy    MarginOrderSideEffectType = "MARGIN_BUY"
	SideEffectTypeAutoRepay    MarginOrderSideEffectType = "AUTO_REPAY"
)

func (*MarginOrderSideEffectType) UnmarshalJSON added in v1.11.0

func (t *MarginOrderSideEffectType) UnmarshalJSON(data []byte) error

type MarginSettings added in v1.8.0

type MarginSettings struct {
	IsMargin             bool
	IsIsolatedMargin     bool
	IsolatedMarginSymbol string
}

func (MarginSettings) GetMarginSettings added in v1.8.0

func (e MarginSettings) GetMarginSettings() MarginSettings

func (*MarginSettings) UseIsolatedMargin added in v1.8.0

func (e *MarginSettings) UseIsolatedMargin(symbol string)

func (*MarginSettings) UseMargin added in v1.8.0

func (e *MarginSettings) UseMargin()

type MarginUserAsset added in v1.13.0

type MarginUserAsset struct {
	Asset    string           `json:"asset"`
	Borrowed fixedpoint.Value `json:"borrowed"`
	Free     fixedpoint.Value `json:"free"`
	Interest fixedpoint.Value `json:"interest"`
	Locked   fixedpoint.Value `json:"locked"`
	NetAsset fixedpoint.Value `json:"netAsset"`
}

MarginUserAsset define user assets of margin account

type Market

type Market struct {
	Symbol string `json:"symbol"`

	// LocalSymbol is used for exchange's API (exchange package internal)
	LocalSymbol string `json:"localSymbol,omitempty"`

	// PricePrecision is the precision used for formatting price, 8 = 8 decimals
	// can be converted from price tick step size, e.g.
	//    int(math.Log10(price step size))
	PricePrecision int `json:"pricePrecision"`

	// VolumePrecision is the precision used for formatting quantity and volume, 8 = 8 decimals
	// can be converted from step size, e.g.
	//    int(math.Log10(quantity step size))
	VolumePrecision int `json:"volumePrecision"`

	// QuoteCurrency is the currency name for quote, e.g. USDT in BTC/USDT, USDC in BTC/USDC
	QuoteCurrency string `json:"quoteCurrency"`

	// BaseCurrency is the current name for base, e.g. BTC in BTC/USDT, ETH in ETH/USDC
	BaseCurrency string `json:"baseCurrency"`

	// The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol.
	// An order's notional value is the price * quantity
	MinNotional float64 `json:"minNotional,omitempty"`
	MinAmount   float64 `json:"minAmount,omitempty"`

	// The LOT_SIZE filter defines the quantity
	MinQuantity float64 `json:"minQuantity,omitempty"`

	// MaxQuantity is currently not used in the code
	MaxQuantity float64 `json:"maxQuantity,omitempty"`

	// StepSize is the step size of quantity
	// can be converted from precision, e.g.
	//    1.0 / math.Pow10(m.BaseUnitPrecision)
	StepSize float64 `json:"stepSize,omitempty"`

	MinPrice float64 `json:"minPrice,omitempty"`
	MaxPrice float64 `json:"maxPrice,omitempty"`

	// TickSize is the step size of price
	TickSize float64 `json:"tickSize,omitempty"`
}

func (Market) BaseCurrencyFormatter added in v1.18.0

func (m Market) BaseCurrencyFormatter() *accounting.Accounting

func (Market) CanonicalizeVolume

func (m Market) CanonicalizeVolume(val float64) float64

func (Market) FormatPrice

func (m Market) FormatPrice(val float64) string

func (Market) FormatPriceCurrency

func (m Market) FormatPriceCurrency(val float64) string

func (Market) FormatQuantity

func (m Market) FormatQuantity(val float64) string

func (Market) FormatVolume

func (m Market) FormatVolume(val float64) string

func (Market) QuoteCurrencyFormatter added in v1.18.0

func (m Market) QuoteCurrencyFormatter() *accounting.Accounting

func (Market) TruncateQuantity added in v1.21.0

func (m Market) TruncateQuantity(quantity fixedpoint.Value) fixedpoint.Value

TruncateQuantity uses the step size to truncate floating number, in order to avoid the rounding issue

type MarketMap

type MarketMap map[string]Market

func (MarketMap) Add added in v1.21.0

func (m MarketMap) Add(market Market)

type MillisecondTimestamp added in v1.17.0

type MillisecondTimestamp time.Time

func MustParseMillisecondTimestamp added in v1.21.0

func MustParseMillisecondTimestamp(a string) MillisecondTimestamp

func NewMillisecondTimestampFromInt added in v1.21.0

func NewMillisecondTimestampFromInt(i int64) MillisecondTimestamp

func (MillisecondTimestamp) String added in v1.17.0

func (t MillisecondTimestamp) String() string

func (MillisecondTimestamp) Time added in v1.17.0

func (t MillisecondTimestamp) Time() time.Time

func (*MillisecondTimestamp) UnmarshalJSON added in v1.17.0

func (t *MillisecondTimestamp) UnmarshalJSON(data []byte) error

type MutexOrderBook

type MutexOrderBook struct {
	sync.Mutex

	Symbol    string
	OrderBook OrderBook
}

func NewMutexOrderBook

func NewMutexOrderBook(symbol string) *MutexOrderBook

func (*MutexOrderBook) BestAsk added in v1.17.0

func (b *MutexOrderBook) BestAsk() (pv PriceVolume, ok bool)

func (*MutexOrderBook) BestBid added in v1.17.0

func (b *MutexOrderBook) BestBid() (pv PriceVolume, ok bool)

func (*MutexOrderBook) BestBidAndAsk added in v1.17.0

func (b *MutexOrderBook) BestBidAndAsk() (bid, ask PriceVolume, ok bool)

func (*MutexOrderBook) Copy added in v1.17.0

func (b *MutexOrderBook) Copy() OrderBook

func (*MutexOrderBook) CopyDepth added in v1.17.0

func (b *MutexOrderBook) CopyDepth(depth int) OrderBook

func (*MutexOrderBook) IsValid added in v1.17.0

func (b *MutexOrderBook) IsValid() (ok bool, err error)

func (*MutexOrderBook) Load

func (b *MutexOrderBook) Load(book SliceOrderBook)

func (*MutexOrderBook) Reset added in v1.11.0

func (b *MutexOrderBook) Reset()

func (*MutexOrderBook) Update

func (b *MutexOrderBook) Update(update SliceOrderBook)

type NanosecondTimestamp added in v1.21.3

type NanosecondTimestamp time.Time

func (NanosecondTimestamp) Time added in v1.21.3

func (t NanosecondTimestamp) Time() time.Time

func (*NanosecondTimestamp) UnmarshalJSON added in v1.21.3

func (t *NanosecondTimestamp) UnmarshalJSON(data []byte) error

type Order

type Order struct {
	SubmitOrder

	Exchange ExchangeName `json:"exchange" db:"exchange"`

	// GID is used for relational database storage, it's an incremental ID
	GID     uint64 `json:"gid" db:"gid"`
	OrderID uint64 `json:"orderID" db:"order_id"` // order id
	UUID    string `json:"uuid,omitempty"`

	Status           OrderStatus `json:"status" db:"status"`
	ExecutedQuantity float64     `json:"executedQuantity" db:"executed_quantity"`
	IsWorking        bool        `json:"isWorking" db:"is_working"`
	CreationTime     Time        `json:"creationTime" db:"created_at"`
	UpdateTime       Time        `json:"updateTime" db:"updated_at"`

	IsMargin   bool `json:"isMargin" db:"is_margin"`
	IsIsolated bool `json:"isIsolated" db:"is_isolated"`
}

func (Order) Backup added in v1.14.0

func (o Order) Backup() SubmitOrder

Backup backs up the current order quantity to a SubmitOrder object so that we can post the order later when we want to restore the orders.

func (Order) PlainText added in v1.4.0

func (o Order) PlainText() string

PlainText is used for telegram-styled messages

func (Order) SlackAttachment added in v1.17.0

func (o Order) SlackAttachment() slack.Attachment

func (Order) String

func (o Order) String() string

type OrderBook

type OrderBook interface {
	Spread() (fixedpoint.Value, bool)
	BestAsk() (PriceVolume, bool)
	BestBid() (PriceVolume, bool)
	Reset()
	Load(book SliceOrderBook)
	Update(book SliceOrderBook)
	Copy() OrderBook
	SideBook(sideType SideType) PriceVolumeSlice
	CopyDepth(depth int) OrderBook
	IsValid() (bool, error)
}

type OrderMap

type OrderMap map[uint64]Order

OrderMap is used for storing orders by their order id

func (OrderMap) Add

func (m OrderMap) Add(o Order)

func (OrderMap) Backup added in v1.14.0

func (m OrderMap) Backup() (orderForms []SubmitOrder)

func (OrderMap) Canceled

func (m OrderMap) Canceled() OrderSlice

func (OrderMap) Exists

func (m OrderMap) Exists(orderID uint64) bool

func (OrderMap) Filled

func (m OrderMap) Filled() OrderSlice

func (OrderMap) FindByStatus

func (m OrderMap) FindByStatus(status OrderStatus) (orders OrderSlice)

func (OrderMap) IDs

func (m OrderMap) IDs() (ids []uint64)

func (OrderMap) Orders

func (m OrderMap) Orders() (orders OrderSlice)

func (OrderMap) Remove added in v1.1.0

func (m OrderMap) Remove(orderID uint64)

func (OrderMap) Update

func (m OrderMap) Update(o Order)

Update only updates the order when the order exists in the map

type OrderSlice

type OrderSlice []Order

func (OrderSlice) IDs

func (s OrderSlice) IDs() (ids []uint64)

type OrderStatus

type OrderStatus string
const (
	// OrderStatusNew means the order is active on the orderbook without any filling.
	OrderStatusNew OrderStatus = "NEW"

	// OrderStatusFilled means the order is fully-filled, it's an end state.
	OrderStatusFilled OrderStatus = "FILLED"

	// OrderStatusPartiallyFilled means the order is partially-filled, it's an end state, the order might be canceled in the end.
	OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED"

	// OrderStatusCanceled means the order is canceled without partially filled or filled.
	OrderStatusCanceled OrderStatus = "CANCELED"

	// OrderStatusRejected means the order is not placed successfully, it's rejected by the api
	OrderStatusRejected OrderStatus = "REJECTED"
)

type OrderType

type OrderType string

OrderType define order type

const (
	OrderTypeLimit      OrderType = "LIMIT"
	OrderTypeLimitMaker OrderType = "LIMIT_MAKER"
	OrderTypeMarket     OrderType = "MARKET"
	OrderTypeStopLimit  OrderType = "STOP_LIMIT"
	OrderTypeStopMarket OrderType = "STOP_MARKET"
	OrderTypeIOCLimit   OrderType = "IOC_LIMIT"
)

type PlainText added in v1.4.0

type PlainText interface {
	PlainText() string
}

type Position added in v1.21.0

type Position struct {
	Symbol        string `json:"symbol"`
	BaseCurrency  string `json:"baseCurrency"`
	QuoteCurrency string `json:"quoteCurrency"`

	Market Market `json:"market"`

	Base        fixedpoint.Value `json:"base"`
	Quote       fixedpoint.Value `json:"quote"`
	AverageCost fixedpoint.Value `json:"averageCost"`

	// ApproximateAverageCost adds the computed fee in quote in the average cost
	// This is used for calculating net profit
	ApproximateAverageCost fixedpoint.Value `json:"approximateAverageCost"`

	FeeRate          *ExchangeFee                 `json:"feeRate,omitempty"`
	ExchangeFeeRates map[ExchangeName]ExchangeFee `json:"exchangeFeeRates"`

	sync.Mutex
}

func NewPosition added in v1.21.0

func NewPosition(symbol, base, quote string) *Position

func NewPositionFromMarket added in v1.21.0

func NewPositionFromMarket(market Market) *Position

func (*Position) AddTrade added in v1.21.0

func (p *Position) AddTrade(t Trade) (profit fixedpoint.Value, netProfit fixedpoint.Value, madeProfit bool)

func (*Position) AddTrades added in v1.21.0

func (p *Position) AddTrades(trades []Trade) (fixedpoint.Value, fixedpoint.Value, bool)

func (*Position) BindStream added in v1.21.0

func (p *Position) BindStream(stream Stream)

func (*Position) PlainText added in v1.21.0

func (p *Position) PlainText() string

func (*Position) Reset added in v1.21.0

func (p *Position) Reset()

func (*Position) SetExchangeFeeRate added in v1.21.0

func (p *Position) SetExchangeFeeRate(ex ExchangeName, exchangeFee ExchangeFee)

func (*Position) SetFeeRate added in v1.21.0

func (p *Position) SetFeeRate(exchangeFee ExchangeFee)

func (*Position) SlackAttachment added in v1.21.0

func (p *Position) SlackAttachment() slack.Attachment

func (*Position) String added in v1.21.0

func (p *Position) String() string

type PositionMap added in v1.21.0

type PositionMap map[string]Position

type PositionRisk added in v1.21.0

type PositionRisk struct {
	Leverage         fixedpoint.Value `json:"leverage"`
	LiquidationPrice fixedpoint.Value `json:"liquidationPrice"`
}

type PremiumIndex added in v1.21.0

type PremiumIndex struct {
	Symbol          string           `json:"symbol"`
	MarkPrice       fixedpoint.Value `json:"markPrice"`
	LastFundingRate fixedpoint.Value `json:"lastFundingRate"`
	NextFundingTime time.Time        `json:"nextFundingTime"`
	Time            time.Time        `json:"time"`
}

type PriceVolume

type PriceVolume struct {
	Price, Volume fixedpoint.Value
}

func (PriceVolume) String

func (p PriceVolume) String() string

type PriceVolumeSlice

type PriceVolumeSlice []PriceVolume

func ParsePriceVolumeSliceJSON added in v1.21.0

func ParsePriceVolumeSliceJSON(b []byte) (slice PriceVolumeSlice, err error)

ParsePriceVolumeSliceJSON tries to parse a 2 dimensional string array into a PriceVolumeSlice

[["9000", "10"], ["9900", "10"], ... ]

func (PriceVolumeSlice) Copy

func (slice PriceVolumeSlice) Copy() PriceVolumeSlice

func (PriceVolumeSlice) CopyDepth added in v1.17.0

func (slice PriceVolumeSlice) CopyDepth(depth int) PriceVolumeSlice

func (PriceVolumeSlice) Find

func (slice PriceVolumeSlice) Find(price fixedpoint.Value, descending bool) (pv PriceVolume, idx int)

Find finds the pair by the given price, this function is a read-only operation, so we use the value receiver to avoid copy value from the pointer If the price is not found, it will return the index where the price can be inserted at. true for descending (bid orders), false for ascending (ask orders)

func (PriceVolumeSlice) First

func (slice PriceVolumeSlice) First() (PriceVolume, bool)

func (PriceVolumeSlice) IndexByVolumeDepth

func (slice PriceVolumeSlice) IndexByVolumeDepth(requiredVolume fixedpoint.Value) int

func (PriceVolumeSlice) InsertAt

func (slice PriceVolumeSlice) InsertAt(idx int, pv PriceVolume) PriceVolumeSlice

func (PriceVolumeSlice) Len

func (slice PriceVolumeSlice) Len() int

func (PriceVolumeSlice) Less

func (slice PriceVolumeSlice) Less(i, j int) bool

func (PriceVolumeSlice) Remove

func (slice PriceVolumeSlice) Remove(price fixedpoint.Value, descending bool) PriceVolumeSlice

func (PriceVolumeSlice) Second added in v1.17.0

func (slice PriceVolumeSlice) Second() (PriceVolume, bool)

func (PriceVolumeSlice) Swap

func (slice PriceVolumeSlice) Swap(i, j int)

func (PriceVolumeSlice) Trim

func (slice PriceVolumeSlice) Trim() (pvs PriceVolumeSlice)

Trim removes the pairs that volume = 0

func (*PriceVolumeSlice) UnmarshalJSON added in v1.21.0

func (slice *PriceVolumeSlice) UnmarshalJSON(b []byte) error

func (PriceVolumeSlice) Upsert

func (slice PriceVolumeSlice) Upsert(pv PriceVolume, descending bool) PriceVolumeSlice

type RBNode added in v1.17.0

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

RBNode A red node always has black children. A black node may have red or black children

type RBTOrderBook added in v1.17.0

type RBTOrderBook struct {
	Symbol string
	Bids   *RBTree
	Asks   *RBTree
	// contains filtered or unexported fields
}

func NewRBOrderBook added in v1.17.0

func NewRBOrderBook(symbol string) *RBTOrderBook

func (*RBTOrderBook) BestAsk added in v1.17.0

func (b *RBTOrderBook) BestAsk() (PriceVolume, bool)

func (*RBTOrderBook) BestBid added in v1.17.0

func (b *RBTOrderBook) BestBid() (PriceVolume, bool)

func (*RBTOrderBook) Copy added in v1.17.0

func (b *RBTOrderBook) Copy() OrderBook

func (*RBTOrderBook) CopyDepth added in v1.17.0

func (b *RBTOrderBook) CopyDepth(limit int) OrderBook

func (*RBTOrderBook) EmitLoad added in v1.17.0

func (b *RBTOrderBook) EmitLoad(book *RBTOrderBook)

func (*RBTOrderBook) EmitUpdate added in v1.17.0

func (b *RBTOrderBook) EmitUpdate(book *RBTOrderBook)

func (*RBTOrderBook) IsValid added in v1.17.0

func (b *RBTOrderBook) IsValid() (bool, error)

func (*RBTOrderBook) Load added in v1.17.0

func (b *RBTOrderBook) Load(book SliceOrderBook)

func (*RBTOrderBook) OnLoad added in v1.17.0

func (b *RBTOrderBook) OnLoad(cb func(book *RBTOrderBook))

func (*RBTOrderBook) OnUpdate added in v1.17.0

func (b *RBTOrderBook) OnUpdate(cb func(book *RBTOrderBook))

func (*RBTOrderBook) Print added in v1.17.0

func (b *RBTOrderBook) Print()

func (*RBTOrderBook) Reset added in v1.17.0

func (b *RBTOrderBook) Reset()

func (*RBTOrderBook) SideBook added in v1.17.0

func (b *RBTOrderBook) SideBook(sideType SideType) PriceVolumeSlice

func (*RBTOrderBook) Spread added in v1.17.0

func (b *RBTOrderBook) Spread() (fixedpoint.Value, bool)

func (*RBTOrderBook) Update added in v1.17.0

func (b *RBTOrderBook) Update(book SliceOrderBook)

type RBTree added in v1.17.0

type RBTree struct {
	Root *RBNode
	// contains filtered or unexported fields
}

func NewRBTree added in v1.17.0

func NewRBTree() *RBTree

func (*RBTree) Copy added in v1.17.0

func (tree *RBTree) Copy() *RBTree

func (*RBTree) CopyInorder added in v1.17.0

func (tree *RBTree) CopyInorder(limit int) *RBTree

func (*RBTree) CopyInorderReverse added in v1.17.0

func (tree *RBTree) CopyInorderReverse(limit int) *RBTree

func (*RBTree) Delete added in v1.17.0

func (tree *RBTree) Delete(key fixedpoint.Value) bool

func (*RBTree) DeleteFixup added in v1.17.0

func (tree *RBTree) DeleteFixup(current *RBNode)

func (*RBTree) Inorder added in v1.17.0

func (tree *RBTree) Inorder(cb func(n *RBNode) bool)

Inorder traverses the tree in ascending order

func (*RBTree) InorderOf added in v1.17.0

func (tree *RBTree) InorderOf(current *RBNode, cb func(n *RBNode) bool)

func (*RBTree) InorderReverse added in v1.17.0

func (tree *RBTree) InorderReverse(cb func(n *RBNode) bool)

InorderReverse traverses the tree in descending order

func (*RBTree) InorderReverseOf added in v1.17.0

func (tree *RBTree) InorderReverseOf(current *RBNode, cb func(n *RBNode) bool)

func (*RBTree) Insert added in v1.17.0

func (tree *RBTree) Insert(key, val fixedpoint.Value)

func (*RBTree) InsertFixup added in v1.17.0

func (tree *RBTree) InsertFixup(current *RBNode)

func (*RBTree) Leftmost added in v1.17.0

func (tree *RBTree) Leftmost() *RBNode

func (*RBTree) LeftmostOf added in v1.17.0

func (tree *RBTree) LeftmostOf(current *RBNode) *RBNode

func (*RBTree) Postorder added in v1.17.0

func (tree *RBTree) Postorder(cb func(n *RBNode) bool)

func (*RBTree) PostorderOf added in v1.17.0

func (tree *RBTree) PostorderOf(current *RBNode, cb func(n *RBNode) bool)

func (*RBTree) Preorder added in v1.17.0

func (tree *RBTree) Preorder(cb func(n *RBNode))

func (*RBTree) PreorderOf added in v1.17.0

func (tree *RBTree) PreorderOf(current *RBNode, cb func(n *RBNode))

func (*RBTree) Print added in v1.17.0

func (tree *RBTree) Print()

func (*RBTree) Rightmost added in v1.17.0

func (tree *RBTree) Rightmost() *RBNode

func (*RBTree) RightmostOf added in v1.17.0

func (tree *RBTree) RightmostOf(current *RBNode) *RBNode

func (*RBTree) RotateLeft added in v1.17.0

func (tree *RBTree) RotateLeft(x *RBNode)

RotateLeft x is the axes of rotation, y is the node that will be replace x's position. we need to: 1. move y's left child to the x's right child 2. change y's parent to x's parent 3. change x's parent to y

func (*RBTree) RotateRight added in v1.17.0

func (tree *RBTree) RotateRight(y *RBNode)

func (*RBTree) Search added in v1.17.0

func (tree *RBTree) Search(key fixedpoint.Value) *RBNode

func (*RBTree) Size added in v1.17.0

func (tree *RBTree) Size() int

func (*RBTree) Successor added in v1.17.0

func (tree *RBTree) Successor(current *RBNode) *RBNode

func (*RBTree) Upsert added in v1.17.0

func (tree *RBTree) Upsert(key, val fixedpoint.Value)

type Reward added in v1.13.0

type Reward struct {
	GID      int64            `json:"gid" db:"gid"`
	UUID     string           `json:"uuid" db:"uuid"`
	Exchange ExchangeName     `json:"exchange" db:"exchange"`
	Type     RewardType       `json:"reward_type" db:"reward_type"`
	Currency string           `json:"currency" db:"currency"`
	Quantity fixedpoint.Value `json:"quantity" db:"quantity"`
	State    string           `json:"state" db:"state"`
	Note     string           `json:"note" db:"note"`
	Spent    bool             `json:"spent" db:"spent"`

	// Unix timestamp in seconds
	CreatedAt Time `json:"created_at" db:"created_at"`
}

type RewardSlice added in v1.13.0

type RewardSlice []Reward

func (RewardSlice) Len added in v1.13.0

func (s RewardSlice) Len() int

func (RewardSlice) Swap added in v1.13.0

func (s RewardSlice) Swap(i, j int)

type RewardSliceByCreationTime added in v1.13.0

type RewardSliceByCreationTime RewardSlice

func (RewardSliceByCreationTime) Len added in v1.13.0

func (RewardSliceByCreationTime) Less added in v1.13.0

func (s RewardSliceByCreationTime) Less(i, j int) bool

Less reports whether x[i] should be ordered before x[j]

func (RewardSliceByCreationTime) Swap added in v1.13.0

func (s RewardSliceByCreationTime) Swap(i, j int)

type RewardType added in v1.13.0

type RewardType string

type SideType

type SideType string

SideType define side type of order

func StrToSideType added in v1.17.0

func StrToSideType(s string) (side SideType, err error)

func (SideType) Color

func (side SideType) Color() string

func (SideType) Reverse

func (side SideType) Reverse() SideType

func (SideType) String added in v1.17.0

func (side SideType) String() string

func (*SideType) UnmarshalJSON added in v1.14.0

func (side *SideType) UnmarshalJSON(data []byte) error

type SliceOrderBook added in v1.17.0

type SliceOrderBook struct {
	Symbol string
	Bids   PriceVolumeSlice
	Asks   PriceVolumeSlice
	// contains filtered or unexported fields
}

SliceOrderBook is a general order book structure which could be used for RESTful responses and websocket stream parsing

func NewSliceOrderBook added in v1.17.0

func NewSliceOrderBook(symbol string) *SliceOrderBook

func (*SliceOrderBook) BestAsk added in v1.17.0

func (b *SliceOrderBook) BestAsk() (PriceVolume, bool)

func (*SliceOrderBook) BestBid added in v1.17.0

func (b *SliceOrderBook) BestBid() (PriceVolume, bool)

func (*SliceOrderBook) Copy added in v1.17.0

func (b *SliceOrderBook) Copy() OrderBook

func (*SliceOrderBook) CopyDepth added in v1.17.0

func (b *SliceOrderBook) CopyDepth(limit int) OrderBook

func (*SliceOrderBook) EmitLoad added in v1.17.0

func (b *SliceOrderBook) EmitLoad(book *SliceOrderBook)

func (*SliceOrderBook) EmitUpdate added in v1.17.0

func (b *SliceOrderBook) EmitUpdate(book *SliceOrderBook)

func (*SliceOrderBook) IsValid added in v1.17.0

func (b *SliceOrderBook) IsValid() (bool, error)

func (*SliceOrderBook) Load added in v1.17.0

func (b *SliceOrderBook) Load(book SliceOrderBook)

func (*SliceOrderBook) OnLoad added in v1.17.0

func (b *SliceOrderBook) OnLoad(cb func(book *SliceOrderBook))

func (*SliceOrderBook) OnUpdate added in v1.17.0

func (b *SliceOrderBook) OnUpdate(cb func(book *SliceOrderBook))

func (*SliceOrderBook) PriceVolumesBySide added in v1.17.0

func (b *SliceOrderBook) PriceVolumesBySide(side SideType) PriceVolumeSlice

func (*SliceOrderBook) Print added in v1.17.0

func (b *SliceOrderBook) Print()

func (*SliceOrderBook) Reset added in v1.17.0

func (b *SliceOrderBook) Reset()

func (*SliceOrderBook) SideBook added in v1.17.0

func (b *SliceOrderBook) SideBook(sideType SideType) PriceVolumeSlice

func (*SliceOrderBook) Spread added in v1.17.0

func (b *SliceOrderBook) Spread() (fixedpoint.Value, bool)

func (*SliceOrderBook) String added in v1.17.0

func (b *SliceOrderBook) String() string

func (*SliceOrderBook) Update added in v1.17.0

func (b *SliceOrderBook) Update(book SliceOrderBook)

type StandardStream

type StandardStream struct {
	PublicOnly bool

	// ReconnectC is a signal channel for reconnecting
	ReconnectC chan struct{}

	// CloseC is a signal channel for closing stream
	CloseC chan struct{}

	Subscriptions []Subscription

	// Futures
	FuturesPositionUpdateCallbacks []func(futuresPositions FuturesPositionMap)

	FuturesPositionSnapshotCallbacks []func(futuresPositions FuturesPositionMap)
	// contains filtered or unexported fields
}

func (*StandardStream) Dial added in v1.17.0

func (stream *StandardStream) Dial(url string) (*websocket.Conn, error)

func (*StandardStream) EmitBalanceSnapshot

func (stream *StandardStream) EmitBalanceSnapshot(balances BalanceMap)

func (*StandardStream) EmitBalanceUpdate

func (stream *StandardStream) EmitBalanceUpdate(balances BalanceMap)

func (*StandardStream) EmitBookSnapshot

func (stream *StandardStream) EmitBookSnapshot(book SliceOrderBook)

func (*StandardStream) EmitBookTickerUpdate added in v1.21.0

func (stream *StandardStream) EmitBookTickerUpdate(bookTicker BookTicker)

func (*StandardStream) EmitBookUpdate

func (stream *StandardStream) EmitBookUpdate(book SliceOrderBook)

func (*StandardStream) EmitConnect

func (stream *StandardStream) EmitConnect()

func (*StandardStream) EmitDisconnect added in v1.14.0

func (stream *StandardStream) EmitDisconnect()

func (*StandardStream) EmitFuturesPositionSnapshot added in v1.22.0

func (stream *StandardStream) EmitFuturesPositionSnapshot(futuresPositions FuturesPositionMap)

func (*StandardStream) EmitFuturesPositionUpdate added in v1.22.0

func (stream *StandardStream) EmitFuturesPositionUpdate(futuresPositions FuturesPositionMap)

func (*StandardStream) EmitKLine

func (stream *StandardStream) EmitKLine(kline KLine)

func (*StandardStream) EmitKLineClosed

func (stream *StandardStream) EmitKLineClosed(kline KLine)

func (*StandardStream) EmitOrderUpdate

func (stream *StandardStream) EmitOrderUpdate(order Order)

func (*StandardStream) EmitStart added in v1.14.0

func (stream *StandardStream) EmitStart()

func (*StandardStream) EmitTradeUpdate

func (stream *StandardStream) EmitTradeUpdate(trade Trade)

func (*StandardStream) OnBalanceSnapshot

func (stream *StandardStream) OnBalanceSnapshot(cb func(balances BalanceMap))

func (*StandardStream) OnBalanceUpdate

func (stream *StandardStream) OnBalanceUpdate(cb func(balances BalanceMap))

func (*StandardStream) OnBookSnapshot

func (stream *StandardStream) OnBookSnapshot(cb func(book SliceOrderBook))

func (*StandardStream) OnBookTickerUpdate added in v1.21.0

func (stream *StandardStream) OnBookTickerUpdate(cb func(bookTicker BookTicker))

func (*StandardStream) OnBookUpdate

func (stream *StandardStream) OnBookUpdate(cb func(book SliceOrderBook))

func (*StandardStream) OnConnect

func (stream *StandardStream) OnConnect(cb func())

func (*StandardStream) OnDisconnect added in v1.14.0

func (stream *StandardStream) OnDisconnect(cb func())

func (*StandardStream) OnFuturesPositionSnapshot added in v1.22.0

func (stream *StandardStream) OnFuturesPositionSnapshot(cb func(futuresPositions FuturesPositionMap))

func (*StandardStream) OnFuturesPositionUpdate added in v1.22.0

func (stream *StandardStream) OnFuturesPositionUpdate(cb func(futuresPositions FuturesPositionMap))

func (*StandardStream) OnKLine

func (stream *StandardStream) OnKLine(cb func(kline KLine))

func (*StandardStream) OnKLineClosed

func (stream *StandardStream) OnKLineClosed(cb func(kline KLine))

func (*StandardStream) OnOrderUpdate

func (stream *StandardStream) OnOrderUpdate(cb func(order Order))

func (*StandardStream) OnStart added in v1.14.0

func (stream *StandardStream) OnStart(cb func())

func (*StandardStream) OnTradeUpdate

func (stream *StandardStream) OnTradeUpdate(cb func(trade Trade))

func (*StandardStream) Reconnect added in v1.17.0

func (stream *StandardStream) Reconnect()

func (*StandardStream) SetPublicOnly added in v1.21.0

func (stream *StandardStream) SetPublicOnly()

func (*StandardStream) Subscribe

func (stream *StandardStream) Subscribe(channel Channel, symbol string, options SubscribeOptions)

type StandardStreamEventHub

type StandardStreamEventHub interface {
	OnStart(cb func())

	OnConnect(cb func())

	OnDisconnect(cb func())

	OnTradeUpdate(cb func(trade Trade))

	OnOrderUpdate(cb func(order Order))

	OnBalanceSnapshot(cb func(balances BalanceMap))

	OnBalanceUpdate(cb func(balances BalanceMap))

	OnKLineClosed(cb func(kline KLine))

	OnKLine(cb func(kline KLine))

	OnBookUpdate(cb func(book SliceOrderBook))

	OnBookTickerUpdate(cb func(bookTicker BookTicker))

	OnBookSnapshot(cb func(book SliceOrderBook))

	OnFuturesPositionUpdate(cb func(futuresPositions FuturesPositionMap))

	OnFuturesPositionSnapshot(cb func(futuresPositions FuturesPositionMap))
}

type Stream

type Stream interface {
	StandardStreamEventHub

	Subscribe(channel Channel, symbol string, options SubscribeOptions)
	SetPublicOnly()
	Connect(ctx context.Context) error
	Close() error
}

type StreamOrderBook

type StreamOrderBook struct {
	*MutexOrderBook

	C sigchan.Chan
}

StreamOrderBook receives streaming data from websocket connection and update the order book with mutex lock, so you can safely access it.

func NewStreamBook

func NewStreamBook(symbol string) *StreamOrderBook

func (*StreamOrderBook) BindStream

func (sb *StreamOrderBook) BindStream(stream Stream)

type Stringer added in v1.16.0

type Stringer interface {
	String() string
}

type SubmitOrder

type SubmitOrder struct {
	ClientOrderID string `json:"clientOrderID" db:"client_order_id"`

	Symbol string    `json:"symbol" db:"symbol"`
	Side   SideType  `json:"side" db:"side"`
	Type   OrderType `json:"orderType" db:"order_type"`

	Quantity  float64 `json:"quantity" db:"quantity"`
	Price     float64 `json:"price" db:"price"`
	StopPrice float64 `json:"stopPrice,omitempty" db:"stop_price"`

	Market Market `json:"-" db:"-"`

	// TODO: we can probably remove these field
	StopPriceString string `json:"-"`
	PriceString     string `json:"-"`
	QuantityString  string `json:"-"`

	TimeInForce string `json:"timeInForce,omitempty" db:"time_in_force"` // GTC, IOC, FOK

	GroupID uint32 `json:"groupID,omitempty"`

	MarginSideEffect MarginOrderSideEffectType `json:"marginSideEffect,omitempty"` // AUTO_REPAY = repay, MARGIN_BUY = borrow, defaults to  NO_SIDE_EFFECT

	// futures order fields
	IsFutures     bool `json:"is_futures" db:"is_futures"`
	ReduceOnly    bool `json:"reduceOnly" db:"reduce_only"`
	ClosePosition bool `json:"closePosition" db:"close_position"`
}

func (*SubmitOrder) PlainText added in v1.4.0

func (o *SubmitOrder) PlainText() string

func (*SubmitOrder) SlackAttachment

func (o *SubmitOrder) SlackAttachment() slack.Attachment

func (*SubmitOrder) String

func (o *SubmitOrder) String() string

type SubscribeOptions

type SubscribeOptions struct {
	Interval string `json:"interval,omitempty"`
	Depth    string `json:"depth,omitempty"`
}

SubscribeOptions provides the standard stream options

func (SubscribeOptions) String

func (o SubscribeOptions) String() string

type Subscription

type Subscription struct {
	Symbol  string           `json:"symbol"`
	Channel Channel          `json:"channel"`
	Options SubscribeOptions `json:"options"`
}

type SyncOrderMap

type SyncOrderMap struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewSyncOrderMap

func NewSyncOrderMap() *SyncOrderMap

func (*SyncOrderMap) Add

func (m *SyncOrderMap) Add(o Order)

func (*SyncOrderMap) AnyFilled

func (m *SyncOrderMap) AnyFilled() (order Order, ok bool)

AnyFilled find any order is filled and stop iterating the order map

func (*SyncOrderMap) Backup added in v1.14.0

func (m *SyncOrderMap) Backup() (orders []SubmitOrder)

func (*SyncOrderMap) Canceled

func (m *SyncOrderMap) Canceled() OrderSlice

func (*SyncOrderMap) Exists

func (m *SyncOrderMap) Exists(orderID uint64) (exists bool)

func (*SyncOrderMap) Filled

func (m *SyncOrderMap) Filled() OrderSlice

func (*SyncOrderMap) FindByStatus

func (m *SyncOrderMap) FindByStatus(status OrderStatus) OrderSlice

func (*SyncOrderMap) IDs

func (m *SyncOrderMap) IDs() (ids []uint64)

func (*SyncOrderMap) Iterate

func (m *SyncOrderMap) Iterate(it func(id uint64, order Order) bool)

func (*SyncOrderMap) Len

func (m *SyncOrderMap) Len() int

func (*SyncOrderMap) Orders

func (m *SyncOrderMap) Orders() (slice OrderSlice)

func (*SyncOrderMap) Remove added in v1.1.0

func (m *SyncOrderMap) Remove(orderID uint64) (exists bool)

func (*SyncOrderMap) Update

func (m *SyncOrderMap) Update(o Order)

type Ticker added in v1.11.0

type Ticker struct {
	Time   time.Time
	Volume float64 // `volume` from Max & binance
	Last   float64 // `last` from Max, `lastPrice` from binance
	Open   float64 // `open` from Max, `openPrice` from binance
	High   float64 // `high` from Max, `highPrice` from binance
	Low    float64 // `low` from Max, `lowPrice` from binance
	Buy    float64 // `buy` from Max, `bidPrice` from binance
	Sell   float64 // `sell` from Max, `askPrice` from binance
}

type Time added in v1.17.0

type Time time.Time

func NewTimeFromUnix added in v1.21.0

func NewTimeFromUnix(sec int64, nsec int64) Time

func (Time) After added in v1.21.0

func (t Time) After(time2 time.Time) bool

func (Time) Before added in v1.21.0

func (t Time) Before(time2 time.Time) bool

func (Time) MarshalJSON added in v1.17.0

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

func (*Time) Scan added in v1.17.0

func (t *Time) Scan(src interface{}) error

func (Time) String added in v1.17.0

func (t Time) String() string

func (Time) Time added in v1.17.0

func (t Time) Time() time.Time

func (Time) Unix added in v1.21.0

func (t Time) Unix() int64

func (*Time) UnmarshalJSON added in v1.17.0

func (t *Time) UnmarshalJSON(data []byte) error

func (Time) Value added in v1.17.0

func (t Time) Value() (driver.Value, error)

Value implements the driver.Valuer interface see http://jmoiron.net/blog/built-in-interfaces/

type Trade

type Trade struct {
	// GID is the global ID
	GID int64 `json:"gid" db:"gid"`

	// ID is the source trade ID
	ID            uint64       `json:"id" db:"id"`
	OrderID       uint64       `json:"orderID" db:"order_id"`
	Exchange      ExchangeName `json:"exchange" db:"exchange"`
	Price         float64      `json:"price" db:"price"`
	Quantity      float64      `json:"quantity" db:"quantity"`
	QuoteQuantity float64      `json:"quoteQuantity" db:"quote_quantity"`
	Symbol        string       `json:"symbol" db:"symbol"`

	Side        SideType `json:"side" db:"side"`
	IsBuyer     bool     `json:"isBuyer" db:"is_buyer"`
	IsMaker     bool     `json:"isMaker" db:"is_maker"`
	Time        Time     `json:"tradedAt" db:"traded_at"`
	Fee         float64  `json:"fee" db:"fee"`
	FeeCurrency string   `json:"feeCurrency" db:"fee_currency"`

	IsMargin   bool `json:"isMargin" db:"is_margin"`
	IsFutures  bool `json:"isFutures" db:"is_futures"`
	IsIsolated bool `json:"isIsolated" db:"is_isolated"`

	StrategyID sql.NullString  `json:"strategyID" db:"strategy"`
	PnL        sql.NullFloat64 `json:"pnl" db:"pnl"`
}

func (Trade) Key added in v1.11.1

func (trade Trade) Key() TradeKey

func (Trade) Liquidity added in v1.16.0

func (trade Trade) Liquidity() (o string)

func (Trade) PlainText added in v1.4.0

func (trade Trade) PlainText() string

PlainText is used for telegram-styled messages

func (Trade) PositionChange added in v1.21.0

func (trade Trade) PositionChange() fixedpoint.Value

func (Trade) SlackAttachment

func (trade Trade) SlackAttachment() slack.Attachment

func (Trade) String added in v1.17.0

func (trade Trade) String() string

String is for console output

type TradeKey added in v1.11.1

type TradeKey struct {
	ID   uint64
	Side SideType
}

type TradeQueryOptions

type TradeQueryOptions struct {
	StartTime   *time.Time
	EndTime     *time.Time
	Limit       int64
	LastTradeID uint64
}

type TradeSlice added in v1.11.0

type TradeSlice struct {
	Trades []Trade
	// contains filtered or unexported fields
}

func (*TradeSlice) Append added in v1.11.0

func (s *TradeSlice) Append(t Trade)

func (*TradeSlice) Copy added in v1.11.0

func (s *TradeSlice) Copy() []Trade

func (*TradeSlice) Reverse added in v1.13.0

func (s *TradeSlice) Reverse()

type Withdraw

type Withdraw struct {
	GID        int64        `json:"gid" db:"gid"`
	Exchange   ExchangeName `json:"exchange" db:"exchange"`
	Asset      string       `json:"asset" db:"asset"`
	Amount     float64      `json:"amount" db:"amount"`
	Address    string       `json:"address" db:"address"`
	AddressTag string       `json:"addressTag"`
	Status     string       `json:"status"`

	TransactionID          string  `json:"transactionID" db:"txn_id"`
	TransactionFee         float64 `json:"transactionFee" db:"txn_fee"`
	TransactionFeeCurrency string  `json:"transactionFeeCurrency" db:"txn_fee_currency"`
	WithdrawOrderID        string  `json:"withdrawOrderId"`
	ApplyTime              Time    `json:"applyTime" db:"time"`
	Network                string  `json:"network" db:"network"`
}

func (Withdraw) EffectiveTime

func (w Withdraw) EffectiveTime() time.Time

func (Withdraw) String added in v1.14.0

func (w Withdraw) String() string

type WithdrawalOptions added in v1.17.0

type WithdrawalOptions struct {
	Network    string
	AddressTag string
}

Jump to

Keyboard shortcuts

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