dola

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2021 License: MIT Imports: 27 Imported by: 0

README

Dola

Що се рекло от три наречници,
що се рекло и се извършило...

Dola is a cryptocurrency trading library that provides:

Exchanges

Dola expects to find a configuration file at ~/.dola/config.json. See an example here.

NB: Dola needs just the exchanges section.

Strategies

Each strategy is an implementation of the following interface. Dola has the responsibility of invoking all of the Strategy methods. Strategy.On* methods are invoked whenever there is new data from one of the registered exchanges. If you need a strategy that supports just one exchange (out of many), take a look at DedicatedStrategy.

type Strategy interface {
	Init(k *Keep, e exchange.IBotExchange) error
	OnFunding(k *Keep, e exchange.IBotExchange, x stream.FundingData) error
	OnPrice(k *Keep, e exchange.IBotExchange, x ticker.Price) error
	OnKline(k *Keep, e exchange.IBotExchange, x stream.KlineData) error
	OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error
	OnOrder(k *Keep, e exchange.IBotExchange, x order.Detail) error
	OnModify(k *Keep, e exchange.IBotExchange, x order.Modify) error
	OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error
	OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error
	Deinit(k *Keep, e exchange.IBotExchange) error
}

Example

package main

import (
	"context"
	"github.com/ydm/dola"
)

func main() {
	keep, _ := dola.NewKeepBuilder().Build()
	keep.Root.Add("verbose", dola.VerboseStrategy{})
	keep.Run(context.Background())
}
Augment config
keep, _ := dola.NewKeepBuilder().Augment(func (c *config.Config) erro {
    doSomething(c)
}).Build()
Use custom exchanges
creator := func() (exchange.IBotExchange, error) {
  return NewCustomExchange()
}
keep, _ := dola.NewKeepBuilder().CustomExchange(name, creator).Build()

Documentation

Overview

Package dola provides cryptocurrency trading primitives: exchange integrations (via github.com/thrasher-corp/gocryptotrader), event-driven strategies, utilities and more.

The toolbelt is a set of helper functions that eases strategies and cross usage.

Index

Examples

Constants

View Source
const (
	// In dormant mode the AwakenLogger outputs trace logs as info
	// every once in a while.
	Dormant = iota
	// In awaken mode everything is outputted as-is.
	Awaken = iota
)

Variables

View Source
var (
	ErrNoExchangesLoaded    = errors.New("no exchanges have been loaded")
	ErrExchangeFailedToLoad = errors.New("exchange failed to load")
)
View Source
var (
	ErrAccountIndexOutOfRange = errors.New("no account with this index exists")
	ErrCurrencyNotFound       = errors.New("currency not found in holdings")
	ErrHoldingsNotFound       = errors.New("holdings not found for exchange")
)
View Source
var (
	ErrStrategyNotFound = errors.New("strategy not found")
	ErrNotStrategy      = errors.New("given object is not a strategy")
)
View Source
var (
	ErrWebsocketNotSupported = errors.New("websocket not supported")
	ErrWebsocketNotEnabled   = errors.New("websocket is not enabled")
)
View Source
var ErrCreatorNotRegistered = errors.New("exchange creator not registered")
View Source
var ErrNeedBalancesStrategy = errors.New("Keep should be configured with balances support")
View Source
var ErrOrdersAlreadyExists = errors.New("order already exists")
View Source
var ErrUnknownEvent = errors.New("unknown event")

Functions

func CheckerAssert

func CheckerAssert()

CheckerAssert should be defer-called in main().

func CheckerPop

func CheckerPop(xs ...string)

func CheckerPush

func CheckerPush(xs ...string)

func Code

func Code(e *zerolog.Event, code string)

func ConfigFile

func ConfigFile(inp string) string

ConfigFile checks whether a file with the given path exists. If it doesnt, it falls back to: (1) $DOLA_CONFIG, (2) ~/.dola.config.json or (3) returns an empty string.

func CurrencyBalance

func CurrencyBalance(k *Keep, exchangeName, currencyCode string, accountID string) (account.Balance, error)

func ExpandUser

func ExpandUser(path string) string

ExpandUser returns the argument with an initial ~ replaced by user's home directory.

func FileExists

func FileExists(path string) bool

func Holdings

func Holdings(k *Keep, exchangeName string) (account.Holdings, error)

func Location

func Location() string

Location returns the name of the caller function.

func Location2

func Location2() string

Location2 returns the name of the caller of the caller function.

func ModifyOrder

func ModifyOrder(ctx context.Context,
	k *Keep,
	e exchange.IBotExchange,
	mod order.Modify) (ans order.Modify, err error)

func ModifyToCancel

func ModifyToCancel(mod order.Modify) order.Cancel

func ModifyToSubmit

func ModifyToSubmit(mod order.Modify) order.Submit

func Msg

func Msg(e *zerolog.Event)

func RandomOrderID

func RandomOrderID(prefix string) string

RandomOrderID uses code and ideas from: https://stackoverflow.com/questions/32349807 and https://stackoverflow.com/questions/13378815 .

Length of produced client order ID is encoded in the code. See `seed`.

func Stream

func Stream(ctx context.Context, k *Keep, e exchange.IBotExchange, s Strategy) error

func Ticker

func Ticker(p interface{}) ticker.Price

Ticker casts a void* to ticker.Price.

func What

func What(e *zerolog.Event, what string)

Types

type Array

type Array interface {
	At(index int) interface{}
	Len() int
	Last() interface{}

	Floats() []float64
	LastFloat() float64
}

type AugmentConfigFunc

type AugmentConfigFunc func(*config.Config) error

type AwakenLogger

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

func NewAwakenLogger

func NewAwakenLogger(d time.Duration) AwakenLogger

func (*AwakenLogger) Trace

func (t *AwakenLogger) Trace() *zerolog.Event

func (*AwakenLogger) WakeUp

func (t *AwakenLogger) WakeUp()

WakeUp gets the AwakenLogger out of its dormant state for a an amount of time.

type BalancesStrategy

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

func (*BalancesStrategy) Currency

func (b *BalancesStrategy) Currency(exchangeName string, code string, accountID string) (account.Balance, error)

func (*BalancesStrategy) Deinit

func (b *BalancesStrategy) Deinit(k *Keep, e exchange.IBotExchange) error

func (*BalancesStrategy) Init

func (*BalancesStrategy) Load

func (b *BalancesStrategy) Load(exchangeName string) (holdings account.Holdings, loaded bool)

func (*BalancesStrategy) OnBalanceChange

func (b *BalancesStrategy) OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error

func (*BalancesStrategy) OnFunding

func (*BalancesStrategy) OnKline

func (*BalancesStrategy) OnModify

func (*BalancesStrategy) OnOrder

func (*BalancesStrategy) OnOrderBook

func (b *BalancesStrategy) OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error

func (*BalancesStrategy) OnPrice

func (*BalancesStrategy) OnUnrecognized

func (b *BalancesStrategy) OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error

func (*BalancesStrategy) Store

func (b *BalancesStrategy) Store(holdings account.Holdings)

type CircularArray

type CircularArray struct {
	Offset int
	// contains filtered or unexported fields
}

func NewCircularArray

func NewCircularArray(n int) CircularArray

func (*CircularArray) At

func (a *CircularArray) At(index int) interface{}

func (*CircularArray) Floats

func (a *CircularArray) Floats() []float64

func (*CircularArray) Index

func (a *CircularArray) Index(i int) int

Index maps an external 0-based index to the corresponding internal index.

func (*CircularArray) Last

func (a *CircularArray) Last() interface{}

func (*CircularArray) LastFloat

func (a *CircularArray) LastFloat() float64

func (*CircularArray) LastIndex

func (a *CircularArray) LastIndex() int

func (*CircularArray) Len

func (a *CircularArray) Len() int

func (*CircularArray) Push

func (a *CircularArray) Push(x interface{})

type DedicatedStrategy

type DedicatedStrategy struct {
	Exchange string
	Wrapped  Strategy
}

DedicatedStrategy is a Strategy wrapper that executes wrapped methods only when events come from a particular exchange.

func (*DedicatedStrategy) Deinit

func (*DedicatedStrategy) Init

func (*DedicatedStrategy) OnBalanceChange

func (d *DedicatedStrategy) OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error

func (*DedicatedStrategy) OnFunding

func (*DedicatedStrategy) OnKline

func (*DedicatedStrategy) OnModify

func (*DedicatedStrategy) OnOrder

func (*DedicatedStrategy) OnOrderBook

func (d *DedicatedStrategy) OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error

func (*DedicatedStrategy) OnPrice

func (*DedicatedStrategy) OnUnrecognized

func (d *DedicatedStrategy) OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error

type ErrorWaitGroup

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

func (*ErrorWaitGroup) Add

func (m *ErrorWaitGroup) Add(delta int)

func (*ErrorWaitGroup) Done

func (m *ErrorWaitGroup) Done(right error)

func (*ErrorWaitGroup) Wait

func (m *ErrorWaitGroup) Wait() error

type ExchangeCreatorFunc

type ExchangeCreatorFunc func() (exchange.IBotExchange, error)

type ExchangeFactory

type ExchangeFactory map[string]ExchangeCreatorFunc

func (ExchangeFactory) NewExchangeByName

func (e ExchangeFactory) NewExchangeByName(name string) (exchange.IBotExchange, error)

NewExchangeByName implements gocryptotrader/engine.CustomExchangeBuilder.

func (ExchangeFactory) Register

func (e ExchangeFactory) Register(name string, fn ExchangeCreatorFunc)

type GCTLog

type GCTLog struct {
	ExchangeSys interface{}
}

func (GCTLog) Debugf

func (g GCTLog) Debugf(_ interface{}, data string, v ...interface{})

func (GCTLog) Errorf

func (g GCTLog) Errorf(_ interface{}, data string, v ...interface{})

func (GCTLog) Warnf

func (g GCTLog) Warnf(_ interface{}, data string, v ...interface{})

type Historian

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

func NewHistorian

func NewHistorian(interval time.Duration, stateLength int, f func(Array)) Historian

func (*Historian) Floats

func (u *Historian) Floats() []float64

Floats returns the State array, but casted to []float64.

func (*Historian) Push

func (u *Historian) Push(x interface{})

func (*Historian) Update

func (u *Historian) Update(now time.Time, x interface{})

type HistoryStrategy

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

func NewHistoryStrategy

func NewHistoryStrategy() HistoryStrategy

func (*HistoryStrategy) AddHistorian

func (r *HistoryStrategy) AddHistorian(
	exchangeName,
	eventName string,
	interval time.Duration,
	stateLength int,
	f func(Array),
) error

func (*HistoryStrategy) BindOnPrice

func (r *HistoryStrategy) BindOnPrice(unit *Historian)

func (*HistoryStrategy) Deinit

func (r *HistoryStrategy) Deinit(k *Keep, e exchange.IBotExchange) error

func (*HistoryStrategy) Init

func (*HistoryStrategy) OnBalanceChange

func (r *HistoryStrategy) OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error

func (*HistoryStrategy) OnFunding

func (*HistoryStrategy) OnKline

func (*HistoryStrategy) OnModify

func (r *HistoryStrategy) OnModify(k *Keep, e exchange.IBotExchange, x order.Modify) error

func (*HistoryStrategy) OnOrder

func (*HistoryStrategy) OnOrderBook

func (r *HistoryStrategy) OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error

func (*HistoryStrategy) OnPrice

func (*HistoryStrategy) OnUnrecognized

func (r *HistoryStrategy) OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error

type Keep

type Keep struct {
	Config          config.Config
	ExchangeManager engine.ExchangeManager
	Root            RootStrategy
	Settings        engine.Settings
	// contains filtered or unexported fields
}
Example
package main

import (
	"context"

	"github.com/ydm/dola"
)

func main() {
	keep, _ := dola.NewKeepBuilder().Build()
	keep.Root.Add("verbose", dola.VerboseStrategy{}) //nolint:exhaustivestruct
	keep.Run(context.Background())
}
Output:

func (*Keep) AddHistorian

func (bot *Keep) AddHistorian(
	exchangeName,
	eventName string,
	interval time.Duration,
	stateLength int,
	f func(Array),
) error

func (*Keep) CancelAllOrders

func (bot *Keep) CancelAllOrders(
	ctx context.Context,
	exchangeOrName interface{},
	assetType asset.Item,
	pair currency.Pair,
) (
	order.CancelAllResponse, error,
)

func (*Keep) CancelOrder

func (bot *Keep) CancelOrder(ctx context.Context, exchangeOrName interface{}, x order.Cancel) error

func (*Keep) CancelOrdersByPrefix

func (bot *Keep) CancelOrdersByPrefix(
	ctx context.Context,
	exchangeOrName interface{},
	x order.Cancel,
	prefix string,
) error

func (*Keep) GetActiveOrders

func (bot *Keep) GetActiveOrders(ctx context.Context, exchangeOrName interface{}, request order.GetOrdersRequest) (
	[]order.Detail, error,
)

func (*Keep) GetExchanges

func (bot *Keep) GetExchanges() []exchange.IBotExchange

func (*Keep) GetOrderValue

func (bot *Keep) GetOrderValue(exchangeName, orderID string) (OrderValue, bool)

func (*Keep) LoadExchange

func (bot *Keep) LoadExchange(name string, wg *sync.WaitGroup) error

func (*Keep) ModifyOrder

func (bot *Keep) ModifyOrder(
	ctx context.Context,
	exchangeOrName interface{},
	mod order.Modify,
) (order.Modify, error)

func (*Keep) OnOrder

func (bot *Keep) OnOrder(e exchange.IBotExchange, x order.Detail)

func (*Keep) Run

func (bot *Keep) Run(ctx context.Context)

Run is the entry point of all exchange data streams. Strategy.On*() events for a single exchange are invoked from the same thread. Thus, if a strategy deals with multiple exchanges simultaneously, there may be race conditions.

func (*Keep) SubmitOrder

func (bot *Keep) SubmitOrder(
	ctx context.Context,
	exchangeOrName interface{},
	submit order.Submit,
) (order.SubmitResponse, error)

func (*Keep) SubmitOrderUD

func (bot *Keep) SubmitOrderUD(
	ctx context.Context,
	exchangeOrName interface{},
	submit order.Submit,
	userData interface{},
) (
	order.SubmitResponse, error,
)

func (*Keep) SubmitOrders

func (bot *Keep) SubmitOrders(ctx context.Context, e exchange.IBotExchange, xs ...order.Submit) error

type KeepBuilder

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

func NewKeepBuilder

func NewKeepBuilder() *KeepBuilder

func (*KeepBuilder) Augment

func (b *KeepBuilder) Augment(f AugmentConfigFunc) *KeepBuilder

func (*KeepBuilder) Balances

func (b *KeepBuilder) Balances(refreshRate time.Duration) *KeepBuilder

func (*KeepBuilder) Build

func (b *KeepBuilder) Build() (*Keep, error)

func (*KeepBuilder) CustomExchange

func (b *KeepBuilder) CustomExchange(name string, fn ExchangeCreatorFunc) *KeepBuilder

func (*KeepBuilder) Settings

func (b *KeepBuilder) Settings(s engine.Settings) *KeepBuilder

type LogState

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

LogState keeps track of what the current state is.

func NewLogState

func NewLogState(duration time.Duration) LogState

func (*LogState) Awaken

func (s *LogState) Awaken() bool

func (*LogState) WakeUp

func (s *LogState) WakeUp()

type OnFilledObserver

type OnFilledObserver interface {
	OnFilled(k *Keep, e exchange.IBotExchange, x order.Detail)
}

type OrderKey

type OrderKey struct {
	ExchangeName string
	OrderID      string
}

type OrderRegistry

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

func NewOrderRegistry

func NewOrderRegistry() *OrderRegistry

func (*OrderRegistry) GetOrderValue

func (r *OrderRegistry) GetOrderValue(exchangeName, orderID string) (OrderValue, bool)

func (*OrderRegistry) Length

func (r *OrderRegistry) Length() int

func (*OrderRegistry) Store

func (r *OrderRegistry) Store(exchangeName string, response order.SubmitResponse, userData interface{}) bool

Store saves order details. If such an order exists (matched by exchange name and order ID), false is returned.

type OrderValue

type OrderValue struct {
	SubmitResponse order.SubmitResponse
	UserData       interface{}
}

type Profiler

type Profiler struct {
	Filename string
}

func NewProfiler

func NewProfiler(filename string) Profiler

func (Profiler) Stop

func (p Profiler) Stop()

type RootStrategy

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

func NewRootStrategy

func NewRootStrategy() RootStrategy

func (*RootStrategy) Add

func (m *RootStrategy) Add(name string, s Strategy)

func (*RootStrategy) Deinit

func (m *RootStrategy) Deinit(k *Keep, e exchange.IBotExchange) error

func (*RootStrategy) Delete

func (m *RootStrategy) Delete(name string) (Strategy, error)

func (*RootStrategy) Get

func (m *RootStrategy) Get(name string) (Strategy, error)

func (*RootStrategy) Init

func (m *RootStrategy) Init(k *Keep, e exchange.IBotExchange) error

func (*RootStrategy) OnBalanceChange

func (m *RootStrategy) OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error

func (*RootStrategy) OnFunding

func (*RootStrategy) OnKline

func (*RootStrategy) OnModify

func (m *RootStrategy) OnModify(k *Keep, e exchange.IBotExchange, x order.Modify) error

func (*RootStrategy) OnOrder

func (m *RootStrategy) OnOrder(k *Keep, e exchange.IBotExchange, x order.Detail) error

func (*RootStrategy) OnOrderBook

func (m *RootStrategy) OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error

func (*RootStrategy) OnPrice

func (m *RootStrategy) OnPrice(k *Keep, e exchange.IBotExchange, x ticker.Price) error

func (*RootStrategy) OnUnrecognized

func (m *RootStrategy) OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error

type Slots

type Slots struct {
	OnFilledSlot func(k *Keep, e exchange.IBotExchange, x order.Detail)
}

func (Slots) OnFilled

func (s Slots) OnFilled(k *Keep, e exchange.IBotExchange, x order.Detail)

OnFilled implements OnFilledObserver.

type Strategy

type Strategy interface {
	Init(k *Keep, e exchange.IBotExchange) error
	OnFunding(k *Keep, e exchange.IBotExchange, x stream.FundingData) error
	OnPrice(k *Keep, e exchange.IBotExchange, x ticker.Price) error
	OnKline(k *Keep, e exchange.IBotExchange, x stream.KlineData) error
	OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error
	OnOrder(k *Keep, e exchange.IBotExchange, x order.Detail) error
	OnModify(k *Keep, e exchange.IBotExchange, x order.Modify) error
	OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error
	OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error
	Deinit(k *Keep, e exchange.IBotExchange) error
}

func NewBalancesStrategy

func NewBalancesStrategy(refreshRate time.Duration) Strategy

type TickerStrategy

type TickerStrategy struct {
	Interval time.Duration
	TickFunc func(k *Keep, e exchange.IBotExchange)
	// contains filtered or unexported fields
}

func (*TickerStrategy) Deinit

func (s *TickerStrategy) Deinit(k *Keep, e exchange.IBotExchange) error

func (*TickerStrategy) Init

func (*TickerStrategy) OnBalanceChange

func (s *TickerStrategy) OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error

func (*TickerStrategy) OnFunding

func (*TickerStrategy) OnKline

func (*TickerStrategy) OnModify

func (s *TickerStrategy) OnModify(k *Keep, e exchange.IBotExchange, x order.Modify) error

func (*TickerStrategy) OnOrder

func (s *TickerStrategy) OnOrder(k *Keep, e exchange.IBotExchange, x order.Detail) error

func (*TickerStrategy) OnOrderBook

func (s *TickerStrategy) OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error

func (*TickerStrategy) OnPrice

func (s *TickerStrategy) OnPrice(k *Keep, e exchange.IBotExchange, x ticker.Price) error

func (*TickerStrategy) OnUnrecognized

func (s *TickerStrategy) OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error

type Trade

type Trade struct {
	Timestamp     time.Time
	BaseCurrency  string
	QuoteCurrency string
	OrderID       string
	AveragePrice  float64
	Quantity      float64
	Fee           float64
	FeeCurrency   string
}

type VerboseStrategy

type VerboseStrategy struct {
	SilencePrice     bool
	SilenceKline     bool
	SilenceOrderBook bool
	SilenceOrder     bool
}

func (VerboseStrategy) Deinit

func (VerboseStrategy) Init

func (VerboseStrategy) OnBalanceChange

func (v VerboseStrategy) OnBalanceChange(k *Keep, e exchange.IBotExchange, x account.Change) error

func (VerboseStrategy) OnFunding

func (VerboseStrategy) OnKline

func (VerboseStrategy) OnModify

func (VerboseStrategy) OnOrder

func (VerboseStrategy) OnOrderBook

func (v VerboseStrategy) OnOrderBook(k *Keep, e exchange.IBotExchange, x orderbook.Base) error

func (VerboseStrategy) OnPrice

func (VerboseStrategy) OnUnrecognized

func (v VerboseStrategy) OnUnrecognized(k *Keep, e exchange.IBotExchange, x interface{}) error

Jump to

Keyboard shortcuts

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