quota

package module
v1.0.31-alpha Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2021 License: Apache-2.0 Imports: 15 Imported by: 0

README

Quota

Go Reference GitHub go.mod Go version of a Go module GoReportCard example GitHub license GitHub release PRs Welcome CI CodeQL AutoRelease

Quota of candles

A time series to help you with your trading bot.

Documentation

Overview

Package quota will provide fundamental concept and utils to operate with financial time-series data, specially supports crypto-currencies.

Index

Constants

View Source
const (
	// SourceOpen determines open Source
	SourceOpen = Source("open")
	// SourceHigh determines open Source
	SourceHigh = Source("high")
	// SourceLow determines open Source
	SourceLow = Source("low")
	// SourceClose determines open Source
	SourceClose = Source("close")
	// SourceVolume determines open Source
	SourceVolume = Source("volume")

	// SourceOpenHigh determines oh2 Source
	SourceOpenHigh = Source("oh2")
	// SourceOpenLow determines ol2 Source
	SourceOpenLow = Source("ol2")
	// SourceOpenClose determines oc2 Source
	SourceOpenClose = Source("oc2")
	// SourceHighLow determines hl2 Source
	SourceHighLow = Source("hl2")
	// SourceHighClose determines hc2 Source
	SourceHighClose = Source("hc2")
	// SourceLowClose determines lc2 Source
	SourceLowClose = Source("lc2")

	// SourceOpenHighLow determines ohl3 Source
	SourceOpenHighLow = Source("ohl3")
	// SourceOpenHighClose determines ohc3 Source
	SourceOpenHighClose = Source("ohc3")
	// SourceOpenLowClose determines olc3 Source
	SourceOpenLowClose = Source("olc3")
	// SourceHighLowClose determines hlc3 Source
	SourceHighLowClose = Source("hlc3")

	// SourceOpenHighLowClose determines ohlc4 Source
	SourceOpenHighLowClose = Source("ohlc4")

	// PositionBuy determines buy PositionType
	PositionBuy = PositionType("Buy")
	// PositionSell determines sell PositionType
	PositionSell = PositionType("Sell")

	// TradeStatusOpen determines open TradeStatus
	TradeStatusOpen = TradeStatus("Open")
	// TradeStatusClose determines close TradeStatus
	TradeStatusClose = TradeStatus("Close")

	// ExitCauseStopLossTriggered determines stop loss triggered on trade.
	ExitCauseStopLossTriggered = ExitCause("Stop loss")
	// ExitCauseTakeProfitTriggered determines take profit triggered on trade.
	ExitCauseTakeProfitTriggered = ExitCause("Take profit")
	// ExitCauseMarket determines trade closed by market.
	ExitCauseMarket = ExitCause("Market")
)
View Source
const (
	REDIS_KEY_PREFIX     = "holiday"      // The prefix for all keys.
	REDIS_TIMESTAMPS_KEY = "%s:timestamp" // The key for the timestamps.
	REDIS_KEY_FORMAT     = "%s:%s:%s:%d"  // The format of the redis key. The first parameter is the prefix, the second is the symbol, the third is the interval and the fourth is the timestamp.
)

Variables

View Source
var (
	// ErrInvalidCandleData occurs on Candle operations.
	ErrInvalidCandleData = errors.New("invalid data provided for candle").(CandleError)
	// ErrNotEnoughCandles occurs when there is not enough Candle in Quota to operate.
	ErrNotEnoughCandles = errors.New("not enough candles to operate").(CandleError)
)

Functions

func NewCandle

func NewCandle(open, high, low, close, volume float64, symbol string, barSize okex.BarSize, openTime, closeTime time.Time, previous, next *Candle) (candle *Candle, err CandleError)

NewCandle returns a pointer to a fresh candle with provided data.

func SerializeCandle

func SerializeCandle(c *Candle) (data string, err error)

SerializeCandle serializes the given candle.

func SerilizeQuota

func SerilizeQuota(q *Quota) (data string, err error)

SerializeQuota serializes the given quota.

Types

type Candle

type Candle struct {
	Open       float64                  `json:"open"`
	High       float64                  `json:"high"`
	Low        float64                  `json:"low"`
	Close      float64                  `json:"close"`
	Volume     float64                  `json:"volume"`
	Score      float64                  `json:"score"`
	Symbol     string                   `json:"symbol"`
	BarSize    okex.BarSize             `json:"barSize"`
	Indicators map[IndicatorTag]float64 `json:"indicators"`
	OpenTime   time.Time                `json:"open_time"`
	CloseTime  time.Time                `json:"close_time"`
	Next       *Candle                  `json:"-"`
	Previous   *Candle                  `json:"-"`
}

Candle is the main structure which contains a group of useful candlestick data.

func DeserializeCandle

func DeserializeCandle(data string) (c *Candle, err error)

DeserializeCandle deserializes the given data.

func (*Candle) AddIndicator

func (c *Candle) AddIndicator(tag IndicatorTag, value float64)

AddIndicator adds unimplementedIndicator value by the given name into the candle.

func (*Candle) CrossedOver

func (c *Candle) CrossedOver(fastSource, slowSource Source) bool

CrossedOver checks if fast source crossed over the slow source.

fastSource > slowSource prevFastSource <= prevSlowSource

func (*Candle) CrossedUnder

func (c *Candle) CrossedUnder(fastSource, slowSource Source) bool

CrossedUnder checks if fast source crossed under the slow source.

fastSource < slowSource prevFastSource >= prevSlowSource

func (*Candle) Csv

func (c *Candle) Csv(indicators ...IndicatorTag) (csv string)

Csv returns csv row of the candle.

func (*Candle) Get

func (c *Candle) Get(source Source) (float64, bool)

Get Retrieves the value of the target field on the candle.

func (*Candle) IsAbove

func (c *Candle) IsAbove(source Source) bool

IsAbove checks if candle is above of the source.

O,H,L,C > source

func (*Candle) IsBearish

func (c *Candle) IsBearish() bool

IsBearish checks if candle is bearish.

O < C,

func (*Candle) IsBelow

func (c *Candle) IsBelow(source Source) bool

IsBelow checks if candle is below of the source.

O,H,L,C < source

func (*Candle) IsBullish

func (c *Candle) IsBullish() bool

IsBullish checks if candle is bullish.

O > C,

func (*Candle) IsMiddle

func (c *Candle) IsMiddle(source Source) bool

IsMiddle checks if source is passed through middle of the candle.

O >= source H > source L < source C <= source

func (*Candle) TouchedDown

func (c *Candle) TouchedDown(source Source) bool

TouchedDown checks if candle closed above the source but the Low shadow touched the source.

O,H,C > source L <= source

func (*Candle) TouchedUp

func (c *Candle) TouchedUp(source Source) bool

TouchedUp checks if candle close above the source but the High shadow touched the source.

H >= source O,L,C < source

type CandleChannel

type CandleChannel chan *Candle

CandleChannel to pass Candle through it

type CandleError

type CandleError error

CandleError will occur on Candle's operations

type EnterChannel

type EnterChannel chan EnterSignal

EnterChannel to pass EnterSignal through it

type EnterSignal

type EnterSignal struct {
	Symbol     string
	Score      float64
	Quote      float64
	TakeProfit float64
	Stoploss   float64
	Cause      string
	Candle     Candle
}

EnterSignal is a signal for entering into positions

type ExitCause

type ExitCause string

ExitCause indicates why the position has been closed for

type ExitChannel

type ExitChannel chan ExitSignal

ExitChannel to pass ExitSignal through it

type ExitSignal

type ExitSignal struct {
	Trade  *Trade
	Candle *Candle
	Cause  ExitCause
}

ExitSignal is a signal for exiting from positions

type InMemoryStorage

type InMemoryStorage struct {
	Q *Quota
	// contains filtered or unexported fields
}

InMemoryStorage is an in-memory implementation of the Storage interface.

func NewInMemoryStorage

func NewInMemoryStorage(symbol string, interval time.Duration) *InMemoryStorage

NewInMemoryStorage creates a new InMemoryStorage instance.

func (*InMemoryStorage) All

func (s *InMemoryStorage) All() (*Quota, error)

All returns all the data in the storage.

func (*InMemoryStorage) Close

func (s *InMemoryStorage) Close() error

Close closes the storage.

func (*InMemoryStorage) Delete

func (s *InMemoryStorage) Delete(c *Candle) error

Delete deletes the value for the given key.

func (*InMemoryStorage) Get

func (s *InMemoryStorage) Get(openTime time.Time) (*Candle, error)

Get returns the value for the given key.

func (*InMemoryStorage) GetByIndex

func (s *InMemoryStorage) GetByIndex(index int) (*Candle, error)

GetByIndex retrieves candle from the storage by index.

func (*InMemoryStorage) PersistOlds

func (s *InMemoryStorage) PersistOlds(persist Storage, size int) error

PersistOlds will store the old candles into a persistance storage and remove them from the quota.

func (*InMemoryStorage) Put

func (s *InMemoryStorage) Put(c ...*Candle) error

Put stores the given value for the given key.

func (*InMemoryStorage) Update

func (s *InMemoryStorage) Update(c ...*Candle) error

Update updates the value for the given key.

type Indicator

type Indicator interface {
	Add(q *Quota, c *Candle) (ok bool)
	Is(tag IndicatorTag) bool
}

Indicator indicates how an UnimplementedIndicator should be implemented.

type IndicatorTag

type IndicatorTag string

IndicatorTag specifies each UnimplementedIndicator for others.

type MarketType

type MarketType string

MarketType indicates the market type

type PositionType

type PositionType string

PositionType indicates position direction

type Quota

type Quota []*Candle

Quota is the group of candles and make time-series.

func DeserializeQuota

func DeserializeQuota(data string) (q *Quota, err error)

DeserializeQuota deserializes the given data.

func NewQuoteFromCsv

func NewQuoteFromCsv(filename string, symbol string, barSize okex.BarSize) (*Quota, error)

NewQuoteFromCsv reads quote from csv file.

func (*Quota) AddIndicator

func (q *Quota) AddIndicator(tag IndicatorTag, values []float64) error

AddIndicator adds unimplementedIndicator values by the given tag into the quota.

func (*Quota) BarSize

func (q *Quota) BarSize() okex.BarSize

BarSize will return the okex.BarSize of candles.

func (*Quota) Csv

func (q *Quota) Csv(indicators ...IndicatorTag) (csv string)

Csv returns csv formatted string of whole quote.

func (*Quota) Find

func (q *Quota) Find(timestamp int64) (*Candle, int)

Find searches for a candle, and its index among Quota by its symbol and provided timestamp.

func (*Quota) Get

func (q *Quota) Get(source Source) []float64

Get retrieves value of target field on all candles.

func (*Quota) IndicatorTags

func (q *Quota) IndicatorTags() []IndicatorTag

IndicatorTags returns a list of indicators used in quota.

func (*Quota) Merge

func (q *Quota) Merge(target *Quota)

Merge target quota into the current quota, rewrite duplicates and sort it.

func (*Quota) ScoreByAbove

func (q *Quota) ScoreByAbove(source Source, score float64)

ScoreByAbove scores candles by checking if candles are above source.

func (*Quota) ScoreByBands

func (q *Quota) ScoreByBands(source Source, score float64)

ScoreByBands scores candles by checking touching and turning back into the band.

func (*Quota) ScoreByBearish

func (q *Quota) ScoreByBearish(score float64)

ScoreByBearish scores candles by if candle is bearish

func (*Quota) ScoreByBelow

func (q *Quota) ScoreByBelow(source Source, score float64)

ScoreByBelow scores candles by checking if candles are below source.

func (*Quota) ScoreByBullish

func (q *Quota) ScoreByBullish(score float64)

ScoreByBullish scores candles by checking if candles are bullish.

func (*Quota) ScoreByCross

func (q *Quota) ScoreByCross(fastSource, slowSource Source, score float64)

ScoreByCross scores candles by checking sources both crosses over and under condition on each of them.

func (*Quota) ScoreByCrossOver

func (q *Quota) ScoreByCrossOver(fastSource, slowSource Source, score float64)

ScoreByCrossOver scores candles by checking sources cross over condition on each of them.

func (*Quota) ScoreByCrossUnder

func (q *Quota) ScoreByCrossUnder(fastSource, slowSource Source, score float64)

ScoreByCrossUnder scores candles by checking sources cross under condition on each of them.

func (*Quota) ScoreByMiddle

func (q *Quota) ScoreByMiddle(source Source, score float64)

ScoreByMiddle scores candles by checking if candles are middle of the source.

func (*Quota) ScoreBySupportResistance

func (q *Quota) ScoreBySupportResistance(source Source, score float64)

ScoreBySupportResistance scores candles by checking support/resistance line reaction.

func (*Quota) ScoreByTouchDown

func (q *Quota) ScoreByTouchDown(source Source, score float64)

ScoreByTouchDown scores candles by checking if candles are touching down source.

func (*Quota) ScoreByTouchUp

func (q *Quota) ScoreByTouchUp(source Source, score float64)

ScoreByTouchUp scores candles by checking if candles are touching up source.

func (*Quota) Sort

func (q *Quota) Sort()

Sort runs through the quota and reorder candles by the open time.

func (*Quota) Symbol

func (q *Quota) Symbol() string

Symbol will return the symbol of candles.

func (*Quota) Sync

func (q *Quota) Sync(open, high, low, close, volume float64, openTime, closeTime time.Time, sCandle ...*Candle) (candle *Candle, err CandleError)

Sync searches the quota for provided candle and update it if it exists, otherwise, it will append to end of the quota.

If you want to update a candle directly then pass sCandle.

func (*Quota) WriteToCsv

func (q *Quota) WriteToCsv(filename string, indicators ...IndicatorTag) error

WriteToCsv writes down whole quote into a csv file.

type RedisStorage

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

RedisStorage is a storage implementation that uses Redis as a backend.

func NewRedisStorage

func NewRedisStorage(symbol string, interval time.Duration, config map[string]interface{}, ctx context.Context) *RedisStorage

NewRedisStorage creates a new RedisStorage instance.

func (*RedisStorage) All

func (s *RedisStorage) All() (*Quota, error)

Implemenet the Storage interface for RedisStorage. All returns all the values.

func (*RedisStorage) Close

func (s *RedisStorage) Close() error

Close closes the RedisStorage instance.

func (*RedisStorage) Delete

func (s *RedisStorage) Delete(c *Candle) error

Delete removes the value for the given key.

func (*RedisStorage) Get

func (s *RedisStorage) Get(openTime time.Time) (*Candle, error)

Get retrieves the value for the given key.

func (*RedisStorage) GetByIndex

func (s *RedisStorage) GetByIndex(index int) (*Candle, error)

GetByIndex retrieves candle from the storage by index.

func (*RedisStorage) PersistOlds

func (s *RedisStorage) PersistOlds(persist Storage, size int) error

PersistOlds will store the old candles into a persistance storage and remove them from the quota.

func (*RedisStorage) Put

func (s *RedisStorage) Put(c ...*Candle) error

Put stores the value for the given key.

func (*RedisStorage) Update

func (s *RedisStorage) Update(candle ...*Candle) error

Update updates the value for the given key.

type Source

type Source string

Source is a target field on candle.

type SourceError

type SourceError error

SourceError will occur on Source's operations

type Storage

type Storage interface {
	// All returns all the candle in the storage.
	All() (*Quota, error)

	// Get retrieves candle from the storage.
	Get(openTime time.Time) (*Candle, error)

	// GetByIndex retrieves candle from the storage by index.
	GetByIndex(index int) (*Candle, error)

	// Put stores the given candle in the storage.
	Put(candle ...*Candle) error

	// Update updates candle in the storage.
	Update(candle ...*Candle) error

	// Delete removes the candle from the storage.
	Delete(candle *Candle) error

	// Close closes the storage.
	Close() error

	// PersistOlds will store the old candles into a persistance storage and remove them from the quota.
	PersistOlds(persist Storage, size int) error
}

Storage is an interface for storing and retrieving candles.

type Trade

type Trade struct {
	ID                string
	Coin              string
	Base              string
	Driver            string
	Quote             float64
	Size              float64
	Entry             float64
	Exit              float64
	ProfitPrice       float64
	ProfitPercentage  float64
	StopLossPercent   float64
	StopLossPrice     float64
	TakeProfitPercent float64
	TakeProfitPrice   float64
	Position          PositionType
	Status            TradeStatus
	OpenCandle        *Candle
	CloseCandle       *Candle
	OpenAt            *time.Time
	CloseAt           *time.Time
}

Trade represents a real world trade

func NewTrade

func NewTrade(id, driver, coin, base string, position PositionType, quote, entry, sl, tp float64, openCandle *Candle) *Trade

NewTrade returns a pointer to a fresh trade.

func (*Trade) Close

func (t *Trade) Close(price float64, candle *Candle)

Close closes an active trade.

func (Trade) String

func (t Trade) String() string

String Stringify the trade.

type TradeError

type TradeError error

TradeError will occur on Trade's operations

type TradeStatus

type TradeStatus string

TradeStatus indicates the trade status

type Trader

type Trader interface {
	Open(coin, base string, position PositionType, quote, entry, sl, tp float64, openCandle *Candle) *Trade
	Close(id string, exit float64, closeCandle *Candle)
	Start() TradeError
	EntryWatcher()
	ExitWatcher()
	CloseWatcher()
}

Trader determines how a trader should be implemented.

type Trades

type Trades []*Trade

Trades is just a group of Trade just an in memory storage

func (Trades) Find

func (t Trades) Find(id string) (*Trade, int)

Find searches for a trade, and its index among all trades.

type TradesChannel

type TradesChannel chan *Trade

TradesChannel to pass Trade through it

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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