service

package
v0.0.0-...-cb4139d Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2023 License: AGPL-3.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrExchangeRewardServiceNotImplemented = errors.New("exchange does not implement ExchangeRewardService interface")
View Source
var ErrNotImplemented = errors.New("not implemented")
View Source
var ErrPersistenceNotExists = errors.New("persistent data does not exists")
View Source
var ErrTradeNotFound = errors.New("trade not found")

Functions

func NewDefaultTotpKey

func NewDefaultTotpKey() (*otp.Key, error)

func ParseStructTag

func ParseStructTag(s string) (string, map[string]string)

func ReformatMysqlDSN

func ReformatMysqlDSN(dsn string) (string, error)

func SelectKLineTimePoints

func SelectKLineTimePoints(ex types.ExchangeName, symbol string, interval types.Interval, args ...time.Time) sq.SelectBuilder

func SelectKLineTimeRange

func SelectKLineTimeRange(ex types.ExchangeName, symbol string, interval types.Interval, args ...time.Time) sq.SelectBuilder

SelectKLineTimeRange returns the existing klines time range (since < kline.start_time < until)

func SelectLastDeposits

func SelectLastDeposits(ex types.ExchangeName, limit uint64) sq.SelectBuilder

func SelectLastKLines

func SelectLastKLines(ex types.ExchangeName, symbol string, interval types.Interval, startTime, endTime time.Time, limit uint64) sq.SelectBuilder

TODO: add is_futures column since the klines data is different

func SelectLastMarginInterests

func SelectLastMarginInterests(ex types.ExchangeName, asset string, limit uint64) sq.SelectBuilder

func SelectLastMarginLiquidations

func SelectLastMarginLiquidations(ex types.ExchangeName, limit uint64) sq.SelectBuilder

func SelectLastMarginLoans

func SelectLastMarginLoans(ex types.ExchangeName, asset string, limit uint64) sq.SelectBuilder

func SelectLastMarginRepays

func SelectLastMarginRepays(ex types.ExchangeName, asset string, limit uint64) sq.SelectBuilder

func SelectLastOrders

func SelectLastOrders(ex types.ExchangeName, symbol string, isMargin, isFutures, isIsolated bool, limit uint64) sq.SelectBuilder

func SelectLastRewards

func SelectLastRewards(ex types.ExchangeName, limit uint64) sq.SelectBuilder

func SelectLastTrades

func SelectLastTrades(ex types.ExchangeName, symbol string, isMargin, isFutures, isIsolated bool, limit uint64) sq.SelectBuilder

func SelectLastWithdraws

func SelectLastWithdraws(ex types.ExchangeName, limit uint64) sq.SelectBuilder

Types

type AccountService

type AccountService struct {
	DB *sqlx.DB
}

func NewAccountService

func NewAccountService(db *sqlx.DB) *AccountService

func (*AccountService) InsertAsset

func (s *AccountService) InsertAsset(time time.Time, session string, name types.ExchangeName, account string, isMargin bool, isIsolatedMargin bool, isolatedMarginSymbol string, assets types.AssetMap) error

TODO: should pass bbgo.ExchangeSession to this function, but that might cause cyclic import

type AggOrder

type AggOrder struct {
	types.Order
	AveragePrice *float64 `json:"averagePrice" db:"average_price"`
}

type BacktestService

type BacktestService struct {
	DB *sqlx.DB
}

func (*BacktestService) BatchInsert

func (s *BacktestService) BatchInsert(kline []types.KLine) error

BatchInsert Note: all kline should be same exchange, or it will cause issue.

func (*BacktestService) FindMissingTimeRanges

func (s *BacktestService) FindMissingTimeRanges(ctx context.Context, ex types.Exchange, symbol string, interval types.Interval, since, until time.Time) ([]TimeRange, error)

FindMissingTimeRanges returns the missing time ranges, the start/end time represents the existing data time points. So when sending kline query to the exchange API, we need to add one second to the start time and minus one second to the end time.

func (*BacktestService) Insert

func (s *BacktestService) Insert(kline types.KLine) error

func (*BacktestService) QueryExistingDataRange

func (s *BacktestService) QueryExistingDataRange(ctx context.Context, ex types.Exchange, symbol string, interval types.Interval, tArgs ...time.Time) (start, end *types.Time, err error)

func (*BacktestService) QueryKLine

func (s *BacktestService) QueryKLine(ex types.ExchangeName, symbol string, interval types.Interval, orderBy string, limit int) (*types.KLine, error)

QueryKLine queries the klines from the database

func (*BacktestService) QueryKLinesBackward

func (s *BacktestService) QueryKLinesBackward(exchange types.ExchangeName, symbol string, interval types.Interval, endTime time.Time, limit int) ([]types.KLine, error)

func (*BacktestService) QueryKLinesCh

func (s *BacktestService) QueryKLinesCh(since, until time.Time, exchange types.Exchange, symbols []string, intervals []types.Interval) (chan types.KLine, chan error)

func (*BacktestService) QueryKLinesForward

func (s *BacktestService) QueryKLinesForward(exchange types.ExchangeName, symbol string, interval types.Interval, startTime time.Time, limit int) ([]types.KLine, error)

QueryKLinesForward is used for querying klines to back-testing

func (*BacktestService) Sync

func (s *BacktestService) Sync(ctx context.Context, ex types.Exchange, symbol string, interval types.Interval, since, until time.Time) error

func (*BacktestService) SyncFresh

func (s *BacktestService) SyncFresh(ctx context.Context, exchange types.Exchange, symbol string, interval types.Interval, startTime, endTime time.Time) error

func (*BacktestService) SyncKLineByInterval

func (s *BacktestService) SyncKLineByInterval(ctx context.Context, exchange types.Exchange, symbol string, interval types.Interval, startTime, endTime time.Time) error

func (*BacktestService) SyncPartial

func (s *BacktestService) SyncPartial(ctx context.Context, ex types.Exchange, symbol string, interval types.Interval, since, until time.Time) error

SyncPartial find the existing data time range (t1, t2) scan if there is a missing part create a time range slice []TimeRange iterate the []TimeRange slice to sync data.

func (*BacktestService) Verify

func (s *BacktestService) Verify(sourceExchange types.Exchange, symbols []string, startTime time.Time, endTime time.Time) error

type CurrencyPositionMap

type CurrencyPositionMap map[string]fixedpoint.Value

type DatabaseService

type DatabaseService struct {
	Driver string
	DSN    string
	DB     *sqlx.DB
}

func NewDatabaseService

func NewDatabaseService(driver, dsn string) *DatabaseService

func (*DatabaseService) Close

func (s *DatabaseService) Close() error

func (*DatabaseService) Connect

func (s *DatabaseService) Connect() error

func (*DatabaseService) Insert

func (s *DatabaseService) Insert(record interface{}) error

func (*DatabaseService) Upgrade

func (s *DatabaseService) Upgrade(ctx context.Context) error

type DepositService

type DepositService struct {
	DB *sqlx.DB
}

func (*DepositService) Query

func (s *DepositService) Query(exchangeName types.ExchangeName) ([]types.Deposit, error)

func (*DepositService) Sync

func (s *DepositService) Sync(ctx context.Context, ex types.Exchange, startTime time.Time) error

Sync syncs the withdraw records into db

type Expirable

type Expirable interface {
	Expiration() time.Duration
}

type JsonPersistenceConfig

type JsonPersistenceConfig struct {
	Directory string `yaml:"directory" json:"directory"`
}

type JsonPersistenceService

type JsonPersistenceService struct {
	Directory string
}

func (*JsonPersistenceService) NewStore

func (s *JsonPersistenceService) NewStore(id string, subIDs ...string) Store

type JsonStore

type JsonStore struct {
	ID        string
	Directory string
}

func (JsonStore) Load

func (store JsonStore) Load(val interface{}) error

func (JsonStore) Reset

func (store JsonStore) Reset() error

func (JsonStore) Save

func (store JsonStore) Save(val interface{}) error

type MarginService

type MarginService struct {
	DB *sqlx.DB
}

func (*MarginService) Sync

func (s *MarginService) Sync(ctx context.Context, ex types.Exchange, asset string, startTime time.Time) error

type MemoryService

type MemoryService struct {
	Slots map[string]interface{}
}

func NewMemoryService

func NewMemoryService() *MemoryService

func (*MemoryService) NewStore

func (s *MemoryService) NewStore(id string, subIDs ...string) Store

type MemoryStore

type MemoryStore struct {
	Key string
	// contains filtered or unexported fields
}

func (*MemoryStore) Load

func (store *MemoryStore) Load(val interface{}) error

func (*MemoryStore) Reset

func (store *MemoryStore) Reset() error

func (*MemoryStore) Save

func (store *MemoryStore) Save(val interface{}) error

type OrderService

type OrderService struct {
	DB *sqlx.DB
}

func (*OrderService) Insert

func (s *OrderService) Insert(order types.Order) (err error)

func (*OrderService) Query

func (s *OrderService) Query(options QueryOrdersOptions) ([]AggOrder, error)

func (*OrderService) Sync

func (s *OrderService) Sync(ctx context.Context, exchange types.Exchange, symbol string, startTime time.Time) error

type PersistenceService

type PersistenceService interface {
	NewStore(id string, subIDs ...string) Store
}

type PersistenceServiceFacade

type PersistenceServiceFacade struct {
	Redis  *RedisPersistenceService
	Json   *JsonPersistenceService
	Memory *MemoryService
}

func (*PersistenceServiceFacade) Get

Get returns the preferred persistence service by fallbacks Redis will be preferred at the first position.

type PositionService

type PositionService struct {
	DB *sqlx.DB
}

func NewPositionService

func NewPositionService(db *sqlx.DB) *PositionService

func (*PositionService) Insert

func (s *PositionService) Insert(position *types.Position, trade types.Trade, profit fixedpoint.Value) error

func (*PositionService) Load

func (s *PositionService) Load(ctx context.Context, id int64) (*types.Position, error)

type ProfitService

type ProfitService struct {
	DB *sqlx.DB
}

func (*ProfitService) Insert

func (s *ProfitService) Insert(profit types.Profit) error

func (*ProfitService) Load

func (s *ProfitService) Load(ctx context.Context, id int64) (*types.Trade, error)

type QueryOrdersOptions

type QueryOrdersOptions struct {
	Exchange types.ExchangeName
	Symbol   string
	LastGID  int64
	Ordering string
}

type QueryTradesOptions

type QueryTradesOptions struct {
	Exchange types.ExchangeName
	Sessions []string
	Symbol   string
	LastGID  int64
	Since    *time.Time

	// ASC or DESC
	Ordering string
	Limit    uint64
}

type RedisPersistenceConfig

type RedisPersistenceConfig struct {
	Host      string `yaml:"host" json:"host" env:"REDIS_HOST"`
	Port      string `yaml:"port" json:"port" env:"REDIS_PORT"`
	Password  string `yaml:"password,omitempty" json:"password,omitempty" env:"REDIS_PASSWORD"`
	DB        int    `yaml:"db" json:"db" env:"REDIS_DB"`
	Namespace string `yaml:"namespace" json:"namespace" env:"REDIS_NAMESPACE"`
}

type RedisPersistenceService

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

func NewRedisPersistenceService

func NewRedisPersistenceService(config *RedisPersistenceConfig) *RedisPersistenceService

func (*RedisPersistenceService) NewStore

func (s *RedisPersistenceService) NewStore(id string, subIDs ...string) Store

type RedisStore

type RedisStore struct {
	ID string
	// contains filtered or unexported fields
}

func (*RedisStore) Load

func (store *RedisStore) Load(val interface{}) error

func (*RedisStore) Reset

func (store *RedisStore) Reset() error

func (*RedisStore) Save

func (store *RedisStore) Save(val interface{}) error

type ReflectCache

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

func NewReflectCache

func NewReflectCache() *ReflectCache

func (*ReflectCache) FieldsOf

func (c *ReflectCache) FieldsOf(t interface{}) []string

func (*ReflectCache) InsertSqlOf

func (c *ReflectCache) InsertSqlOf(t interface{}) string

func (*ReflectCache) PlaceholderOf

func (c *ReflectCache) PlaceholderOf(t interface{}) []string

func (*ReflectCache) TableNameOf

func (c *ReflectCache) TableNameOf(t interface{}) string

type RewardService

type RewardService struct {
	DB *sqlx.DB
}

RewardService collects the reward records from the exchange, currently it's only available for MAX exchange. TODO: add summary query for calculating the reward amounts CREATE VIEW reward_summary_by_years AS SELECT YEAR(created_at) as year, reward_type, currency, SUM(quantity) FROM rewards WHERE reward_type != 'airdrop' GROUP BY YEAR(created_at), reward_type, currency ORDER BY year DESC;

func (*RewardService) AggregateUnspentCurrencyPosition

func (s *RewardService) AggregateUnspentCurrencyPosition(ctx context.Context, ex types.ExchangeName, since time.Time) (CurrencyPositionMap, error)

func (*RewardService) Insert

func (s *RewardService) Insert(reward types.Reward) error

func (*RewardService) MarkAsSpent

func (s *RewardService) MarkAsSpent(ctx context.Context, uuid string) error

func (*RewardService) MarkCurrencyAsSpent

func (s *RewardService) MarkCurrencyAsSpent(ctx context.Context, currency string) error

func (*RewardService) QueryUnspent

func (s *RewardService) QueryUnspent(ctx context.Context, ex types.ExchangeName, rewardTypes ...types.RewardType) ([]types.Reward, error)

func (*RewardService) QueryUnspentSince

func (s *RewardService) QueryUnspentSince(ctx context.Context, ex types.ExchangeName, since time.Time, rewardTypes ...types.RewardType) ([]types.Reward, error)

func (*RewardService) Sync

func (s *RewardService) Sync(ctx context.Context, exchange types.Exchange, startTime time.Time) error

type Store

type Store interface {
	Load(val interface{}) error
	Save(val interface{}) error
	Reset() error
}

type SyncService

type SyncService struct {
	TradeService    *TradeService
	OrderService    *OrderService
	RewardService   *RewardService
	WithdrawService *WithdrawService
	DepositService  *DepositService
	MarginService   *MarginService
}

func (*SyncService) SyncDepositHistory

func (s *SyncService) SyncDepositHistory(ctx context.Context, exchange types.Exchange, startTime time.Time) error

func (*SyncService) SyncMarginHistory

func (s *SyncService) SyncMarginHistory(ctx context.Context, exchange types.Exchange, startTime time.Time, assets ...string) error

func (*SyncService) SyncRewardHistory

func (s *SyncService) SyncRewardHistory(ctx context.Context, exchange types.Exchange, startTime time.Time) error

func (*SyncService) SyncSessionSymbols

func (s *SyncService) SyncSessionSymbols(ctx context.Context, exchange types.Exchange, startTime time.Time, symbols ...string) error

SyncSessionSymbols syncs the trades from the given exchange session

func (*SyncService) SyncWithdrawHistory

func (s *SyncService) SyncWithdrawHistory(ctx context.Context, exchange types.Exchange, startTime time.Time) error

type SyncTask

type SyncTask struct {
	// Type is the element type of this sync task
	// Since it will create a []Type slice from this type, you should not set pointer to this field
	Type interface{}

	// ID is a function that returns the unique identity of the object
	// This function will be used for detecting duplicated objects.
	ID func(obj interface{}) string

	// Time is a function that returns the time of the object
	// This function will be used for sorting records
	Time func(obj interface{}) time.Time

	// Select is the select query builder for querying existing db records
	// The built SQL will be used for querying existing db records.
	// And then the ID function will be used for filtering duplicated object.
	Select squirrel.SelectBuilder

	// OnLoad is an optional field, which is called when the records are loaded from the database
	OnLoad func(objs interface{})

	// Filter is an optional field, which is used for filtering the remote records
	// Return true to keep the record,
	// Return false to filter the record.
	Filter func(obj interface{}) bool

	// BatchQuery is used for querying remote records.
	BatchQuery func(ctx context.Context, startTime, endTime time.Time) (interface{}, chan error)

	// Insert is an option field, which is used for customizing the record insert
	Insert func(obj interface{}) error

	// Insert is an option field, which is used for customizing the record batch insert
	BatchInsert func(obj interface{}) error

	BatchInsertBuffer int

	// LogInsert logs the insert record in INFO level
	LogInsert bool
}

SyncTask defines the behaviors for syncing remote records

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

func (*TimeRange) String

func (t *TimeRange) String() string

type TradeService

type TradeService struct {
	DB *sqlx.DB
}

func NewTradeService

func NewTradeService(db *sqlx.DB) *TradeService

func (*TradeService) DeleteAll

func (s *TradeService) DeleteAll() error

func (*TradeService) Insert

func (s *TradeService) Insert(trade types.Trade) error

func (*TradeService) Load

func (s *TradeService) Load(ctx context.Context, id int64) (*types.Trade, error)

func (*TradeService) Query

func (s *TradeService) Query(options QueryTradesOptions) ([]types.Trade, error)

func (*TradeService) QueryForTradingFeeCurrency

func (s *TradeService) QueryForTradingFeeCurrency(ex types.ExchangeName, symbol string, feeCurrency string) ([]types.Trade, error)

func (*TradeService) QueryTradingVolume

func (s *TradeService) QueryTradingVolume(startTime time.Time, options TradingVolumeQueryOptions) ([]TradingVolume, error)

func (*TradeService) Sync

func (s *TradeService) Sync(ctx context.Context, exchange types.Exchange, symbol string, startTime time.Time) error

type TradingVolume

type TradingVolume struct {
	Year        int       `db:"year" json:"year"`
	Month       int       `db:"month" json:"month,omitempty"`
	Day         int       `db:"day" json:"day,omitempty"`
	Time        time.Time `json:"time,omitempty"`
	Exchange    string    `db:"exchange" json:"exchange,omitempty"`
	Symbol      string    `db:"symbol" json:"symbol,omitempty"`
	QuoteVolume float64   `db:"quote_volume" json:"quoteVolume"`
}

type TradingVolumeQueryOptions

type TradingVolumeQueryOptions struct {
	GroupByPeriod string
	SegmentBy     string
}

type WithdrawService

type WithdrawService struct {
	DB *sqlx.DB
}

func (*WithdrawService) Insert

func (s *WithdrawService) Insert(withdrawal types.Withdraw) error

func (*WithdrawService) Query

func (s *WithdrawService) Query(exchangeName types.ExchangeName) ([]types.Withdraw, error)

func (*WithdrawService) QueryLast

func (s *WithdrawService) QueryLast(ex types.ExchangeName, limit int) ([]types.Withdraw, error)

func (*WithdrawService) Sync

func (s *WithdrawService) Sync(ctx context.Context, ex types.Exchange, startTime time.Time) error

Sync syncs the withdrawal records into db

Jump to

Keyboard shortcuts

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