types

package
v1.60.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2024 License: AGPL-3.0 Imports: 33 Imported by: 161

Documentation

Index

Constants

View Source
const (
	AccountTypeFutures        = AccountType("futures")
	AccountTypeMargin         = AccountType("margin")
	AccountTypeIsolatedMargin = AccountType("isolated_margin")
	AccountTypeSpot           = AccountType("spot")
)
View Source
const (
	BookChannel        = Channel("book")
	KLineChannel       = Channel("kline")
	BookTickerChannel  = Channel("bookTicker")
	MarketTradeChannel = Channel("trade")
	AggTradeChannel    = Channel("aggTrade")
	ForceOrderChannel  = Channel("forceOrder")

	// channels for futures
	MarkPriceChannel = Channel("markPrice")

	LiquidationOrderChannel = Channel("liquidationOrder")

	// ContractInfoChannel is the contract info provided by the exchange
	ContractInfoChannel = Channel("contractInfo")
)
View Source
const (
	USDT = "USDT"
	USDC = "USDC"
	BUSD = "BUSD"
)
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 (
	PositionShort  = PositionType("Short")
	PositionLong   = PositionType("Long")
	PositionClosed = PositionType("Closed")
)
View Source
const (
	Red   = Color(false)
	Black = Color(true)
)
View Source
const (
	RewardAirdrop          = RewardType("airdrop")
	RewardCommission       = RewardType("commission")
	RewardReferralKickback = RewardType("referral_kickback")
	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 NoClientOrderID = "0"

Variables

View Source
var BNB = wrapper{accounting.Accounting{Symbol: "BNB ", Precision: 4}}
View Source
var BTC = wrapper{accounting.Accounting{Symbol: "BTC ", Precision: 8}}
View Source
var ErrInvalidBalanceType = errors.New("invalid balance type")
View Source
var ErrInvalidPriceType = errors.New("invalid price type")
View Source
var ErrInvalidSideType = errors.New("invalid side type")
View Source
var ErrNotSimpleDuration = errors.New("the given input is not simple duration format, valid format: [1-9][0-9]*[hdw]")
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 Interval1mo = Interval("1mo")
View Source
var Interval1s = Interval("1s")
View Source
var Interval1w = Interval("1w")
View Source
var Interval2h = Interval("2h")
View Source
var Interval2w = Interval("2w")
View Source
var Interval30m = Interval("30m")
View Source
var Interval3d = Interval("3d")
View Source
var Interval3m = Interval("3m")
View Source
var Interval4h = Interval("4h")
View Source
var Interval5m = Interval("5m")
View Source
var Interval6h = Interval("6h")
View Source
var QuantityDelta = fixedpoint.MustNewFromString("0.00000000001")
View Source
var SupportedIntervals = IntervalMap{
	Interval1s:  1,
	Interval1m:  1 * 60,
	Interval3m:  3 * 60,
	Interval5m:  5 * 60,
	Interval15m: 15 * 60,
	Interval30m: 30 * 60,
	Interval1h:  60 * 60,
	Interval2h:  60 * 60 * 2,
	Interval4h:  60 * 60 * 4,
	Interval6h:  60 * 60 * 6,
	Interval12h: 60 * 60 * 12,
	Interval1d:  60 * 60 * 24,
	Interval3d:  60 * 60 * 24 * 3,
	Interval1w:  60 * 60 * 24 * 7,
	Interval2w:  60 * 60 * 24 * 14,
	Interval1mo: 60 * 60 * 24 * 30,
}
View Source
var USD = wrapper{accounting.Accounting{Symbol: "$ ", Precision: 2}}
View Source
var USDFiatCurrencies = []string{"USDT", "USDC", "USD", "BUSD"}

USDFiatCurrencies lists the USD stable coins

Functions

func Array added in v1.36.0

func Array(a Series, limit ...int) (result []float64)

Array extracts elements from the Series to a float64 array, following the order of Index(0..limit) if limit is given, will only take the first limit numbers (a.Index[0..limit]) otherwise will operate on all elements

func AutoCorrelation added in v1.38.0

func AutoCorrelation(a Series, length int, lags ...int) float64

similar to pandas.Series.autocorr() function.

The method computes the Pearson correlation between Series and shifted itself

func BeginningOfTheDay added in v1.40.0

func BeginningOfTheDay(t time.Time) time.Time

func Correlation added in v1.36.0

func Correlation(a Series, b Series, length int, method ...CorrFunc) float64

similar to pandas.Series.corr() function.

method could either be `types.Pearson`, `types.Spearman` or `types.Kendall`

func Covariance added in v1.36.0

func Covariance(a Series, b Series, length int) float64

similar to pandas.Series.cov() function with ddof=0

Compute covariance with Series

func CrossEntropy added in v1.37.0

func CrossEntropy(a, b Series, window int) (e float64)

CrossEntropy computes the cross-entropy between the two distributions

func Dot added in v1.30.2

func Dot(a interface{}, b interface{}, limit ...int) float64

Calculate (a dot b). if limit is given, will only calculate the first limit numbers (a.Index[0..limit]) otherwise will operate on all elements

func Entropy added in v1.37.0

func Entropy(a Series, window int) (e float64)

Entropy computes the Shannon entropy of a distribution or the distance between two distributions. The natural logarithm is used. - sum(v * ln(v))

func ExchangeFooterIcon added in v1.32.0

func ExchangeFooterIcon(exName ExchangeName) string

func FormatPrice added in v1.43.0

func FormatPrice(price fixedpoint.Value, tickSize fixedpoint.Value) string

func Highest added in v1.30.2

func Highest(a Series, lookback int) float64

func IsActiveOrder added in v1.44.0

func IsActiveOrder(o Order) bool

func IsFiatCurrency added in v1.18.1

func IsFiatCurrency(currency string) bool

func IsUSDFiatCurrency added in v1.39.0

func IsUSDFiatCurrency(currency string) bool

func KLineClosePriceMapper added in v1.51.0

func KLineClosePriceMapper(k KLine) float64

func KLineHLC3Mapper added in v1.51.0

func KLineHLC3Mapper(k KLine) float64

func KLineHighPriceMapper added in v1.51.0

func KLineHighPriceMapper(k KLine) float64

func KLineLowPriceMapper added in v1.51.0

func KLineLowPriceMapper(k KLine) float64

func KLineOpenPriceMapper added in v1.51.0

func KLineOpenPriceMapper(k KLine) float64

func KLinePriceVolumeMapper added in v1.51.0

func KLinePriceVolumeMapper(k KLine) float64

func KLineTypicalPriceMapper added in v1.51.0

func KLineTypicalPriceMapper(k KLine) float64

func KLineVolumeMapper added in v1.51.0

func KLineVolumeMapper(k KLine) float64

func Kendall added in v1.36.0

func Kendall(a, b Series, length int) float64

func LinearRegression added in v1.38.0

func LinearRegression(a Series, lookback int) (alpha float64, beta float64)

func Lowest added in v1.30.2

func Lowest(a Series, lookback int) float64

func MapKLinePrice added in v1.51.0

func MapKLinePrice(kLines []KLine, f KLineValueMapper) (prices []float64)

func Mean added in v1.30.2

func Mean(a Series, limit ...int) (mean float64)

Calculate the average value of the series if limit is given, will only calculate the average of first limit numbers (a.Index[0..limit]) otherwise will operate on all elements

func MustParseUnixTimestamp added in v1.21.0

func MustParseUnixTimestamp(a string) time.Time

func NewOrderError added in v1.25.3

func NewOrderError(e error, o Order) error

func NextCross added in v1.30.2

func NextCross(a Series, b Series, lookback int) (int, float64, bool)

This will make prediction using Linear Regression to get the next cross point Return (offset from latest, crossed value, could cross) offset from latest should always be positive lookback param is to use at most `lookback` points to determine linear regression functions

You may also refer to excel's FORECAST function

func Omega added in v1.38.0

func Omega(returns Series, returnThresholds ...float64) float64

Determines the Omega ratio of a strategy See https://en.wikipedia.org/wiki/Omega_ratio for more details

@param returns (Series): Series of profit/loss percentage every specific interval @param returnThresholds(float64): threshold for returns filtering @return Omega ratio for give return series and threshold

func OrdersAll added in v1.44.0

func OrdersAll(orders []Order, f func(o Order) bool) bool

func OrdersAny added in v1.44.0

func OrdersAny(orders []Order, f func(o Order) bool) bool

func Over24Hours added in v1.40.0

func Over24Hours(since time.Time) bool

func ParseInterval added in v1.40.3

func ParseInterval(input Interval) int

func ParseTimeWithFormats added in v1.40.0

func ParseTimeWithFormats(strTime string, formats []string) (time.Time, error)

func Pearson added in v1.36.0

func Pearson(a, b Series, length int) float64

func Predict added in v1.30.2

func Predict(a Series, lookback int, offset ...int) float64

func Reverse added in v1.36.0

func Reverse(a Series, limit ...int) (result floats.Slice)

Similar to Array but in reverse order. Useful when you want to cache series' calculated result as float64 array the then reuse the result in multiple places (so that no recalculation will be triggered)

notice that the return type is a Float64Slice, which implements the Series interface

func Sharpe added in v1.38.0

func Sharpe(returns Series, periods int, annualize bool, smart bool) float64

Sharpe: Calcluates the sharpe ratio of access returns

@param returns (Series): Series of profit/loss percentage every specific interval @param periods (int): Freq. of returns (252/365 for daily, 12 for monthy, 1 for annually) @param annualize (bool): return annualize sharpe? @param smart (bool): return smart sharpe ratio

func SideToColorName

func SideToColorName(side SideType) string

func Skew added in v1.36.0

func Skew(a Series, length int) float64

similar to pandas.Series.skew() function.

Return unbiased skew over input series

func Sortino added in v1.39.2

func Sortino(returns Series, riskFreeReturns float64, periods int, annualize bool, smart bool) float64

Sortino: Calcluates the sotino ratio of access returns

ROI_excess   E[ROI] - ROI_risk_free

sortino = ---------- = -----------------------

risk      sqrt(E[ROI_drawdown^2])

@param returns (Series): Series of profit/loss percentage every specific interval @param riskFreeReturns (float): risk-free return rate of year @param periods (int): Freq. of returns (252/365 for daily, 12 for monthy, 1 for annually) @param annualize (bool): return annualize sortino? @param smart (bool): return smart sharpe ratio

func Spearman added in v1.36.0

func Spearman(a, b Series, length int) float64

func Stdev added in v1.33.0

func Stdev(a Series, params ...int) float64

func Sum added in v1.30.2

func Sum(a Series, limit ...int) (sum float64)

Calculate sum of the series if limit is given, will only sum first limit numbers (a.Index[0..limit]) otherwise will sum all elements

func TradeWith added in v1.48.0

func TradeWith(symbol string, f func(trade Trade)) func(trade Trade)

func Variance added in v1.36.0

func Variance(a Series, length int) float64

Types

type AbsResult added in v1.30.2

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

func (*AbsResult) Index added in v1.30.2

func (a *AbsResult) Index(i int) float64

func (*AbsResult) Last added in v1.30.2

func (a *AbsResult) Last(i int) float64

func (*AbsResult) Length added in v1.30.2

func (a *AbsResult) Length() int

type Acc added in v1.28.0

type Acc = accounting.Accounting

type Account

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

	AccountType        AccountType `json:"accountType,omitempty"`
	FuturesInfo        *FuturesAccountInfo
	MarginInfo         *MarginAccountInfo
	IsolatedMarginInfo *IsolatedMarginAccountInfo

	// Margin related common field
	// From binance:
	// Margin Level = Total Asset Value / (Total Borrowed + Total Accrued Interest)
	// If your margin level drops to 1.3, you will receive a Margin Call, which is a reminder that you should either increase your collateral (by depositing more funds) or reduce your loan (by repaying what you’ve borrowed).
	// If your margin level drops to 1.1, your assets will be automatically liquidated, meaning that Binance will sell your funds at market price to repay the loan.
	MarginLevel     fixedpoint.Value `json:"marginLevel,omitempty"`
	MarginTolerance fixedpoint.Value `json:"marginTolerance,omitempty"`

	BorrowEnabled   bool `json:"borrowEnabled,omitempty"`
	TransferEnabled bool `json:"transferEnabled,omitempty"`

	// isolated margin related fields
	// LiquidationPrice is only used when account is in the isolated margin mode
	MarginRatio      fixedpoint.Value `json:"marginRatio,omitempty"`
	LiquidationPrice fixedpoint.Value `json:"liquidationPrice,omitempty"`
	LiquidationRate  fixedpoint.Value `json:"liquidationRate,omitempty"`

	MakerFeeRate fixedpoint.Value `json:"makerFeeRate,omitempty"`
	TakerFeeRate fixedpoint.Value `json:"takerFeeRate,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) 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 AddSeriesResult added in v1.30.2

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

func (*AddSeriesResult) Index added in v1.30.2

func (a *AddSeriesResult) Index(i int) float64

func (*AddSeriesResult) Last added in v1.30.2

func (a *AddSeriesResult) Last(i int) float64

func (*AddSeriesResult) Length added in v1.30.2

func (a *AddSeriesResult) Length() int

type Asset added in v1.11.0

type Asset struct {
	Currency string `json:"currency" db:"currency"`

	Total fixedpoint.Value `json:"total" db:"total"`

	NetAsset fixedpoint.Value `json:"netAsset" db:"net_asset"`

	Interest fixedpoint.Value `json:"interest" db:"interest"`

	// InUSD is net asset in USD
	InUSD fixedpoint.Value `json:"inUSD" db:"net_asset_in_usd"`

	// InBTC is net asset in BTC
	InBTC fixedpoint.Value `json:"inBTC" db:"net_asset_in_btc"`

	Time       time.Time        `json:"time" db:"time"`
	Locked     fixedpoint.Value `json:"lock" db:"lock" `
	Available  fixedpoint.Value `json:"available"  db:"available"`
	Borrowed   fixedpoint.Value `json:"borrowed" db:"borrowed"`
	PriceInUSD fixedpoint.Value `json:"priceInUSD" db:"price_in_usd"`
}

type AssetMap added in v1.11.0

type AssetMap map[string]Asset

func (AssetMap) InUSD added in v1.33.0

func (m AssetMap) InUSD() (total fixedpoint.Value)

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 BacktestStream added in v1.35.0

type BacktestStream struct {
	StandardStreamEmitter
}

func (*BacktestStream) Close added in v1.35.0

func (s *BacktestStream) Close() error

func (*BacktestStream) Connect added in v1.35.0

func (s *BacktestStream) Connect(ctx context.Context) error

type Balance

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

	// margin related fields
	Borrowed fixedpoint.Value `json:"borrowed,omitempty"`
	Interest fixedpoint.Value `json:"interest,omitempty"`

	// NetAsset = (Available + Locked) - Borrowed - Interest
	NetAsset fixedpoint.Value `json:"net,omitempty"`

	MaxWithdrawAmount fixedpoint.Value `json:"maxWithdrawAmount,omitempty"`
}

func (Balance) Add added in v1.32.0

func (b Balance) Add(b2 Balance) Balance

func (Balance) Debt added in v1.38.0

func (b Balance) Debt() fixedpoint.Value

func (Balance) Net added in v1.32.0

func (b Balance) Net() fixedpoint.Value

Net returns the net asset value (total - debt)

func (Balance) String added in v1.2.0

func (b Balance) String() (o string)

func (Balance) Total added in v1.11.1

func (b Balance) Total() fixedpoint.Value

func (Balance) ValueString added in v1.33.0

func (b Balance) ValueString() (o string)

type BalanceMap

type BalanceMap map[string]Balance

func (BalanceMap) Add added in v1.32.0

func (m BalanceMap) Add(bm BalanceMap) BalanceMap

func (BalanceMap) Assets added in v1.11.0

func (m BalanceMap) Assets(prices PriceMap, priceTime time.Time) AssetMap

Assets converts balances into assets with the given prices

func (BalanceMap) Copy added in v1.18.0

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

func (BalanceMap) Currencies added in v1.32.0

func (m BalanceMap) Currencies() (currencies []string)

func (BalanceMap) Debts added in v1.33.0

func (m BalanceMap) Debts() BalanceMap

func (BalanceMap) NotZero added in v1.51.1

func (m BalanceMap) NotZero() BalanceMap

func (BalanceMap) Print

func (m BalanceMap) Print()

func (BalanceMap) SlackAttachment added in v1.33.0

func (m BalanceMap) SlackAttachment() slack.Attachment

func (BalanceMap) String added in v1.2.0

func (m BalanceMap) String() string

type BalanceSnapshot added in v1.33.0

type BalanceSnapshot struct {
	Balances BalanceMap `json:"balances"`
	Session  string     `json:"session"`
	Time     time.Time  `json:"time"`
}

func (BalanceSnapshot) CsvHeader added in v1.33.0

func (m BalanceSnapshot) CsvHeader() []string

func (BalanceSnapshot) CsvRecords added in v1.33.0

func (m BalanceSnapshot) CsvRecords() [][]string

type BalanceType added in v1.58.0

type BalanceType string
const (
	BalanceTypeAvailable BalanceType = "AVAILABLE"
	BalanceTypeLocked    BalanceType = "LOCKED"
	BalanceTypeBorrowed  BalanceType = "BORROWED"
	BalanceTypeInterest  BalanceType = "INTEREST"
	BalanceTypeNet       BalanceType = "NET"
	BalanceTypeTotal     BalanceType = "TOTAL"
	BalanceTypeDebt      BalanceType = "DEBT"
)

func ParseBalanceType added in v1.58.0

func ParseBalanceType(s string) (b BalanceType, err error)

func (BalanceType) Map added in v1.58.0

func (b BalanceType) Map(balance Balance) fixedpoint.Value

func (*BalanceType) UnmarshalJSON added in v1.58.0

func (b *BalanceType) UnmarshalJSON(data []byte) error

type BeforeConnect added in v1.52.0

type BeforeConnect func(ctx context.Context) error

type BollingerSetting added in v1.36.0

type BollingerSetting struct {
	IntervalWindow
	BandWidth float64 `json:"bandWidth"`
}

BollingerSetting contains the bollinger indicator setting propers Interval, Window and BandWidth

type BookSignal added in v1.55.0

type BookSignal struct {
	Type BookSignalType
	Time time.Time
}

type BookSignalType added in v1.55.0

type BookSignalType int
const (
	BookSignalSnapshot BookSignalType = 1
	BookSignalUpdate   BookSignalType = 2
)

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 BoolSeries added in v1.30.2

type BoolSeries interface {
	Last() bool
	Index(int) bool
	Length() int
}

The interface maps to pinescript basic type `series` for bool type Access the internal historical data from the latest to the oldest Index(0) always maps to Last()

func CrossOver added in v1.30.2

func CrossOver(a Series, b Series) BoolSeries

a series cross above b series. If in current KLine, a is higher than b, and in previous KLine, a is lower than b, then return true. Otherwise return false. If accessing index <= length, will always return false

func CrossUnder added in v1.30.2

func CrossUnder(a Series, b Series) BoolSeries

a series cross under b series. If in current KLine, a is lower than b, and in previous KLine, a is higher than b, then return true. Otherwise return false. If accessing index <= length, will always return false

type CancelReplaceModeType added in v1.43.0

type CancelReplaceModeType string
var (
	StopOnFailure CancelReplaceModeType = "STOP_ON_FAILURE"
	AllowFailure  CancelReplaceModeType = "ALLOW_FAILURE"
)

type Canvas added in v1.38.0

type Canvas struct {
	chart.Chart
	Interval Interval
}

func NewCanvas added in v1.38.0

func NewCanvas(title string, intervals ...Interval) *Canvas

func (*Canvas) Plot added in v1.38.0

func (canvas *Canvas) Plot(tag string, a Series, endTime Time, length int, intervals ...Interval)

func (*Canvas) PlotRaw added in v1.38.0

func (canvas *Canvas) PlotRaw(tag string, a Series, length int)

type ChangeResult added in v1.30.2

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

func (*ChangeResult) Index added in v1.30.2

func (c *ChangeResult) Index(i int) float64

func (*ChangeResult) Last added in v1.30.2

func (c *ChangeResult) Last(i int) float64

func (*ChangeResult) Length added in v1.30.2

func (c *ChangeResult) Length() int

type Channel

type Channel string

type Color added in v1.17.0

type Color bool

Color is the RB Tree color

type CorrFunc added in v1.36.0

type CorrFunc func(Series, Series, int) float64

type CrossResult added in v1.30.2

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

The result structure that maps to the crossing result of `CrossOver` and `CrossUnder` Accessible through BoolSeries interface

func (*CrossResult) Index added in v1.30.2

func (c *CrossResult) Index(i int) bool

func (*CrossResult) Last added in v1.30.2

func (c *CrossResult) Last() bool

func (*CrossResult) Length added in v1.30.2

func (c *CrossResult) Length() int

type CsvFormatter added in v1.33.0

type CsvFormatter interface {
	CsvHeader() []string
	CsvRecords() [][]string
}

CsvFormatter is an interface used for dumping object into csv file

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        fixedpoint.Value `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"`

	// Required confirm for unlock balance
	UnlockConfirm int `json:"unlockConfirm"`

	// Confirmation format = "current/required", for example: "7/16"
	Confirmation string `json:"confirmation"`
}

func (Deposit) EffectiveTime

func (d Deposit) EffectiveTime() time.Time

func (Deposit) GetCurrentConfirmation added in v1.52.0

func (d Deposit) GetCurrentConfirmation() (current int, required int)

func (Deposit) String added in v1.33.2

func (d Deposit) String() (o string)

type DepositStatus

type DepositStatus string

type Depth added in v1.25.4

type Depth string
const (
	DepthLevelFull   Depth = "FULL"
	DepthLevelMedium Depth = "MEDIUM"
	DepthLevel1      Depth = "1"
	DepthLevel5      Depth = "5"
	DepthLevel10     Depth = "10"
	DepthLevel15     Depth = "15"
	DepthLevel20     Depth = "20"
	DepthLevel50     Depth = "50"
	DepthLevel200    Depth = "200"
	DepthLevel400    Depth = "400"
)

type Direction added in v1.2.1

type Direction int

type Dispatcher added in v1.23.0

type Dispatcher func(e interface{})

type DivSeriesResult added in v1.30.2

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

func (*DivSeriesResult) Index added in v1.30.2

func (a *DivSeriesResult) Index(i int) float64

func (*DivSeriesResult) Last added in v1.30.2

func (a *DivSeriesResult) Last(i int) float64

func (*DivSeriesResult) Length added in v1.30.2

func (a *DivSeriesResult) Length() int

type Duration added in v1.3.1

type Duration time.Duration

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 EndpointCreator added in v1.23.0

type EndpointCreator func(ctx context.Context) (string, error)

type ExchangeAccountService added in v1.48.0

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

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

type ExchangeAmountFeeProtect added in v1.39.0

type ExchangeAmountFeeProtect interface {
	SetModifyOrderAmountForFee(ExchangeFee)
}

type ExchangeBasic added in v1.48.0

type ExchangeBasic = Exchange

ExchangeBasic is the new type for replacing the original Exchange interface

type ExchangeDefaultFeeRates added in v1.33.0

type ExchangeDefaultFeeRates interface {
	DefaultFeeRates() ExchangeFee
}

type ExchangeFee added in v1.21.0

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

ExchangeFee stores the exchange fee rate

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 ExchangeMinimal added in v1.48.0

type ExchangeMinimal interface {
	Name() ExchangeName
	PlatformFeeCurrency() string
}

type ExchangeName

type ExchangeName string
const (
	ExchangeMax      ExchangeName = "max"
	ExchangeBinance  ExchangeName = "binance"
	ExchangeOKEx     ExchangeName = "okex"
	ExchangeKucoin   ExchangeName = "kucoin"
	ExchangeBitget   ExchangeName = "bitget"
	ExchangeBacktest ExchangeName = "backtest"
	ExchangeBybit    ExchangeName = "bybit"
)

func ValidExchangeName

func ValidExchangeName(a string) (ExchangeName, error)

func (ExchangeName) IsValid added in v1.54.0

func (n ExchangeName) IsValid() bool

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 ExchangeOrderQueryService added in v1.28.0

type ExchangeOrderQueryService interface {
	QueryOrder(ctx context.Context, q OrderQuery) (*Order, error)
	QueryOrderTrades(ctx context.Context, q OrderQuery) ([]Trade, error)
}

ExchangeOrderQueryService provides an interface for querying the order status via order ID or client order ID

type ExchangePublic added in v1.58.0

type ExchangePublic interface {
	ExchangeMinimal
	ExchangeMarketDataService
}

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 {
	SubmitOrder(ctx context.Context, order SubmitOrder) (createdOrder *Order, err error)

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

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

type ExchangeTransferHistoryService added in v1.60.0

type ExchangeTransferHistoryService 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 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 {
	Withdraw(ctx context.Context, asset string, amount fixedpoint.Value, address string, options *WithdrawalOptions) error
}

type FilterResult added in v1.42.0

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

func (*FilterResult) Index added in v1.42.0

func (f *FilterResult) Index(j int) float64

func (*FilterResult) Last added in v1.42.0

func (f *FilterResult) Last(j int) float64

func (*FilterResult) Length added in v1.42.0

func (f *FilterResult) Length() int

type Float64Calculator added in v1.51.0

type Float64Calculator interface {
	Calculate(x float64) float64
	PushAndEmit(x float64)
}

type Float64Indicator added in v1.17.1

type Float64Indicator interface {
	Last(i int) float64
}

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

type Float64Series added in v1.51.0

type Float64Series struct {
	SeriesBase
	Float64Updater
	Slice floats.Slice
}

func NewFloat64Series added in v1.51.0

func NewFloat64Series(v ...float64) *Float64Series

func (*Float64Series) AddSubscriber added in v1.53.0

func (f *Float64Series) AddSubscriber(fn func(v float64))

AddSubscriber adds the subscriber function and push historical data to the subscriber

func (*Float64Series) Bind added in v1.51.0

func (f *Float64Series) Bind(source Float64Source, target Float64Calculator)

Bind binds the source event to the target (Float64Calculator) A Float64Calculator should be able to calculate the float64 result from a single float64 argument input

func (*Float64Series) Index added in v1.51.0

func (f *Float64Series) Index(i int) float64

func (*Float64Series) Last added in v1.51.0

func (f *Float64Series) Last(i int) float64

func (*Float64Series) Length added in v1.51.0

func (f *Float64Series) Length() int

func (*Float64Series) Push added in v1.51.0

func (f *Float64Series) Push(x float64)

func (*Float64Series) PushAndEmit added in v1.51.0

func (f *Float64Series) PushAndEmit(x float64)

func (*Float64Series) Subscribe added in v1.51.0

func (f *Float64Series) Subscribe(source Float64Source, c func(x float64))

type Float64Source added in v1.51.0

type Float64Source interface {
	Series
	OnUpdate(f func(v float64))
}

type Float64Subscription added in v1.51.0

type Float64Subscription interface {
	Series
	AddSubscriber(f func(v float64))
}

type Float64Truncator added in v1.51.0

type Float64Truncator interface {
	Truncate()
}

type Float64Updater added in v1.51.0

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

func (*Float64Updater) EmitUpdate added in v1.51.0

func (F *Float64Updater) EmitUpdate(v float64)

func (*Float64Updater) OnUpdate added in v1.51.0

func (F *Float64Updater) OnUpdate(cb func(v float64))

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                      FuturesAssetMap    `json:"assets"`
	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 FuturesAssetMap added in v1.26.2

type FuturesAssetMap map[string]FuturesUserAsset

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"`

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

	// Futures data fields
	// -------------------
	// Isolated margin mode
	Isolated bool `json:"isolated"`

	// UpdateTime is the time when the position is updated
	UpdateTime int64 `json:"updateTime"`

	// PositionRisk stores the position risk data
	PositionRisk *PositionRisk
}

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 HeartBeat added in v1.52.0

type HeartBeat func(conn *websocket.Conn) error

HeartBeat keeps connection alive by sending the ping packet.

type HeikinAshiStream added in v1.35.0

type HeikinAshiStream struct {
	StandardStreamEmitter

	LastOrigin map[string]map[Interval]*KLine
	// contains filtered or unexported fields
}

func (*HeikinAshiStream) EmitKLine added in v1.35.0

func (s *HeikinAshiStream) EmitKLine(kline KLine)

No writeback to lastAshi

func (*HeikinAshiStream) EmitKLineClosed added in v1.35.0

func (s *HeikinAshiStream) EmitKLineClosed(kline KLine)

type InstanceIDProvider added in v1.40.0

type InstanceIDProvider interface {
	InstanceID() string
}

type Interval

type Interval string

func (Interval) Duration

func (i Interval) Duration() time.Duration

func (Interval) Milliseconds added in v1.43.0

func (i Interval) Milliseconds() int

Milliseconds is specially handled, for better precision for ms level interval, calling Seconds and Minutes directly might trigger panic error

func (Interval) Minutes

func (i Interval) Minutes() int

func (Interval) Seconds added in v1.43.0

func (i Interval) Seconds() int

func (Interval) String

func (i Interval) String() string

func (*Interval) UnmarshalJSON

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

type IntervalMap added in v1.51.0

type IntervalMap map[Interval]int

func (IntervalMap) Slice added in v1.51.0

func (m IntervalMap) Slice() (slice IntervalSlice)

type IntervalProfitCollector added in v1.38.0

type IntervalProfitCollector struct {
	Interval  Interval      `json:"interval"`
	Profits   *floats.Slice `json:"profits"`
	Timestamp *floats.Slice `json:"timestamp"`
	// contains filtered or unexported fields
}

func NewIntervalProfitCollector added in v1.38.0

func NewIntervalProfitCollector(i Interval, startTime time.Time) *IntervalProfitCollector

func (*IntervalProfitCollector) GetNonProfitableIntervals added in v1.39.0

func (s *IntervalProfitCollector) GetNonProfitableIntervals() (result []ProfitReport)

Get all none-profitable intervals

func (*IntervalProfitCollector) GetNumOfNonProfitableIntervals added in v1.38.0

func (s *IntervalProfitCollector) GetNumOfNonProfitableIntervals() (nonprofit int)

Get number of non-profitable traded intervals (no trade within the interval or pnl = 0 will be also included here)

func (*IntervalProfitCollector) GetNumOfProfitableIntervals added in v1.38.0

func (s *IntervalProfitCollector) GetNumOfProfitableIntervals() (profit int)

Get number of profitable traded intervals

func (*IntervalProfitCollector) GetOmega added in v1.38.0

func (s *IntervalProfitCollector) GetOmega() float64

func (*IntervalProfitCollector) GetProfitableIntervals added in v1.39.0

func (s *IntervalProfitCollector) GetProfitableIntervals() (result []ProfitReport)

Get all profitable intervals

func (*IntervalProfitCollector) GetSharpe added in v1.38.0

func (s *IntervalProfitCollector) GetSharpe() float64

Get sharpe value with the interval of profit collected. no smart sharpe ON for the calculated result

func (*IntervalProfitCollector) GetSortino added in v1.39.2

func (s *IntervalProfitCollector) GetSortino() float64

Get sortino value with the interval of profit collected. No risk-free return rate and smart sortino OFF for the calculated result.

func (IntervalProfitCollector) MarshalYAML added in v1.38.0

func (s IntervalProfitCollector) MarshalYAML() (interface{}, error)

func (*IntervalProfitCollector) Update added in v1.38.0

func (s *IntervalProfitCollector) Update(profit *Profit)

Update the collector by every traded profit

type IntervalSlice

type IntervalSlice []Interval

func (IntervalSlice) Sort added in v1.51.0

func (s IntervalSlice) Sort()

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 (for example, EWMA and SMA)
	Window int `json:"window"`

	// RightWindow is used by the pivot indicator
	RightWindow *int `json:"rightWindow"`
}

IntervalWindow is used by the indicators

func (IntervalWindow) String added in v1.4.0

func (iw IntervalWindow) String() string

type IntervalWindowBandWidth added in v1.31.0

type IntervalWindowBandWidth struct {
	IntervalWindow
	BandWidth float64 `json:"bandWidth"`
}

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              IsolatedMarginAssetMap `json:"assets"`
}

IsolatedMarginAccount defines isolated user assets of margin account

type IsolatedMarginAccountInfo added in v1.26.2

type IsolatedMarginAccountInfo struct {
	TotalAssetOfBTC     fixedpoint.Value       `json:"totalAssetOfBtc"`
	TotalLiabilityOfBTC fixedpoint.Value       `json:"totalLiabilityOfBtc"`
	TotalNetAssetOfBTC  fixedpoint.Value       `json:"totalNetAssetOfBtc"`
	Assets              IsolatedMarginAssetMap `json:"userAssets"`
}

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 IsolatedMarginAssetMap added in v1.26.2

type IsolatedMarginAssetMap map[string]IsolatedMarginAsset

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 JsonArr added in v1.40.0

type JsonArr []JsonStruct

func (JsonArr) Len added in v1.40.0

func (a JsonArr) Len() int

func (JsonArr) Less added in v1.40.0

func (a JsonArr) Less(i, j int) bool

func (JsonArr) Swap added in v1.40.0

func (a JsonArr) Swap(i, j int)

type JsonStruct added in v1.40.0

type JsonStruct struct {
	Key   string
	Json  string
	Type  string
	Value interface{}
}

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 follows the binance rule, to avoid endTime overlapping with the next startTime. So if your end time (2023-01-01 01:00:00)
	// are overlapping with next start time interval (2023-01-01 01:00:00), you should subtract -1 time.millisecond on EndTime.
	EndTime Time `json:"endTime" db:"end_time"`

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

	Open                     fixedpoint.Value `json:"open" db:"open"`
	Close                    fixedpoint.Value `json:"close" db:"close"`
	High                     fixedpoint.Value `json:"high" db:"high"`
	Low                      fixedpoint.Value `json:"low" db:"low"`
	Volume                   fixedpoint.Value `json:"volume" db:"volume"`
	QuoteVolume              fixedpoint.Value `json:"quoteVolume" db:"quote_volume"`
	TakerBuyBaseAssetVolume  fixedpoint.Value `json:"takerBuyBaseAssetVolume" db:"taker_buy_base_volume"`
	TakerBuyQuoteAssetVolume fixedpoint.Value `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 SortKLinesAscending added in v1.33.0

func SortKLinesAscending(klines []KLine) []KLine

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) GetAmplification added in v1.26.1

func (k *KLine) GetAmplification() fixedpoint.Value

func (*KLine) GetBody

func (k *KLine) GetBody() fixedpoint.Value

GetBody returns the height of the candle real body

func (*KLine) GetChange

func (k *KLine) GetChange() fixedpoint.Value

GetChange returns Close price - Open price.

func (*KLine) GetClose

func (k *KLine) GetClose() fixedpoint.Value

func (*KLine) GetEndTime

func (k *KLine) GetEndTime() Time

func (*KLine) GetHigh

func (k *KLine) GetHigh() fixedpoint.Value

func (*KLine) GetInterval

func (k *KLine) GetInterval() Interval

func (*KLine) GetLow

func (k *KLine) GetLow() fixedpoint.Value

func (*KLine) GetLowerShadowHeight

func (k *KLine) GetLowerShadowHeight() fixedpoint.Value

func (*KLine) GetLowerShadowRatio

func (k *KLine) GetLowerShadowRatio() fixedpoint.Value

func (*KLine) GetMaxChange

func (k *KLine) GetMaxChange() fixedpoint.Value

func (*KLine) GetOpen

func (k *KLine) GetOpen() fixedpoint.Value

func (*KLine) GetStartTime

func (k *KLine) GetStartTime() Time

func (*KLine) GetThickness

func (k *KLine) GetThickness() fixedpoint.Value

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

func (*KLine) GetUpperShadowHeight

func (k *KLine) GetUpperShadowHeight() fixedpoint.Value

func (*KLine) GetUpperShadowRatio

func (k *KLine) GetUpperShadowRatio() fixedpoint.Value

func (*KLine) Merge added in v1.40.3

func (k *KLine) Merge(o *KLine)

func (*KLine) Mid

func (k *KLine) Mid() fixedpoint.Value

func (*KLine) PlainText added in v1.18.0

func (k *KLine) PlainText() string

func (*KLine) Set added in v1.38.0

func (k *KLine) Set(o *KLine)

func (*KLine) SlackAttachment

func (k *KLine) SlackAttachment() slack.Attachment

func (*KLine) String

func (k *KLine) String() string

type KLineCallback

type KLineCallback func(k KLine)

func KLineWith added in v1.36.0

func KLineWith(symbol string, interval Interval, callback KLineCallback) KLineCallback

type KLineOrWindow

type KLineOrWindow interface {
	GetInterval() string
	Direction() Direction
	GetChange() fixedpoint.Value
	GetMaxChange() fixedpoint.Value
	GetThickness() fixedpoint.Value

	Mid() fixedpoint.Value
	GetOpen() fixedpoint.Value
	GetClose() fixedpoint.Value
	GetHigh() fixedpoint.Value
	GetLow() fixedpoint.Value

	BounceUp() bool
	BounceDown() bool
	GetUpperShadowRatio() fixedpoint.Value
	GetLowerShadowRatio() fixedpoint.Value

	SlackAttachment() slack.Attachment
}

type KLineQueryOptions

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

type KLineSeries added in v1.30.2

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

func (*KLineSeries) Index added in v1.30.2

func (k *KLineSeries) Index(i int) float64

func (*KLineSeries) Last added in v1.30.2

func (k *KLineSeries) Last(i int) float64

func (*KLineSeries) Length added in v1.30.2

func (k *KLineSeries) Length() int

type KLineValueMapper added in v1.51.0

type KLineValueMapper func(k KLine) float64

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) Close added in v1.30.2

func (k *KLineWindow) Close() Series

func (KLineWindow) Color

func (k KLineWindow) Color() string

func (KLineWindow) First

func (k KLineWindow) First() KLine

func (KLineWindow) GetAmplification added in v1.26.1

func (k KLineWindow) GetAmplification() fixedpoint.Value

func (KLineWindow) GetBody

func (k KLineWindow) GetBody() fixedpoint.Value

func (KLineWindow) GetChange

func (k KLineWindow) GetChange() fixedpoint.Value

func (KLineWindow) GetClose

func (k KLineWindow) GetClose() fixedpoint.Value

func (KLineWindow) GetHigh

func (k KLineWindow) GetHigh() fixedpoint.Value

func (KLineWindow) GetInterval

func (k KLineWindow) GetInterval() Interval

func (KLineWindow) GetLow

func (k KLineWindow) GetLow() fixedpoint.Value

func (KLineWindow) GetLowerShadowHeight

func (k KLineWindow) GetLowerShadowHeight() fixedpoint.Value

func (KLineWindow) GetLowerShadowRatio

func (k KLineWindow) GetLowerShadowRatio() fixedpoint.Value

func (KLineWindow) GetMaxChange

func (k KLineWindow) GetMaxChange() fixedpoint.Value

func (KLineWindow) GetOpen

func (k KLineWindow) GetOpen() fixedpoint.Value

func (KLineWindow) GetThickness

func (k KLineWindow) GetThickness() fixedpoint.Value

func (KLineWindow) GetTrend

func (k KLineWindow) GetTrend() int

func (KLineWindow) GetUpperShadowHeight

func (k KLineWindow) GetUpperShadowHeight() fixedpoint.Value

func (KLineWindow) GetUpperShadowRatio

func (k KLineWindow) GetUpperShadowRatio() fixedpoint.Value

func (*KLineWindow) High added in v1.30.2

func (k *KLineWindow) High() Series

func (KLineWindow) Last

func (k KLineWindow) Last() KLine

func (KLineWindow) Len

func (k KLineWindow) Len() int

func (*KLineWindow) Low added in v1.30.2

func (k *KLineWindow) Low() Series

func (KLineWindow) Mid

func (k KLineWindow) Mid() fixedpoint.Value

Mid price

func (*KLineWindow) Open added in v1.30.2

func (k *KLineWindow) Open() Series

func (KLineWindow) ReduceClose

func (k KLineWindow) ReduceClose() fixedpoint.Value

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

func (*KLineWindow) Volume added in v1.30.2

func (k *KLineWindow) Volume() Series

type KValueType added in v1.30.2

type KValueType int

type LiquidationInfo added in v1.53.0

type LiquidationInfo struct {
	Symbol       string
	Side         SideType
	OrderType    OrderType
	TimeInForce  TimeInForce
	Quantity     fixedpoint.Value
	Price        fixedpoint.Value
	AveragePrice fixedpoint.Value
	OrderStatus  OrderStatus
	TradeTime    Time
}

type LogisticRegressionModel added in v1.37.0

type LogisticRegressionModel struct {
	Weight       []float64
	Gradient     float64
	LearningRate float64
}

func LogisticRegression added in v1.37.0

func LogisticRegression(x []Series, y Series, lookback, iterations int, learningRate float64) *LogisticRegressionModel

func (*LogisticRegressionModel) Predict added in v1.37.0

func (l *LogisticRegressionModel) Predict(x []float64) float64

type LooseFormatTime added in v1.27.0

type LooseFormatTime time.Time

LooseFormatTime parses date time string with a wide range of formats.

func ParseLooseFormatTime added in v1.36.0

func ParseLooseFormatTime(s string) (LooseFormatTime, error)

func (LooseFormatTime) MarshalJSON added in v1.33.0

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

func (LooseFormatTime) Time added in v1.27.0

func (t LooseFormatTime) Time() time.Time

func (*LooseFormatTime) UnmarshalJSON added in v1.27.0

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

func (*LooseFormatTime) UnmarshalYAML added in v1.27.0

func (t *LooseFormatTime) UnmarshalYAML(unmarshal func(interface{}) error) error

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 MarginAccountInfo added in v1.26.2

type MarginAccountInfo struct {
	// Margin fields
	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"`
	Assets              MarginAssetMap   `json:"userAssets"`
}

type MarginAssetMap added in v1.26.2

type MarginAssetMap map[string]MarginUserAsset

type MarginBorrowRepayService added in v1.33.0

type MarginBorrowRepayService interface {
	RepayMarginAsset(ctx context.Context, asset string, amount fixedpoint.Value) error
	BorrowMarginAsset(ctx context.Context, asset string, amount fixedpoint.Value) error
	QueryMarginAssetMaxBorrowable(ctx context.Context, asset string) (amount fixedpoint.Value, err error)
}

MarginBorrowRepayService provides repay and borrow actions of an crypto exchange

type MarginExchange added in v1.8.0

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

type MarginHistoryService added in v1.45.0

type MarginHistoryService interface {
	QueryLoanHistory(ctx context.Context, asset string, startTime, endTime *time.Time) ([]MarginLoan, error)
	QueryRepayHistory(ctx context.Context, asset string, startTime, endTime *time.Time) ([]MarginRepay, error)
	QueryLiquidationHistory(ctx context.Context, startTime, endTime *time.Time) ([]MarginLiquidation, error)
	QueryInterestHistory(ctx context.Context, asset string, startTime, endTime *time.Time) ([]MarginInterest, error)
}

MarginHistoryService provides the service of querying loan history and repay history

type MarginInterest added in v1.33.0

type MarginInterest struct {
	GID            uint64           `json:"gid" db:"gid"`
	Exchange       ExchangeName     `json:"exchange" db:"exchange"`
	Asset          string           `json:"asset" db:"asset"`
	Principle      fixedpoint.Value `json:"principle" db:"principle"`
	Interest       fixedpoint.Value `json:"interest" db:"interest"`
	InterestRate   fixedpoint.Value `json:"interestRate" db:"interest_rate"`
	IsolatedSymbol string           `json:"isolatedSymbol" db:"isolated_symbol"`
	Time           Time             `json:"time" db:"time"`
}

type MarginLiquidation added in v1.33.0

type MarginLiquidation struct {
	GID              uint64           `json:"gid" db:"gid"`
	Exchange         ExchangeName     `json:"exchange" db:"exchange"`
	AveragePrice     fixedpoint.Value `json:"averagePrice" db:"average_price"`
	ExecutedQuantity fixedpoint.Value `json:"executedQuantity" db:"executed_quantity"`
	OrderID          uint64           `json:"orderID" db:"order_id"`
	Price            fixedpoint.Value `json:"price" db:"price"`
	Quantity         fixedpoint.Value `json:"quantity" db:"quantity"`
	Side             SideType         `json:"side" db:"side"`
	Symbol           string           `json:"symbol" db:"symbol"`
	TimeInForce      TimeInForce      `json:"timeInForce" db:"time_in_force"`
	IsIsolated       bool             `json:"isIsolated" db:"is_isolated"`
	UpdatedTime      Time             `json:"updatedTime" db:"time"`
}

type MarginLoan added in v1.33.0

type MarginLoan struct {
	GID            uint64           `json:"gid" db:"gid"`
	Exchange       ExchangeName     `json:"exchange" db:"exchange"`
	TransactionID  uint64           `json:"transactionID" db:"transaction_id"`
	Asset          string           `json:"asset" db:"asset"`
	Principle      fixedpoint.Value `json:"principle" db:"principle"`
	Time           Time             `json:"time" db:"time"`
	IsolatedSymbol string           `json:"isolatedSymbol" db:"isolated_symbol"`
}

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"
	SideEffectTypeAutoBorrowRepay MarginOrderSideEffectType = "AUTO_BORROW_REPAY"
)

func (*MarginOrderSideEffectType) UnmarshalJSON added in v1.11.0

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

type MarginRepay added in v1.33.0

type MarginRepay struct {
	GID            uint64           `json:"gid" db:"gid"`
	Exchange       ExchangeName     `json:"exchange" db:"exchange"`
	TransactionID  uint64           `json:"transactionID" db:"transaction_id"`
	Asset          string           `json:"asset" db:"asset"`
	Principle      fixedpoint.Value `json:"principle" db:"principle"`
	Time           Time             `json:"time" db:"time"`
	IsolatedSymbol string           `json:"isolatedSymbol" db:"isolated_symbol"`
}

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 MarginType added in v1.60.1

type MarginType string
const (
	MarginTypeSpot           MarginType = "spot"
	MarginTypeCrossMargin    MarginType = "cross_margin"
	MarginTypeIsolatedMargin MarginType = "isolated_margin"
)

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 {
	Exchange ExchangeName `json:"exchange,omitempty"`

	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 fixedpoint.Value `json:"minNotional,omitempty"`
	MinAmount   fixedpoint.Value `json:"minAmount,omitempty"`

	// The LOT_SIZE filter defines the quantity
	MinQuantity fixedpoint.Value `json:"minQuantity,omitempty"`

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

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

	// TickSize is the step size of price
	TickSize fixedpoint.Value `json:"tickSize,omitempty"`

	MinPrice fixedpoint.Value `json:"minPrice,omitempty"`
	MaxPrice fixedpoint.Value `json:"maxPrice,omitempty"`
}

func (Market) AdjustQuantityByMaxAmount added in v1.60.0

func (m Market) AdjustQuantityByMaxAmount(quantity, currentPrice, maxAmount fixedpoint.Value) fixedpoint.Value

AdjustQuantityByMaxAmount adjusts the quantity to make the amount less than the given maxAmount

func (Market) AdjustQuantityByMinNotional added in v1.45.0

func (m Market) AdjustQuantityByMinNotional(quantity, currentPrice fixedpoint.Value) fixedpoint.Value

AdjustQuantityByMinNotional adjusts the quantity to make the amount greater than the given minAmount

func (Market) AdjustQuantityByMinQuantity added in v1.58.0

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

func (Market) BaseCurrencyFormatter added in v1.18.0

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

func (Market) CanonicalizeVolume

func (m Market) CanonicalizeVolume(val fixedpoint.Value) float64

func (Market) FormatPrice

func (m Market) FormatPrice(val fixedpoint.Value) string

func (Market) FormatPriceCurrency

func (m Market) FormatPriceCurrency(val fixedpoint.Value) string

func (Market) FormatQuantity

func (m Market) FormatQuantity(val fixedpoint.Value) string

func (Market) FormatVolume

func (m Market) FormatVolume(val fixedpoint.Value) string

func (Market) GreaterThanMinimalOrderQuantity added in v1.52.0

func (m Market) GreaterThanMinimalOrderQuantity(
	side SideType, price, available fixedpoint.Value,
) (fixedpoint.Value, bool)

GreaterThanMinimalOrderQuantity ensures that your given balance could fit the minimal order quantity when side = sell, then available = base balance when side = buy, then available = quote balance The balance will be truncated first in order to calculate the minimal notional and minimal quantity The adjusted (truncated) order quantity will be returned

func (Market) IsDustQuantity added in v1.33.0

func (m Market) IsDustQuantity(quantity, price fixedpoint.Value) bool

func (Market) QuoteCurrencyFormatter added in v1.18.0

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

func (Market) RoundDownQuantityByPrecision added in v1.48.0

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

RoundDownQuantityByPrecision uses the volume precision to round down the quantity This is different from the TruncateQuantity, which uses StepSize (it uses fewer fractions to truncate)

func (Market) RoundUpByStepSize added in v1.60.0

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

func (Market) RoundUpQuantityByPrecision added in v1.48.0

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

RoundUpQuantityByPrecision uses the volume precision to round up the quantity

func (Market) TruncatePrice added in v1.39.2

func (m Market) TruncatePrice(price fixedpoint.Value) fixedpoint.Value

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

func (Market) TruncateQuoteQuantity added in v1.52.0

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

TruncateQuoteQuantity uses the tick size to truncate floating number, in order to avoid the rounding issue this is usually used for calculating the order size from the quote quantity.

type MarketMap

type MarketMap map[string]Market

func (MarketMap) Add added in v1.21.0

func (m MarketMap) Add(market Market)

func (MarketMap) Has added in v1.55.3

func (m MarketMap) Has(symbol string) bool

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 MinusSeriesResult added in v1.30.2

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

func (*MinusSeriesResult) Index added in v1.30.2

func (a *MinusSeriesResult) Index(i int) float64

func (*MinusSeriesResult) Last added in v1.30.2

func (a *MinusSeriesResult) Last(i int) float64

func (*MinusSeriesResult) Length added in v1.30.2

func (a *MinusSeriesResult) Length() int

type MulSeriesResult added in v1.30.2

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

func (*MulSeriesResult) Index added in v1.30.2

func (a *MulSeriesResult) Index(i int) float64

func (*MulSeriesResult) Last added in v1.30.2

func (a *MulSeriesResult) Last(i int) float64

func (*MulSeriesResult) Length added in v1.30.2

func (a *MulSeriesResult) Length() int

type MutexOrderBook

type MutexOrderBook struct {
	sync.Mutex

	Symbol   string
	Exchange ExchangeName
	// contains filtered or unexported fields
}

func NewMutexOrderBook

func NewMutexOrderBook(symbol string, exchangeName ExchangeName) *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() (ob OrderBook)

func (*MutexOrderBook) CopyDepth added in v1.17.0

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

func (*MutexOrderBook) IsValid added in v1.17.0

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

func (*MutexOrderBook) LastUpdateTime added in v1.25.4

func (b *MutexOrderBook) LastUpdateTime() time.Time

func (*MutexOrderBook) Load

func (b *MutexOrderBook) Load(book SliceOrderBook)

func (*MutexOrderBook) Reset added in v1.11.0

func (b *MutexOrderBook) Reset()

func (*MutexOrderBook) SideBook added in v1.55.0

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

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 NumberSeries added in v1.30.2

type NumberSeries float64

func (NumberSeries) Clone added in v1.38.0

func (a NumberSeries) Clone() NumberSeries

func (NumberSeries) Index added in v1.30.2

func (a NumberSeries) Index(_ int) float64

func (NumberSeries) Last added in v1.30.2

func (a NumberSeries) Last(_ int) float64

func (NumberSeries) Length added in v1.30.2

func (a NumberSeries) Length() int

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,omitempty" db:"gid"`
	OrderID uint64 `json:"orderID" db:"order_id"` // order id
	UUID    string `json:"uuid,omitempty"`

	Status OrderStatus `json:"status" db:"status"`

	// OriginalStatus stores the original order status from the specific exchange
	OriginalStatus string `json:"originalStatus,omitempty" db:"-"`

	// ExecutedQuantity is how much quantity has been executed
	ExecutedQuantity fixedpoint.Value `json:"executedQuantity" db:"executed_quantity"`

	// IsWorking means if the order is still on the order book (active order)
	IsWorking bool `json:"isWorking" db:"is_working"`

	// CreationTime is the time when this order is created
	CreationTime Time `json:"creationTime" db:"created_at"`

	// UpdateTime is the latest time when this order gets updated
	UpdateTime Time `json:"updateTime" db:"updated_at"`

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

func OrdersActive added in v1.44.0

func OrdersActive(in []Order) []Order

func OrdersFilled added in v1.44.0

func OrdersFilled(in []Order) (out []Order)

func OrdersFilter added in v1.44.0

func OrdersFilter(in []Order, f func(o Order) bool) (out []Order)

func SortOrdersAscending added in v1.33.0

func SortOrdersAscending(orders []Order) []Order

SortOrdersAscending sorts by creation time ascending-ly

func SortOrdersByPrice added in v1.55.0

func SortOrdersByPrice(orders []Order, descending bool) []Order

SortOrdersByPrice sorts by creation time ascending-ly

func SortOrdersDescending added in v1.56.0

func SortOrdersDescending(orders []Order) []Order

SortOrdersDescending sorts by creation time descending-ly

func SortOrdersUpdateTimeAscending added in v1.43.1

func SortOrdersUpdateTimeAscending(orders []Order) []Order

SortOrdersAscending sorts by update time ascending-ly

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) CsvHeader added in v1.33.0

func (o Order) CsvHeader() []string

func (Order) CsvRecords added in v1.33.0

func (o Order) CsvRecords() [][]string

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)
	LastUpdateTime() time.Time
	Reset()
	Load(book SliceOrderBook)
	Update(book SliceOrderBook)
	Copy() OrderBook
	SideBook(sideType SideType) PriceVolumeSlice
	CopyDepth(depth int) OrderBook
	IsValid() (bool, error)
}

type OrderError added in v1.25.3

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

func (*OrderError) Error added in v1.25.3

func (e *OrderError) Error() string

func (*OrderError) Order added in v1.25.3

func (e *OrderError) Order() Order

type OrderMap

type OrderMap map[uint64]Order

OrderMap is used for storing orders by their order id

func NewOrderMap added in v1.55.0

func NewOrderMap(os ...Order) OrderMap

func (OrderMap) Add

func (m OrderMap) Add(os ...Order)

Add the order the map

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) Get added in v1.44.0

func (m OrderMap) Get(orderID uint64) (Order, bool)

func (OrderMap) IDs

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

func (OrderMap) Lookup added in v1.43.0

func (m OrderMap) Lookup(f func(o Order) bool) *Order

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 ID exists in the map

type OrderQuery added in v1.28.0

type OrderQuery struct {
	Symbol        string
	OrderID       string
	ClientOrderID string
}

type OrderSlice

type OrderSlice []Order

func (*OrderSlice) Add added in v1.55.0

func (s *OrderSlice) Add(o Order)

func (OrderSlice) Map added in v1.55.0

func (s OrderSlice) Map() OrderMap

Map builds up an OrderMap by the order id

func (OrderSlice) Print added in v1.55.0

func (s OrderSlice) Print()

func (OrderSlice) SeparateBySide added in v1.55.0

func (s OrderSlice) SeparateBySide() (buyOrders, sellOrders []Order)

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"
)

func (OrderStatus) Closed added in v1.51.1

func (o OrderStatus) Closed() bool

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"
)

type PCA added in v1.40.3

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

func (*PCA) Fit added in v1.40.3

func (pca *PCA) Fit(x []SeriesExtend, lookback int) error

func (*PCA) FitTransform added in v1.40.3

func (pca *PCA) FitTransform(x []SeriesExtend, lookback, feature int) ([]SeriesExtend, error)

func (*PCA) Transform added in v1.40.3

func (pca *PCA) Transform(x []SeriesExtend, lookback int, features int) (result []SeriesExtend)

type Parser added in v1.23.0

type Parser func(message []byte) (interface{}, error)

type PercentageChangeResult added in v1.36.0

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

func (*PercentageChangeResult) Index added in v1.36.0

func (c *PercentageChangeResult) Index(i int) float64

func (*PercentageChangeResult) Last added in v1.36.0

func (c *PercentageChangeResult) Last(i int) float64

func (*PercentageChangeResult) Length added in v1.36.0

func (c *PercentageChangeResult) Length() int

type PeriodProfitStats added in v1.55.0

type PeriodProfitStats struct {
	PnL           fixedpoint.Value `json:"pnl,omitempty"`
	NetProfit     fixedpoint.Value `json:"netProfit,omitempty"`
	GrossProfit   fixedpoint.Value `json:"grossProfit,omitempty"`
	GrossLoss     fixedpoint.Value `json:"grossLoss,omitempty"`
	Volume        fixedpoint.Value `json:"volume,omitempty"`
	VolumeInQuote fixedpoint.Value `json:"volumeInQuote,omitempty"`
	MakerVolume   fixedpoint.Value `json:"makerVolume,omitempty"`
	TakerVolume   fixedpoint.Value `json:"takerVolume,omitempty"`

	// time fields
	LastTradeTime time.Time `json:"lastTradeTime,omitempty"`
	StartTime     time.Time `json:"startTime,omitempty"`
	EndTime       time.Time `json:"endTime,omitempty"`
}

PeriodProfitStats defined the profit stats for a period TODO: replace AccumulatedPnL and TodayPnL fields from the ProfitStats struct

type PersistenceTTL added in v1.56.0

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

func (*PersistenceTTL) Expiration added in v1.56.0

func (p *PersistenceTTL) Expiration() time.Duration

func (*PersistenceTTL) SetTTL added in v1.56.0

func (p *PersistenceTTL) SetTTL(ttl time.Duration)

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" db:"symbol"`
	BaseCurrency  string `json:"baseCurrency" db:"base"`
	QuoteCurrency string `json:"quoteCurrency" db:"quote"`

	Market Market `json:"market,omitempty"`

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

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

	// TotalFee stores the fee currency -> total fee quantity
	TotalFee map[string]fixedpoint.Value `json:"totalFee" db:"-"`

	// FeeAverageCosts stores the fee currency -> average cost of the fee
	// e.g. BNB -> 341.0
	FeeAverageCosts map[string]fixedpoint.Value `json:"feeAverageCosts" db:"-"`

	OpenedAt  time.Time `json:"openedAt,omitempty" db:"-"`
	ChangedAt time.Time `json:"changedAt,omitempty" db:"changed_at"`

	Strategy           string `json:"strategy,omitempty" db:"strategy"`
	StrategyInstanceID string `json:"strategyInstanceID,omitempty" db:"strategy_instance_id"`

	AccumulatedProfit fixedpoint.Value `json:"accumulatedProfit,omitempty" db:"accumulated_profit"`

	sync.Mutex
	// contains filtered or unexported fields
}

Position stores the position data

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(td 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)

BindStream binds the trade update callback and update the position

func (*Position) CsvHeader added in v1.33.0

func (p *Position) CsvHeader() []string

func (*Position) CsvRecords added in v1.33.0

func (p *Position) CsvRecords() [][]string

func (*Position) EmitModify added in v1.39.0

func (p *Position) EmitModify(baseQty fixedpoint.Value, quoteQty fixedpoint.Value, price fixedpoint.Value)

func (*Position) Expiration added in v1.53.0

func (s *Position) Expiration() time.Duration

func (*Position) GetBase added in v1.24.0

func (p *Position) GetBase() (base fixedpoint.Value)

GetBase locks the mutex and return the base quantity The base quantity can be negative

func (*Position) GetQuantity added in v1.36.0

func (p *Position) GetQuantity() fixedpoint.Value

GetQuantity calls GetBase() and then convert the number into a positive number that could be treated as a quantity.

func (*Position) IsClosed added in v1.33.0

func (p *Position) IsClosed() bool

func (*Position) IsClosing added in v1.49.0

func (p *Position) IsClosing() (c bool)

func (*Position) IsDust added in v1.33.0

func (p *Position) IsDust(a ...fixedpoint.Value) bool

IsDust checks if the position is dust, the first argument is the price to calculate the dust quantity

func (*Position) IsLong added in v1.33.0

func (p *Position) IsLong() bool

func (*Position) IsOpened added in v1.36.0

func (p *Position) IsOpened(currentPrice fixedpoint.Value) bool

func (*Position) IsShort added in v1.33.0

func (p *Position) IsShort() bool

func (*Position) ModifyAverageCost added in v1.39.0

func (p *Position) ModifyAverageCost(price fixedpoint.Value) error

ModifyAverageCost modifies position average cost with `price`

func (*Position) ModifyBase added in v1.39.0

func (p *Position) ModifyBase(qty fixedpoint.Value) error

ModifyBase modifies position base quantity with `qty`

func (*Position) ModifyQuote added in v1.39.0

func (p *Position) ModifyQuote(qty fixedpoint.Value) error

ModifyQuote modifies position quote quantity with `qty`

func (*Position) NewMarketCloseOrder added in v1.33.3

func (p *Position) NewMarketCloseOrder(percentage fixedpoint.Value) *SubmitOrder

func (*Position) NewProfit added in v1.28.0

func (p *Position) NewProfit(trade Trade, profit, netProfit fixedpoint.Value) Profit

NewProfit generates the profit object from the current position

func (*Position) OnModify added in v1.39.0

func (p *Position) OnModify(cb func(baseQty fixedpoint.Value, quoteQty fixedpoint.Value, price fixedpoint.Value))

func (*Position) PlainText added in v1.21.0

func (p *Position) PlainText() (msg string)

func (*Position) ROI added in v1.36.0

func (p *Position) ROI(price fixedpoint.Value) fixedpoint.Value

ROI -- Return on investment (ROI) is a performance measure used to evaluate the efficiency or profitability of an investment or compare the efficiency of a number of different investments. ROI tries to directly measure the amount of return on a particular investment, relative to the investment's cost.

func (*Position) Reset added in v1.21.0

func (p *Position) Reset()

func (*Position) SetClosing added in v1.49.0

func (p *Position) SetClosing(c bool) bool

func (*Position) SetExchangeFeeRate added in v1.21.0

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

func (*Position) SetFeeAverageCost added in v1.60.1

func (p *Position) SetFeeAverageCost(currency string, cost fixedpoint.Value)

func (*Position) SetFeeRate added in v1.21.0

func (p *Position) SetFeeRate(exchangeFee ExchangeFee)

func (*Position) SetTTL added in v1.53.0

func (s *Position) SetTTL(ttl time.Duration)

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

func (*Position) Type added in v1.24.0

func (p *Position) Type() PositionType

func (*Position) UnrealizedProfit added in v1.33.0

func (p *Position) UnrealizedProfit(price fixedpoint.Value) fixedpoint.Value

func (*Position) UpdateMetrics added in v1.60.1

func (p *Position) UpdateMetrics()

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,omitempty"`
	LiquidationPrice fixedpoint.Value `json:"liquidationPrice,omitempty"`
}

PositionRisk stores the position risk data

type PositionType added in v1.24.0

type PositionType string

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"`
}

func (*PremiumIndex) String added in v1.45.0

func (i *PremiumIndex) String() string

type PriceHeartBeat added in v1.25.4

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

PriceHeartBeat is used for monitoring the price volume update.

func NewPriceHeartBeat added in v1.55.0

func NewPriceHeartBeat(timeout time.Duration) *PriceHeartBeat

func (*PriceHeartBeat) Last added in v1.55.0

func (b *PriceHeartBeat) Last() PriceVolume

func (*PriceHeartBeat) Update added in v1.25.4

func (b *PriceHeartBeat) Update(current PriceVolume) (bool, error)

Update updates the price volume object and the last update time It returns (bool, error), when the price is successfully updated, it returns true. If the price is not updated (same price) and the last time exceeded the timeout, Then false, and an error will be returned

type PriceMap added in v1.41.0

type PriceMap map[string]fixedpoint.Value

type PriceType added in v1.57.0

type PriceType string
const (
	// PriceTypeLast uses the last price from the given ticker
	PriceTypeLast PriceType = "LAST"

	// PriceTypeBid uses the bid price from the given ticker
	PriceTypeBid PriceType = "BID"

	// PriceTypeAsk uses the ask price from the given ticker
	PriceTypeAsk PriceType = "ASK"

	// PriceTypeMid calculates the middle price from the given ticker
	PriceTypeMid PriceType = "MID"

	PriceTypeMaker PriceType = "MAKER"
	PriceTypeTaker PriceType = "TAKER"

	PriceTypeBestBidOfferCounterParty1 PriceType = "COUNTERPARTY1"
	PriceTypeBestBidOfferCounterParty5 PriceType = "COUNTERPARTY5"

	PriceTypeBestBidOfferQueue1 PriceType = "QUEUE1"
	PriceTypeBestBidOfferQueue5 PriceType = "QUEUE5"
)

func ParsePriceType added in v1.58.0

func ParsePriceType(s string) (p PriceType, err error)

func (PriceType) GetPrice added in v1.60.0

func (p PriceType) GetPrice(ticker *Ticker, side SideType) fixedpoint.Value

GetPrice returns the price from the given ticker based on the price type

func (*PriceType) UnmarshalJSON added in v1.57.0

func (p *PriceType) UnmarshalJSON(data []byte) error

type PriceVolume

type PriceVolume struct {
	Price, Volume fixedpoint.Value
}

func (PriceVolume) Equals added in v1.51.0

func (p PriceVolume) Equals(b PriceVolume) bool

func (PriceVolume) InQuote added in v1.58.0

func (p PriceVolume) InQuote() fixedpoint.Value

func (PriceVolume) String

func (p PriceVolume) String() string

type PriceVolumeSlice

type PriceVolumeSlice []PriceVolume

func ParsePriceVolumeKvSliceJSON added in v1.60.0

func ParsePriceVolumeKvSliceJSON(b []byte) (PriceVolumeSlice, error)

ParsePriceVolumeKvSliceJSON parses a JSON array of objects into PriceVolumeSlice [{"Price":...,"Volume":...}, ...]

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"], ... ]

if parse failed, then it will try to parse the JSON array of objects, function ParsePriceVolumeKvSliceJSON will be called.

func (PriceVolumeSlice) AverageDepthPrice added in v1.60.0

func (slice PriceVolumeSlice) AverageDepthPrice(requiredQuantity fixedpoint.Value) fixedpoint.Value

AverageDepthPrice uses the required total quantity to calculate the corresponding price

func (PriceVolumeSlice) AverageDepthPriceByQuote added in v1.60.0

func (slice PriceVolumeSlice) AverageDepthPriceByQuote(requiredDepthInQuote fixedpoint.Value, maxLevel int) fixedpoint.Value

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) IndexByQuoteVolumeDepth added in v1.55.0

func (slice PriceVolumeSlice) IndexByQuoteVolumeDepth(requiredQuoteVolume fixedpoint.Value) int

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) SumDepth added in v1.55.0

func (slice PriceVolumeSlice) SumDepth() fixedpoint.Value

func (PriceVolumeSlice) SumDepthInQuote added in v1.55.0

func (slice PriceVolumeSlice) SumDepthInQuote() fixedpoint.Value

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 PrivateChannelSetter added in v1.53.0

type PrivateChannelSetter interface {
	SetPrivateChannels(channels []string)
}

type PrivateChannelSymbolSetter added in v1.54.0

type PrivateChannelSymbolSetter interface {
	SetPrivateChannelSymbols(symbols []string)
}

type Profit added in v1.28.0

type Profit struct {
	// --- position related fields
	// -------------------------------------------
	// Symbol is the symbol of the position
	Symbol        string           `json:"symbol"`
	QuoteCurrency string           `json:"quoteCurrency" db:"quote_currency"`
	BaseCurrency  string           `json:"baseCurrency" db:"base_currency"`
	AverageCost   fixedpoint.Value `json:"averageCost" db:"average_cost"`

	// profit related fields
	// -------------------------------------------
	// Profit is the profit of this trade made. negative profit means loss.
	Profit fixedpoint.Value `json:"profit" db:"profit"`

	// NetProfit is (profit - trading fee)
	NetProfit fixedpoint.Value `json:"netProfit" db:"net_profit"`

	// ProfitMargin is a percentage of the profit and the capital amount
	ProfitMargin fixedpoint.Value `json:"profitMargin" db:"profit_margin"`

	// NetProfitMargin is a percentage of the net profit and the capital amount
	NetProfitMargin fixedpoint.Value `json:"netProfitMargin" db:"net_profit_margin"`

	// trade related fields
	// --------------------------------------------
	// TradeID is the exchange trade id of that trade
	Trade         *Trade           `json:"trade,omitempty" db:"-"`
	TradeID       uint64           `json:"tradeID" db:"trade_id"`
	OrderID       uint64           `json:"orderID,omitempty"`
	Side          SideType         `json:"side" db:"side"`
	IsBuyer       bool             `json:"isBuyer" db:"is_buyer"`
	IsMaker       bool             `json:"isMaker" db:"is_maker"`
	Price         fixedpoint.Value `json:"price" db:"price"`
	Quantity      fixedpoint.Value `json:"quantity" db:"quantity"`
	QuoteQuantity fixedpoint.Value `json:"quoteQuantity" db:"quote_quantity"`

	// FeeInUSD is the summed fee of this profit,
	// you will need to convert the trade fee into USD since the fee currencies can be different.
	FeeInUSD    fixedpoint.Value `json:"feeInUSD" db:"fee_in_usd"`
	Fee         fixedpoint.Value `json:"fee" db:"fee"`
	FeeCurrency string           `json:"feeCurrency" db:"fee_currency"`
	Exchange    ExchangeName     `json:"exchange" db:"exchange"`
	IsMargin    bool             `json:"isMargin" db:"is_margin"`
	IsFutures   bool             `json:"isFutures" db:"is_futures"`
	IsIsolated  bool             `json:"isIsolated" db:"is_isolated"`
	TradedAt    time.Time        `json:"tradedAt" db:"traded_at"`

	PositionOpenedAt time.Time `json:"positionOpenedAt" db:"-"`

	// strategy related fields
	Strategy           string `json:"strategy" db:"strategy"`
	StrategyInstanceID string `json:"strategyInstanceID" db:"strategy_instance_id"`
}

Profit struct stores the PnL information

func (*Profit) PlainText added in v1.28.0

func (p *Profit) PlainText() string

func (*Profit) SlackAttachment added in v1.28.0

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

type ProfitReport added in v1.39.0

type ProfitReport struct {
	StartTime time.Time `json:"startTime"`
	Profit    float64   `json:"profit"`
	Interval  Interval  `json:"interval"`
}

func (ProfitReport) String added in v1.39.0

func (s ProfitReport) String() string

type ProfitStats added in v1.28.0

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

	AccumulatedPnL         fixedpoint.Value `json:"accumulatedPnL,omitempty"`
	AccumulatedNetProfit   fixedpoint.Value `json:"accumulatedNetProfit,omitempty"`
	AccumulatedGrossProfit fixedpoint.Value `json:"accumulatedGrossProfit,omitempty"`
	AccumulatedGrossLoss   fixedpoint.Value `json:"accumulatedGrossLoss,omitempty"`
	AccumulatedVolume      fixedpoint.Value `json:"accumulatedVolume,omitempty"`
	AccumulatedSince       int64            `json:"accumulatedSince,omitempty"`

	TodayPnL         fixedpoint.Value `json:"todayPnL,omitempty"`
	TodayNetProfit   fixedpoint.Value `json:"todayNetProfit,omitempty"`
	TodayGrossProfit fixedpoint.Value `json:"todayGrossProfit,omitempty"`
	TodayGrossLoss   fixedpoint.Value `json:"todayGrossLoss,omitempty"`
	TodaySince       int64            `json:"todaySince,omitempty"`
}

func NewProfitStats added in v1.33.0

func NewProfitStats(market Market) *ProfitStats

func (*ProfitStats) AddProfit added in v1.28.0

func (s *ProfitStats) AddProfit(profit Profit)

func (*ProfitStats) AddTrade added in v1.28.0

func (s *ProfitStats) AddTrade(trade Trade)

func (*ProfitStats) Init added in v1.28.0

func (s *ProfitStats) Init(market Market)

Init Deprecated: use NewProfitStats instead

func (*ProfitStats) IsOver24Hours added in v1.28.0

func (s *ProfitStats) IsOver24Hours() bool

IsOver24Hours checks if the since time is over 24 hours

func (*ProfitStats) PlainText added in v1.28.0

func (s *ProfitStats) PlainText() string

func (*ProfitStats) ResetToday added in v1.28.0

func (s *ProfitStats) ResetToday(t time.Time)

func (*ProfitStats) SlackAttachment added in v1.28.0

func (s *ProfitStats) SlackAttachment() slack.Attachment

type Queue added in v1.33.1

type Queue struct {
	SeriesBase
	// contains filtered or unexported fields
}

Super basic Series type that simply holds the float64 data with size limit (the only difference compare to float64slice)

func NewQueue added in v1.33.1

func NewQueue(size int) *Queue

func (*Queue) Clone added in v1.38.0

func (inc *Queue) Clone() *Queue

func (*Queue) Index added in v1.33.1

func (inc *Queue) Index(i int) float64

func (*Queue) Last added in v1.33.1

func (inc *Queue) Last(i int) float64

func (*Queue) Length added in v1.33.1

func (inc *Queue) Length() int

func (*Queue) Update added in v1.33.1

func (inc *Queue) Update(v float64)

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

func NewNil added in v1.39.0

func NewNil() *RBNode

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) LastUpdateTime added in v1.25.4

func (b *RBTOrderBook) LastUpdateTime() time.Time

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) 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"`
	CreatedAt Time             `json:"created_at" db:"created_at"`
}

func (Reward) String added in v1.36.0

func (r Reward) String() (s string)

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 RollingResult added in v1.36.0

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

func Rolling added in v1.36.0

func Rolling(a Series, window int) *RollingResult

func (*RollingResult) Index added in v1.36.0

func (r *RollingResult) Index(i int) SeriesExtend

func (*RollingResult) Last added in v1.36.0

func (r *RollingResult) Last() SeriesExtend

func (*RollingResult) Length added in v1.36.0

func (r *RollingResult) Length() int

type Series added in v1.30.2

type Series interface {
	Last(i int) float64
	Index(i int) float64
	Length() int
}

The interface maps to pinescript basic type `series` Access the internal historical data from the latest to the oldest Index(0) always maps to Last()

type SeriesBase added in v1.36.0

type SeriesBase struct {
	Series
}

SeriesBase is a wrapper of the Series interface You can assign a data container that implements the Series interface And this SeriesBase struct provides the implemented methods for manipulating your data

func (*SeriesBase) Abs added in v1.36.0

func (s *SeriesBase) Abs() SeriesExtend

func (*SeriesBase) Add added in v1.36.0

func (s *SeriesBase) Add(b interface{}) SeriesExtend

func (*SeriesBase) Array added in v1.36.0

func (s *SeriesBase) Array(limit ...int) []float64

func (*SeriesBase) AutoCorrelation added in v1.38.0

func (s *SeriesBase) AutoCorrelation(length int, lag ...int) float64

func (*SeriesBase) Change added in v1.36.0

func (s *SeriesBase) Change(offset ...int) SeriesExtend

func (*SeriesBase) Correlation added in v1.36.0

func (s *SeriesBase) Correlation(b Series, length int, method ...CorrFunc) float64

func (*SeriesBase) Covariance added in v1.36.0

func (s *SeriesBase) Covariance(b Series, length int) float64

func (*SeriesBase) CrossEntropy added in v1.37.0

func (s *SeriesBase) CrossEntropy(b Series, window int) float64

func (*SeriesBase) CrossOver added in v1.36.0

func (s *SeriesBase) CrossOver(b Series) BoolSeries

func (*SeriesBase) CrossUnder added in v1.36.0

func (s *SeriesBase) CrossUnder(b Series) BoolSeries

func (*SeriesBase) Div added in v1.36.0

func (s *SeriesBase) Div(b interface{}) SeriesExtend

func (*SeriesBase) Dot added in v1.36.0

func (s *SeriesBase) Dot(b interface{}, limit ...int) float64

func (*SeriesBase) Entropy added in v1.37.0

func (s *SeriesBase) Entropy(window int) float64

func (*SeriesBase) Filter added in v1.42.0

func (s *SeriesBase) Filter(b func(int, float64) bool, length int) SeriesExtend

func (*SeriesBase) Highest added in v1.36.0

func (s *SeriesBase) Highest(lookback int) float64

func (*SeriesBase) Index added in v1.36.0

func (s *SeriesBase) Index(i int) float64

func (*SeriesBase) Last added in v1.36.0

func (s *SeriesBase) Last(i int) float64

func (*SeriesBase) Length added in v1.36.0

func (s *SeriesBase) Length() int

func (*SeriesBase) Lowest added in v1.36.0

func (s *SeriesBase) Lowest(lookback int) float64

func (*SeriesBase) Mean added in v1.36.0

func (s *SeriesBase) Mean(limit ...int) float64

func (*SeriesBase) Minus added in v1.36.0

func (s *SeriesBase) Minus(b interface{}) SeriesExtend

func (*SeriesBase) Mul added in v1.36.0

func (s *SeriesBase) Mul(b interface{}) SeriesExtend

func (*SeriesBase) NextCross added in v1.36.0

func (s *SeriesBase) NextCross(b Series, lookback int) (int, float64, bool)

func (*SeriesBase) PercentageChange added in v1.36.0

func (s *SeriesBase) PercentageChange(offset ...int) SeriesExtend

func (*SeriesBase) Predict added in v1.36.0

func (s *SeriesBase) Predict(lookback int, offset ...int) float64

func (*SeriesBase) Rank added in v1.36.0

func (s *SeriesBase) Rank(length int) SeriesExtend

func (*SeriesBase) Reverse added in v1.36.0

func (s *SeriesBase) Reverse(limit ...int) floats.Slice

func (*SeriesBase) Rolling added in v1.36.0

func (s *SeriesBase) Rolling(window int) *RollingResult

func (*SeriesBase) Shift added in v1.36.0

func (s *SeriesBase) Shift(offset int) SeriesExtend

func (*SeriesBase) Sigmoid added in v1.37.0

func (s *SeriesBase) Sigmoid() SeriesExtend

func (*SeriesBase) Skew added in v1.36.0

func (s *SeriesBase) Skew(length int) float64

func (*SeriesBase) Softmax added in v1.37.0

func (s *SeriesBase) Softmax(window int) SeriesExtend

func (*SeriesBase) Stdev added in v1.36.0

func (s *SeriesBase) Stdev(params ...int) float64

func (*SeriesBase) Sum added in v1.36.0

func (s *SeriesBase) Sum(limit ...int) float64

func (*SeriesBase) Variance added in v1.36.0

func (s *SeriesBase) Variance(length int) float64

type SeriesExtend added in v1.36.0

type SeriesExtend interface {
	Series
	Sum(limit ...int) float64
	Mean(limit ...int) float64
	Abs() SeriesExtend
	Predict(lookback int, offset ...int) float64
	NextCross(b Series, lookback int) (int, float64, bool)
	CrossOver(b Series) BoolSeries
	CrossUnder(b Series) BoolSeries
	Highest(lookback int) float64
	Lowest(lookback int) float64
	Add(b interface{}) SeriesExtend
	Minus(b interface{}) SeriesExtend
	Div(b interface{}) SeriesExtend
	Mul(b interface{}) SeriesExtend
	Dot(b interface{}, limit ...int) float64
	Array(limit ...int) (result []float64)
	Reverse(limit ...int) (result floats.Slice)
	Change(offset ...int) SeriesExtend
	PercentageChange(offset ...int) SeriesExtend
	Stdev(params ...int) float64
	Rolling(window int) *RollingResult
	Shift(offset int) SeriesExtend
	Skew(length int) float64
	Variance(length int) float64
	Covariance(b Series, length int) float64
	Correlation(b Series, length int, method ...CorrFunc) float64
	AutoCorrelation(length int, lag ...int) float64
	Rank(length int) SeriesExtend
	Sigmoid() SeriesExtend
	Softmax(window int) SeriesExtend
	Entropy(window int) float64
	CrossEntropy(b Series, window int) float64
	Filter(b func(i int, value float64) bool, length int) SeriesExtend
}

func Abs added in v1.30.2

func Abs(a Series) SeriesExtend

Return series that having all the elements positive

func Add added in v1.30.2

func Add(a interface{}, b interface{}) SeriesExtend

Add two series, result[i] = a[i] + b[i]

func Change added in v1.30.2

func Change(a Series, offset ...int) SeriesExtend

Difference between current value and previous, a - a[offset] offset: if not given, offset is 1.

func Div added in v1.30.2

func Div(a interface{}, b interface{}) SeriesExtend

Divid two series, result[i] = a[i] / b[i]

func Filter added in v1.42.0

func Filter(a Series, b func(i int, value float64) bool, length int) SeriesExtend

Filter function filters Series by using a boolean function. When the boolean function returns true, the Series value at index i will be included in the returned Series. The returned Series will find at most `length` latest matching elements from the input Series. Query index larger or equal than length from the returned Series will return 0 instead. Notice that any Update on the input Series will make the previously returned Series outdated.

func Mul added in v1.30.2

func Mul(a interface{}, b interface{}) SeriesExtend

Multiple two series, result[i] = a[i] * b[i]

func NewSeries added in v1.36.0

func NewSeries(a Series) SeriesExtend

func PercentageChange added in v1.36.0

func PercentageChange(a Series, offset ...int) SeriesExtend

Percentage change between current and a prior element, a / a[offset] - 1. offset: if not give, offset is 1.

func Rank added in v1.36.0

func Rank(a Series, length int) SeriesExtend

func Shift added in v1.36.0

func Shift(a Series, offset int) SeriesExtend

func Sigmoid added in v1.37.0

func Sigmoid(a Series) SeriesExtend

Sigmoid returns the input values in range of -1 to 1 along the sigmoid or s-shaped curve. Commonly used in machine learning while training neural networks as an activation function.

func Softmax added in v1.37.0

func Softmax(a Series, window int) SeriesExtend

SoftMax returns the input value in the range of 0 to 1 with sum of all the probabilities being equal to one. It is commonly used in machine learning neural networks. Will return Softmax SeriesExtend result based in latest [window] numbers from [a] Series

func Sub added in v1.48.0

func Sub(a interface{}, b interface{}) SeriesExtend

Sub two series, result[i] = a[i] - b[i]

type ShiftResult added in v1.36.0

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

func (*ShiftResult) Index added in v1.36.0

func (inc *ShiftResult) Index(i int) float64

func (*ShiftResult) Last added in v1.36.0

func (inc *ShiftResult) Last(i int) float64

func (*ShiftResult) Length added in v1.36.0

func (inc *ShiftResult) Length() int

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 SigmoidResult added in v1.37.0

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

func (*SigmoidResult) Index added in v1.37.0

func (s *SigmoidResult) Index(i int) float64

func (*SigmoidResult) Last added in v1.37.0

func (s *SigmoidResult) Last(i int) float64

func (*SigmoidResult) Length added in v1.37.0

func (s *SigmoidResult) Length() int

type SimpleDuration added in v1.44.0

type SimpleDuration struct {
	Num      int
	Unit     string
	Duration Duration
}

func ParseSimpleDuration added in v1.44.0

func ParseSimpleDuration(s string) (*SimpleDuration, error)

func (*SimpleDuration) Interval added in v1.44.0

func (d *SimpleDuration) Interval() Interval

func (*SimpleDuration) String added in v1.44.0

func (d *SimpleDuration) String() string

func (*SimpleDuration) UnmarshalJSON added in v1.44.0

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

type SlackAttachmentCreator added in v1.51.0

type SlackAttachmentCreator interface {
	SlackAttachment() slack.Attachment
}

type SliceOrderBook added in v1.17.0

type SliceOrderBook struct {
	Symbol string
	Bids   PriceVolumeSlice
	Asks   PriceVolumeSlice
	// Time represents the server time. If empty, it indicates that the server does not provide this information.
	Time time.Time

	// LastUpdateId is the message id from the server
	// this field is optional, not every exchange provides this information
	// this is for binance right now.
	LastUpdateId int64
	// 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) LastUpdateTime added in v1.25.4

func (b *SliceOrderBook) LastUpdateTime() time.Time

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 SliceView added in v1.36.0

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

func (*SliceView) Index added in v1.36.0

func (s *SliceView) Index(i int) float64

func (*SliceView) Last added in v1.36.0

func (s *SliceView) Last(i int) float64

func (*SliceView) Length added in v1.36.0

func (s *SliceView) Length() int

type Speed added in v1.25.4

type Speed string
const (
	SpeedHigh   Speed = "HIGH"
	SpeedMedium Speed = "MEDIUM"
	SpeedLow    Speed = "LOW"
)

type StandardStream

type StandardStream struct {

	// Conn is the websocket connection
	Conn *websocket.Conn

	// ConnCtx is the context of the current websocket connection
	ConnCtx context.Context

	// ConnCancel is the cancel funcion of the current websocket connection
	ConnCancel context.CancelFunc

	// ConnLock is used for locking Conn, ConnCtx and ConnCancel fields.
	// When changing these field values, be sure to call ConnLock
	ConnLock sync.Mutex

	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 NewStandardStream added in v1.23.0

func NewStandardStream() StandardStream

func (*StandardStream) Close added in v1.23.0

func (s *StandardStream) Close() error

func (*StandardStream) Connect added in v1.23.0

func (s *StandardStream) Connect(ctx context.Context) error

Connect starts the stream and create the websocket connection

func (*StandardStream) Dial added in v1.17.0

func (s *StandardStream) Dial(ctx context.Context, args ...string) (*websocket.Conn, error)

func (*StandardStream) DialAndConnect added in v1.23.0

func (s *StandardStream) DialAndConnect(ctx context.Context) error

func (*StandardStream) EmitAggTrade added in v1.43.0

func (s *StandardStream) EmitAggTrade(trade Trade)

func (*StandardStream) EmitAuth added in v1.52.0

func (s *StandardStream) EmitAuth()

func (*StandardStream) EmitBalanceSnapshot

func (s *StandardStream) EmitBalanceSnapshot(balances BalanceMap)

func (*StandardStream) EmitBalanceUpdate

func (s *StandardStream) EmitBalanceUpdate(balances BalanceMap)

func (*StandardStream) EmitBookSnapshot

func (s *StandardStream) EmitBookSnapshot(book SliceOrderBook)

func (*StandardStream) EmitBookTickerUpdate added in v1.21.0

func (s *StandardStream) EmitBookTickerUpdate(bookTicker BookTicker)

func (*StandardStream) EmitBookUpdate

func (s *StandardStream) EmitBookUpdate(book SliceOrderBook)

func (*StandardStream) EmitConnect

func (s *StandardStream) EmitConnect()

func (*StandardStream) EmitDisconnect added in v1.14.0

func (s *StandardStream) EmitDisconnect()

func (*StandardStream) EmitForceOrder added in v1.53.0

func (s *StandardStream) EmitForceOrder(info LiquidationInfo)

func (*StandardStream) EmitFuturesPositionSnapshot added in v1.22.0

func (s *StandardStream) EmitFuturesPositionSnapshot(futuresPositions FuturesPositionMap)

func (*StandardStream) EmitFuturesPositionUpdate added in v1.22.0

func (s *StandardStream) EmitFuturesPositionUpdate(futuresPositions FuturesPositionMap)

func (*StandardStream) EmitKLine

func (s *StandardStream) EmitKLine(kline KLine)

func (*StandardStream) EmitKLineClosed

func (s *StandardStream) EmitKLineClosed(kline KLine)

func (*StandardStream) EmitMarketTrade added in v1.29.0

func (s *StandardStream) EmitMarketTrade(trade Trade)

func (*StandardStream) EmitOrderUpdate

func (s *StandardStream) EmitOrderUpdate(order Order)

func (*StandardStream) EmitRawMessage added in v1.52.0

func (s *StandardStream) EmitRawMessage(raw []byte)

func (*StandardStream) EmitStart added in v1.14.0

func (s *StandardStream) EmitStart()

func (*StandardStream) EmitTradeUpdate

func (s *StandardStream) EmitTradeUpdate(trade Trade)

func (*StandardStream) GetPublicOnly added in v1.35.0

func (s *StandardStream) GetPublicOnly() bool

func (*StandardStream) GetSubscriptions added in v1.35.0

func (s *StandardStream) GetSubscriptions() []Subscription

func (*StandardStream) OnAggTrade added in v1.43.0

func (s *StandardStream) OnAggTrade(cb func(trade Trade))

func (*StandardStream) OnAuth added in v1.52.0

func (s *StandardStream) OnAuth(cb func())

func (*StandardStream) OnBalanceSnapshot

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

func (*StandardStream) OnBalanceUpdate

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

func (*StandardStream) OnBookSnapshot

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

func (*StandardStream) OnBookTickerUpdate added in v1.21.0

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

func (*StandardStream) OnBookUpdate

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

func (*StandardStream) OnConnect

func (s *StandardStream) OnConnect(cb func())

func (*StandardStream) OnDisconnect added in v1.14.0

func (s *StandardStream) OnDisconnect(cb func())

func (*StandardStream) OnForceOrder added in v1.53.0

func (s *StandardStream) OnForceOrder(cb func(info LiquidationInfo))

func (*StandardStream) OnFuturesPositionSnapshot added in v1.22.0

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

func (*StandardStream) OnFuturesPositionUpdate added in v1.22.0

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

func (*StandardStream) OnKLine

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

func (*StandardStream) OnKLineClosed

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

func (*StandardStream) OnMarketTrade added in v1.29.0

func (s *StandardStream) OnMarketTrade(cb func(trade Trade))

func (*StandardStream) OnOrderUpdate

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

func (*StandardStream) OnRawMessage added in v1.52.0

func (s *StandardStream) OnRawMessage(cb func(raw []byte))

func (*StandardStream) OnStart added in v1.14.0

func (s *StandardStream) OnStart(cb func())

func (*StandardStream) OnTradeUpdate

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

func (*StandardStream) Read added in v1.23.0

func (s *StandardStream) Read(ctx context.Context, conn *websocket.Conn, cancel context.CancelFunc)

func (*StandardStream) Reconnect added in v1.17.0

func (s *StandardStream) Reconnect()

func (*StandardStream) Resubscribe added in v1.52.0

func (s *StandardStream) Resubscribe(fn func(old []Subscription) (new []Subscription, err error)) error

Resubscribe synchronizes the new subscriptions based on the provided function. The fn function takes the old subscriptions as input and returns the new subscriptions that will replace the old ones in the struct then Reconnect. This method is thread-safe.

func (*StandardStream) SetBeforeConnect added in v1.52.0

func (s *StandardStream) SetBeforeConnect(fn BeforeConnect)

SetBeforeConnect sets the custom hook function before connect

func (*StandardStream) SetConn added in v1.23.0

func (*StandardStream) SetDispatcher added in v1.23.0

func (s *StandardStream) SetDispatcher(dispatcher Dispatcher)

func (*StandardStream) SetEndpointCreator added in v1.23.0

func (s *StandardStream) SetEndpointCreator(creator EndpointCreator)

func (*StandardStream) SetHeartBeat added in v1.52.0

func (s *StandardStream) SetHeartBeat(fn HeartBeat)

SetHeartBeat sets the custom heart beat implementation if needed

func (*StandardStream) SetParser added in v1.23.0

func (s *StandardStream) SetParser(parser Parser)

func (*StandardStream) SetPingInterval added in v1.56.0

func (s *StandardStream) SetPingInterval(interval time.Duration)

func (*StandardStream) SetPublicOnly added in v1.21.0

func (s *StandardStream) SetPublicOnly()

func (*StandardStream) Subscribe

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

type StandardStreamEmitter added in v1.35.0

type StandardStreamEmitter interface {
	Stream
	EmitStart()
	EmitConnect()
	EmitDisconnect()
	EmitAuth()
	EmitTradeUpdate(Trade)
	EmitOrderUpdate(Order)
	EmitBalanceSnapshot(BalanceMap)
	EmitBalanceUpdate(BalanceMap)
	EmitKLineClosed(KLine)
	EmitKLine(KLine)
	EmitBookUpdate(SliceOrderBook)
	EmitBookTickerUpdate(BookTicker)
	EmitBookSnapshot(SliceOrderBook)
	EmitMarketTrade(Trade)
	EmitAggTrade(Trade)
	EmitForceOrder(LiquidationInfo)
	EmitFuturesPositionUpdate(FuturesPositionMap)
	EmitFuturesPositionSnapshot(FuturesPositionMap)
}

type StandardStreamEventHub

type StandardStreamEventHub interface {
	OnStart(cb func())

	OnConnect(cb func())

	OnDisconnect(cb func())

	OnAuth(cb func())

	OnRawMessage(cb func(raw []byte))

	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))

	OnMarketTrade(cb func(trade Trade))

	OnAggTrade(cb func(trade Trade))

	OnForceOrder(cb func(info LiquidationInfo))

	OnFuturesPositionUpdate(cb func(futuresPositions FuturesPositionMap))

	OnFuturesPositionSnapshot(cb func(futuresPositions FuturesPositionMap))
}

type StrInt64 added in v1.48.0

type StrInt64 int64

func (*StrInt64) MarshalJSON added in v1.48.0

func (s *StrInt64) MarshalJSON() ([]byte, error)

func (*StrInt64) String added in v1.54.0

func (s *StrInt64) String() string

func (*StrInt64) UnmarshalJSON added in v1.48.0

func (s *StrInt64) UnmarshalJSON(body []byte) error

type StrategyStatus added in v1.29.0

type StrategyStatus string

StrategyStatus define strategy status

const (
	StrategyStatusRunning StrategyStatus = "RUNNING"
	StrategyStatusStopped StrategyStatus = "STOPPED"
	StrategyStatusUnknown StrategyStatus = "UNKNOWN"
)

type Stream

type Stream interface {
	StandardStreamEventHub

	// Subscribe subscribes the specific channel, but not connect to the server.
	Subscribe(channel Channel, symbol string, options SubscribeOptions)
	GetSubscriptions() []Subscription
	// Resubscribe used to update or renew existing subscriptions. It will reconnect to the server.
	Resubscribe(func(oldSubs []Subscription) (newSubs []Subscription, err error)) error
	// SetPublicOnly connects to public or private
	SetPublicOnly()
	GetPublicOnly() bool

	// Connect connects to websocket server
	Connect(ctx context.Context) error
	Reconnect()
	Close() error
}

type StreamOrderBook

type StreamOrderBook struct {
	*MutexOrderBook

	C chan *BookSignal
	// contains filtered or unexported fields
}

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, exchangeName ExchangeName) *StreamOrderBook

func (*StreamOrderBook) BindStream

func (sb *StreamOrderBook) BindStream(stream Stream)

func (*StreamOrderBook) EmitSnapshot added in v1.39.0

func (sb *StreamOrderBook) EmitSnapshot(snapshot SliceOrderBook)

func (*StreamOrderBook) EmitUpdate added in v1.39.0

func (sb *StreamOrderBook) EmitUpdate(update SliceOrderBook)

func (*StreamOrderBook) OnSnapshot added in v1.39.0

func (sb *StreamOrderBook) OnSnapshot(cb func(snapshot SliceOrderBook))

func (*StreamOrderBook) OnUpdate added in v1.39.0

func (sb *StreamOrderBook) OnUpdate(cb func(update SliceOrderBook))

type Stringer added in v1.16.0

type Stringer interface {
	String() string
}

type SubmitOrder

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

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

	Quantity fixedpoint.Value `json:"quantity" db:"quantity"`
	Price    fixedpoint.Value `json:"price" db:"price"`

	// AveragePrice is only used in back-test currently
	AveragePrice fixedpoint.Value `json:"averagePrice,omitempty"`

	StopPrice fixedpoint.Value `json:"stopPrice,omitempty" db:"stop_price"`

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

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

	GroupID uint32 `json:"groupID,omitempty"`

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

	ReduceOnly    bool `json:"reduceOnly,omitempty" db:"reduce_only"`
	ClosePosition bool `json:"closePosition,omitempty" db:"close_position"`

	Tag string `json:"tag,omitempty" db:"-"`
}

func (*SubmitOrder) In added in v1.39.0

func (o *SubmitOrder) In() (fixedpoint.Value, string)

func (*SubmitOrder) Out added in v1.39.0

func (o *SubmitOrder) Out() (fixedpoint.Value, string)

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 {
	// TODO: change to Interval type later
	Interval Interval `json:"interval,omitempty"`
	Depth    Depth    `json:"depth,omitempty"`
	Speed    Speed    `json:"speed,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 SyncGroup added in v1.52.0

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

SyncGroup is essentially a wrapper around sync.WaitGroup, designed for ease of use. You only need to use Add() to add routines and Run() to execute them. When it's time to close or reset, you just need to call WaitAndClear(), which takes care of waiting for all the routines to complete before clearing routine.

It eliminates the need for manual management of sync.WaitGroup. Specifically, it highlights that SyncGroup takes care of sync.WaitGroup.Add() and sync.WaitGroup.Done() automatically, reducing the chances of missing these crucial calls.

func NewSyncGroup added in v1.52.0

func NewSyncGroup() SyncGroup

func (*SyncGroup) Add added in v1.52.0

func (w *SyncGroup) Add(fn syncGroupFunc)

func (*SyncGroup) Run added in v1.52.0

func (w *SyncGroup) Run()

func (*SyncGroup) WaitAndClear added in v1.52.0

func (w *SyncGroup) WaitAndClear()

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) Get added in v1.44.0

func (m *SyncOrderMap) Get(orderID uint64) (Order, bool)

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) Lookup added in v1.43.0

func (m *SyncOrderMap) Lookup(f func(o Order) bool) *Order

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 fixedpoint.Value // `volume` from Max & binance
	Last   fixedpoint.Value // `last` from Max, `lastPrice` from binance
	Open   fixedpoint.Value // `open` from Max, `openPrice` from binance
	High   fixedpoint.Value // `high` from Max, `highPrice` from binance
	Low    fixedpoint.Value // `low` from Max, `lowPrice` from binance
	Buy    fixedpoint.Value // `buy` from Max, `bidPrice` from binance
	Sell   fixedpoint.Value // `sell` from Max, `askPrice` from binance
}

func (*Ticker) String added in v1.52.0

func (t *Ticker) String() string

type Time added in v1.17.0

type Time time.Time

Time type implements the driver value for sqlite

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) Equal added in v1.36.0

func (t Time) Equal(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) UnixMilli added in v1.30.1

func (t Time) UnixMilli() 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 TimeInForce added in v1.28.0

type TimeInForce string
var (
	TimeInForceGTC TimeInForce = "GTC"
	TimeInForceIOC TimeInForce = "IOC"
	TimeInForceFOK TimeInForce = "FOK"
)

type Timestamp added in v1.31.0

type Timestamp time.Time

Timestamp is used for parsing unix timestamp (seconds)

func (Timestamp) Format added in v1.31.0

func (t Timestamp) Format(layout string) string

func (Timestamp) MarshalJSON added in v1.31.0

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

func (Timestamp) String added in v1.31.0

func (t Timestamp) String() string

func (Timestamp) Time added in v1.31.0

func (t Timestamp) Time() time.Time

func (*Timestamp) UnmarshalJSON added in v1.31.0

func (t *Timestamp) UnmarshalJSON(o []byte) error

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         fixedpoint.Value `json:"price" db:"price"`
	Quantity      fixedpoint.Value `json:"quantity" db:"quantity"`
	QuoteQuantity fixedpoint.Value `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           fixedpoint.Value `json:"fee" db:"fee"`
	FeeCurrency   string           `json:"feeCurrency" db:"fee_currency"`
	FeeProcessing bool             `json:"feeProcessing" db:"-"`

	// FeeDiscounted is an optional field which indicates whether the trade is using the platform fee token for discount.
	// When FeeDiscounted = true, means the fee is deducted outside the trade
	// By default, it's set to false.
	// This is only used by the MAX exchange
	FeeDiscounted bool `json:"feeDiscounted" db:"-"`

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

	// StrategyID is the strategy that execute this trade
	StrategyID sql.NullString `json:"strategyID" db:"strategy"`

	// PnL is the profit and loss value of the executed trade
	PnL sql.NullFloat64 `json:"pnl" db:"pnl"`

	InsertedAt *Time `json:"insertedAt" db:"inserted_at"`
}

func SortTradesAscending added in v1.30.1

func SortTradesAscending(trades []Trade) []Trade

func (Trade) CsvHeader added in v1.33.0

func (trade Trade) CsvHeader() []string

func (Trade) CsvRecords added in v1.33.0

func (trade Trade) CsvRecords() [][]string

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

PositionChange returns the position delta of this trade BUY trade -> positive quantity SELL trade -> negative quantity

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 {
	Exchange ExchangeName
	ID       uint64
	Side     SideType
}

func (TradeKey) String added in v1.33.0

func (k TradeKey) String() string

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()

func (*TradeSlice) Truncate added in v1.54.0

func (s *TradeSlice) Truncate(size int)

type TradeStats added in v1.36.0

type TradeStats struct {
	Symbol string `json:"symbol,omitempty"`

	WinningRatio     fixedpoint.Value `json:"winningRatio" yaml:"winningRatio"`
	NumOfLossTrade   int              `json:"numOfLossTrade" yaml:"numOfLossTrade"`
	NumOfProfitTrade int              `json:"numOfProfitTrade" yaml:"numOfProfitTrade"`

	GrossProfit fixedpoint.Value `json:"grossProfit" yaml:"grossProfit"`
	GrossLoss   fixedpoint.Value `json:"grossLoss" yaml:"grossLoss"`

	Profits []fixedpoint.Value `json:"profits,omitempty" yaml:"profits,omitempty"`
	Losses  []fixedpoint.Value `json:"losses,omitempty" yaml:"losses,omitempty"`

	LargestProfitTrade fixedpoint.Value `json:"largestProfitTrade,omitempty" yaml:"largestProfitTrade"`
	LargestLossTrade   fixedpoint.Value `json:"largestLossTrade,omitempty" yaml:"largestLossTrade"`
	AverageProfitTrade fixedpoint.Value `json:"averageProfitTrade" yaml:"averageProfitTrade"`
	AverageLossTrade   fixedpoint.Value `json:"averageLossTrade" yaml:"averageLossTrade"`

	ProfitFactor    fixedpoint.Value                      `json:"profitFactor" yaml:"profitFactor"`
	TotalNetProfit  fixedpoint.Value                      `json:"totalNetProfit" yaml:"totalNetProfit"`
	IntervalProfits map[Interval]*IntervalProfitCollector `json:"intervalProfits,omitempty" yaml:"intervalProfits,omitempty"`

	// MaximumConsecutiveWins - (counter) the longest series of winning trades
	MaximumConsecutiveWins int `json:"maximumConsecutiveWins" yaml:"maximumConsecutiveWins"`

	// MaximumConsecutiveLosses - (counter) the longest series of losing trades
	MaximumConsecutiveLosses int `json:"maximumConsecutiveLosses" yaml:"maximumConsecutiveLosses"`

	// MaximumConsecutiveProfit - ($) the longest series of winning trades and their total profit;
	MaximumConsecutiveProfit fixedpoint.Value `json:"maximumConsecutiveProfit" yaml:"maximumConsecutiveProfit"`

	// MaximumConsecutiveLoss - ($) the longest series of losing trades and their total loss;
	MaximumConsecutiveLoss fixedpoint.Value `json:"maximumConsecutiveLoss" yaml:"maximumConsecutiveLoss"`
	// contains filtered or unexported fields
}

TODO: Add more stats from the reference: See https://www.metatrader5.com/en/terminal/help/algotrading/testing_report

func NewTradeStats added in v1.36.0

func NewTradeStats(symbol string) *TradeStats

func (*TradeStats) Add added in v1.36.0

func (s *TradeStats) Add(profit *Profit)

func (*TradeStats) BriefString added in v1.38.0

func (s *TradeStats) BriefString() string

Output TradeStats without Profits and Losses

func (*TradeStats) CsvHeader added in v1.40.0

func (s *TradeStats) CsvHeader() []string

func (*TradeStats) CsvRecords added in v1.40.0

func (s *TradeStats) CsvRecords() [][]string

func (*TradeStats) Recalculate added in v1.40.3

func (s *TradeStats) Recalculate()

Recalculate the trade stats fields from the orderProfits this is for live-trading, one order may have many trades, and we need to merge them.

func (*TradeStats) SetIntervalProfitCollector added in v1.38.0

func (s *TradeStats) SetIntervalProfitCollector(c *IntervalProfitCollector)

Set IntervalProfitCollector explicitly to enable the sharpe ratio calculation

func (*TradeStats) String added in v1.36.0

func (s *TradeStats) String() string

type TransferDirection added in v1.45.0

type TransferDirection int
const (
	TransferIn  TransferDirection = 1
	TransferOut TransferDirection = -1
)

type Unsubscriber added in v1.52.0

type Unsubscriber interface {
	// Unsubscribe unsubscribes the all subscriptions.
	Unsubscribe()
}

type UpdatableSeries added in v1.35.0

type UpdatableSeries interface {
	Series
	Update(float64)
}

type UpdatableSeriesExtend added in v1.36.0

type UpdatableSeriesExtend interface {
	SeriesExtend
	Update(float64)
}

func Clone added in v1.38.0

func TestUpdate added in v1.38.0

type ValueMap added in v1.35.0

type ValueMap map[string]fixedpoint.Value

func (ValueMap) Add added in v1.35.0

func (m ValueMap) Add(n ValueMap) ValueMap

func (ValueMap) AddScalar added in v1.35.0

func (m ValueMap) AddScalar(x fixedpoint.Value) ValueMap

func (ValueMap) Div added in v1.35.0

func (m ValueMap) Div(n ValueMap) ValueMap

func (ValueMap) DivScalar added in v1.35.0

func (m ValueMap) DivScalar(x fixedpoint.Value) ValueMap

func (ValueMap) Eq added in v1.35.0

func (m ValueMap) Eq(n ValueMap) bool

func (ValueMap) Mul added in v1.35.0

func (m ValueMap) Mul(n ValueMap) ValueMap

func (ValueMap) MulScalar added in v1.35.0

func (m ValueMap) MulScalar(x fixedpoint.Value) ValueMap

func (ValueMap) Normalize added in v1.35.0

func (m ValueMap) Normalize() ValueMap

func (ValueMap) Sub added in v1.35.0

func (m ValueMap) Sub(n ValueMap) ValueMap

func (ValueMap) SubScalar added in v1.35.0

func (m ValueMap) SubScalar(x fixedpoint.Value) ValueMap

func (ValueMap) Sum added in v1.35.0

func (m ValueMap) Sum() fixedpoint.Value

type WebsocketPongEvent added in v1.54.0

type WebsocketPongEvent struct{}

type Withdraw

type Withdraw struct {
	GID            int64            `json:"gid" db:"gid"`
	Exchange       ExchangeName     `json:"exchange" db:"exchange"`
	Asset          string           `json:"asset" db:"asset"`
	Amount         fixedpoint.Value `json:"amount" db:"amount"`
	Address        string           `json:"address" db:"address"`
	AddressTag     string           `json:"addressTag"`
	Status         WithdrawStatus   `json:"status"`
	OriginalStatus string           `json:"originalStatus"`

	TransactionID          string           `json:"transactionID" db:"txn_id"`
	TransactionFee         fixedpoint.Value `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) SlackAttachment added in v1.60.0

func (w *Withdraw) SlackAttachment() slack.Attachment

func (Withdraw) String added in v1.14.0

func (w Withdraw) String() (o string)

type WithdrawStatus added in v1.60.0

type WithdrawStatus string
const (
	WithdrawStatusSent             WithdrawStatus = "sent"
	WithdrawStatusCancelled        WithdrawStatus = "cancelled"
	WithdrawStatusAwaitingApproval WithdrawStatus = "awaiting_approval"
	WithdrawStatusRejected         WithdrawStatus = "rejected"
	WithdrawStatusProcessing       WithdrawStatus = "processing"
	WithdrawStatusFailed           WithdrawStatus = "failed"
	WithdrawStatusCompleted        WithdrawStatus = "completed"
	WithdrawStatusUnknown          WithdrawStatus = "unknown"
)

type WithdrawalOptions added in v1.17.0

type WithdrawalOptions struct {
	Network    string
	AddressTag string
}

type ZeroAssetError added in v1.42.0

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

func NewZeroAssetError added in v1.42.0

func NewZeroAssetError(e error) ZeroAssetError

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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