kline

package
v1.0.20 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HundredMilliseconds  = Interval(100 * time.Millisecond)
	ThousandMilliseconds = 10 * HundredMilliseconds
	TenSecond            = Interval(10 * time.Second)
	FifteenSecond        = Interval(15 * time.Second)
	ThirtySecond         = 2 * FifteenSecond
	OneMin               = Interval(time.Minute)
	ThreeMin             = 3 * OneMin
	FiveMin              = 5 * OneMin
	TenMin               = 10 * OneMin
	FifteenMin           = 15 * OneMin
	ThirtyMin            = 30 * OneMin
	OneHour              = Interval(time.Hour)
	TwoHour              = 2 * OneHour
	ThreeHour            = 3 * OneHour
	FourHour             = 4 * OneHour
	SixHour              = 6 * OneHour
	SevenHour            = 7 * OneHour
	EightHour            = 8 * OneHour
	TwelveHour           = 12 * OneHour
	OneDay               = 24 * OneHour
	TwoDay               = 2 * OneDay
	ThreeDay             = 3 * OneDay
	SevenDay             = 7 * OneDay
	FifteenDay           = 15 * OneDay
	OneWeek              = 7 * OneDay
	TwoWeek              = 2 * OneWeek
	ThreeWeek            = 3 * OneWeek
	OneMonth             = 30 * OneDay
	ThreeMonth           = 90 * OneDay
	SixMonth             = 2 * ThreeMonth
	NineMonth            = 3 * ThreeMonth
	OneYear              = 365 * OneDay
	FiveDay              = 5 * OneDay
)

Consts here define basic time intervals

Variables

View Source
var (
	// ErrRequestExceedsExchangeLimits locale for exceeding rate limits message
	ErrRequestExceedsExchangeLimits = errors.New("request will exceed exchange limits, please reduce start-end time window or use GetHistoricCandlesExtended")
	// ErrUnsupportedInterval returns when the provided interval is not supported by an exchange
	ErrUnsupportedInterval = errors.New("interval unsupported by exchange")
	// ErrCanOnlyUpscaleCandles returns when attempting to upscale candles
	ErrCanOnlyUpscaleCandles = errors.New("interval must be a longer duration to scale")
	// ErrWholeNumberScaling returns when old interval data cannot neatly fit into new interval size
	ErrWholeNumberScaling = errors.New("old interval must scale properly into new candle")
	// ErrNotFoundAtTime returned when looking up a candle at a specific time
	ErrNotFoundAtTime = errors.New("candle not found at time")
	// ErrItemNotEqual returns when comparison between two kline items fail
	ErrItemNotEqual = errors.New("kline item not equal")
	// ErrItemUnderlyingNotEqual returns when the underlying pair is not equal
	ErrItemUnderlyingNotEqual = errors.New("kline item underlying pair not equal")
	// ErrValidatingParams defines an error when the kline params are either not
	// enabled or are invalid.
	ErrValidatingParams = errors.New("kline param(s) are invalid")
	// ErrInvalidInterval defines when an interval is invalid e.g. interval <= 0
	ErrInvalidInterval = errors.New("invalid/unset interval")
	// ErrCannotConstructInterval defines an error when an interval cannot be
	// constructed from a list of support intervals.
	ErrCannotConstructInterval = errors.New("cannot construct required interval from supported intervals")
	// ErrInsufficientCandleData defines an error when you have a candle that
	// requires multiple candles to generate.
	ErrInsufficientCandleData = errors.New("insufficient candle data to generate new candle")
	// ErrRequestExceedsMaxLookback defines an error for when you cannot look
	// back further than what is allowed.
	ErrRequestExceedsMaxLookback = errors.New("the requested time window exceeds the maximum lookback period available in the historical data, please reduce window between start and end date of your request")

	// SupportedIntervals is a list of all supported intervals
	SupportedIntervals = []Interval{
		HundredMilliseconds,
		ThousandMilliseconds,
		TenSecond,
		FifteenSecond,
		OneMin,
		ThreeMin,
		FiveMin,
		TenMin,
		FifteenMin,
		ThirtyMin,
		OneHour,
		TwoHour,
		ThreeHour,
		FourHour,
		SixHour,
		SevenHour,
		EightHour,
		TwelveHour,
		OneDay,
		ThreeDay,
		FiveDay,
		SevenDay,
		FifteenDay,
		OneWeek,
		TwoWeek,
		OneMonth,
		ThreeMonth,
		SixMonth,
		OneYear,
		ThreeMonth,
		SixMonth,
	}
)
View Source
var (
	// ErrUnsetName is an error for when the exchange name is not set
	ErrUnsetName = errors.New("unset exchange name")
	// ErrNoTimeSeriesDataToConvert is returned when no data can be processed
	ErrNoTimeSeriesDataToConvert = errors.New("no candle data returned to process")

	// PartialCandle is string flag for when the most recent candle is partially
	// formed.
	PartialCandle = "Partial Candle"
)

Functions

func StoreInDatabase

func StoreInDatabase(in *Item, force bool) (uint64, error)

StoreInDatabase returns Item from database seeded data

func TotalCandlesPerInterval

func TotalCandlesPerInterval(start, end time.Time, interval Interval) int64

TotalCandlesPerInterval returns the total number of candle intervals between the start and end date

Types

type Bollinger

type Bollinger struct {
	Upper  []float64
	Middle []float64
	Lower  []float64
}

Bollinger defines a return type for the bollinger bands

type Candle

type Candle struct {
	Time             time.Time
	Open             float64
	High             float64
	Low              float64
	Close            float64
	Volume           float64
	ValidationIssues string
}

Candle holds historic rate information.

func LoadFromGCTScriptCSV

func LoadFromGCTScriptCSV(file string) (out []Candle, errRet error)

LoadFromGCTScriptCSV loads kline data from a CSV file

func (*Candle) GetAveragePrice

func (c *Candle) GetAveragePrice() float64

GetAveragePrice returns the average price from the open, high, low and close

func (*Candle) GetTypicalPrice

func (c *Candle) GetTypicalPrice() float64

GetTypicalPrice returns the typical average price from the high, low and close values.

type ExchangeCapabilitiesEnabled

type ExchangeCapabilitiesEnabled struct {
	// Intervals defines whether the exchange supports interval kline requests.
	Intervals ExchangeIntervals
	// GlobalResultLimit is the maximum amount of candles that can be returned
	// across all intervals. This is used to determine if a request will exceed
	// the exchange limits. Indivudal interval limits are stored in the
	// ExchangeIntervals struct. If this is set to 0, it will be ignored.
	GlobalResultLimit uint32
}

ExchangeCapabilitiesEnabled all kline related exchange enabled options

func (*ExchangeCapabilitiesEnabled) GetIntervalResultLimit

func (e *ExchangeCapabilitiesEnabled) GetIntervalResultLimit(interval Interval) (int64, error)

GetIntervalResultLimit returns the maximum amount of candles that can be returned for a specific interval. If the individual interval limit is not set, it will be ignored and the global result limit will be returned.

type ExchangeCapabilitiesSupported

type ExchangeCapabilitiesSupported struct {
	Intervals  bool
	DateRanges bool
}

ExchangeCapabilitiesSupported all kline related exchange supported options

type ExchangeIntervals

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

ExchangeIntervals stores the supported intervals in an optimized lookup table with a supplementary aligned retrieval list

func DeployExchangeIntervals

func DeployExchangeIntervals(enabled ...IntervalCapacity) ExchangeIntervals

DeployExchangeIntervals aligns and stores supported intervals for an exchange for future matching.

func (*ExchangeIntervals) Construct

func (e *ExchangeIntervals) Construct(required Interval) (Interval, error)

Construct fetches supported interval that can construct the required interval e.g. 1 hour interval candles can be made from 2 * 30 minute interval candles.

func (*ExchangeIntervals) ExchangeSupported

func (e *ExchangeIntervals) ExchangeSupported(in Interval) bool

ExchangeSupported returns if the exchange directly supports the interval. In future this might be able to be deprecated because we can construct custom intervals from the supported list.

type ExtendedRequest

type ExtendedRequest struct {
	*Request
	RangeHolder *IntervalRangeHolder
}

ExtendedRequest used in extended functionality for when candles requested exceed exchange limits and require multiple requests.

func (*ExtendedRequest) ProcessResponse

func (r *ExtendedRequest) ProcessResponse(timeSeries []Candle) (*Item, error)

ProcessResponse converts time series candles into a kline.Item type. This will auto convert from a lower to higher time series if applicable.

func (*ExtendedRequest) Size

func (r *ExtendedRequest) Size() int

Size returns the max length of return for pre-allocation.

type Interval

type Interval time.Duration

Interval type for kline Interval usage

func (Interval) Duration

func (i Interval) Duration() time.Duration

Duration returns interval casted as time.Duration for compatibility

func (Interval) IntervalsPerYear

func (i Interval) IntervalsPerYear() float64

IntervalsPerYear helps determine the number of intervals in a year used in CAGR calculation to know the amount of time of an interval in a year

func (Interval) MarshalText

func (i Interval) MarshalText() ([]byte, error)

MarshalText implements the TextMarshaler interface for Intervals

func (Interval) Short

func (i Interval) Short() string

Short returns short string version of interval

func (Interval) String

func (i Interval) String() string

String returns numeric string

func (*Interval) UnmarshalJSON

func (i *Interval) UnmarshalJSON(text []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Intervals It does not validate the duration is aligned, only that it is a parsable duration

func (Interval) Word

func (i Interval) Word() string

Word returns text version of Interval

type IntervalCapacity

type IntervalCapacity struct {
	Interval Interval
	Capacity int64
}

IntervalCapacity is used to store the interval and capacity for a candle return

type IntervalData

type IntervalData struct {
	Start   IntervalTime
	End     IntervalTime
	HasData bool
}

IntervalData is used to monitor which candles contain data to determine if any data is missing

type IntervalRange

type IntervalRange struct {
	Start     IntervalTime
	End       IntervalTime
	Intervals []IntervalData
}

IntervalRange is a subset of candles based on exchange API request limits

type IntervalRangeHolder

type IntervalRangeHolder struct {
	Start  IntervalTime
	End    IntervalTime
	Ranges []IntervalRange
	Limit  int
}

IntervalRangeHolder holds the entire range of intervals and the start end dates of everything

func CalculateCandleDateRanges

func CalculateCandleDateRanges(start, end time.Time, interval Interval, limit uint32) (*IntervalRangeHolder, error)

CalculateCandleDateRanges will calculate the expected candle data in intervals in a date range If an API is limited in the amount of candles it can make in a request, it will automatically separate ranges into the limit

func (*IntervalRangeHolder) DataSummary

func (h *IntervalRangeHolder) DataSummary(includeHasData bool) []string

DataSummary returns a summary of a data range to highlight where data is missing

func (*IntervalRangeHolder) HasDataAtDate

func (h *IntervalRangeHolder) HasDataAtDate(t time.Time) bool

HasDataAtDate determines whether a there is any data at a set date inside the existing limits

func (*IntervalRangeHolder) SetHasDataFromCandles

func (h *IntervalRangeHolder) SetHasDataFromCandles(incoming []Candle) error

SetHasDataFromCandles will calculate whether there is data in each candle allowing any missing data from an API request to be highlighted

type IntervalTime

type IntervalTime struct {
	Time  time.Time
	Ticks int64
}

IntervalTime benchmarks demonstrate, see BenchmarkJustifyIntervalTimeStoringUnixValues1 && BenchmarkJustifyIntervalTimeStoringUnixValues2

func CreateIntervalTime

func CreateIntervalTime(tt time.Time) IntervalTime

CreateIntervalTime is a simple helper function to set the time twice

func (*IntervalTime) Equal

func (i *IntervalTime) Equal(tt time.Time) bool

Equal allows for easier unix comparison

type Item

type Item struct {
	Exchange        string
	Pair            currency.Pair
	UnderlyingPair  currency.Pair
	Asset           asset.Item
	Interval        Interval
	Candles         []Candle
	SourceJobID     uuid.UUID
	ValidationJobID uuid.UUID
}

Item holds all the relevant information for internal kline elements

func CreateKline

func CreateKline(trades []order.TradeHistory, interval Interval, pair currency.Pair, a asset.Item, exchName string) (*Item, error)

CreateKline creates candles out of trade history data for a set time interval

func LoadFromDatabase

func LoadFromDatabase(exchange string, pair currency.Pair, a asset.Item, interval Interval, start, end time.Time) (*Item, error)

LoadFromDatabase returns Item from database seeded data

func (*Item) ConvertToNewInterval

func (k *Item) ConvertToNewInterval(newInterval Interval) (*Item, error)

ConvertToNewInterval allows the scaling of candles to larger candles e.g. Convert OneDay candles to ThreeDay candles, if there are adequate candles. Incomplete candles are NOT converted e.g. 4 OneDay candles will convert to one ThreeDay candle, skipping the fourth.

func (*Item) EqualSource

func (k *Item) EqualSource(i *Item) error

EqualSource checks whether two sets of candles come from the same data source

func (*Item) FormatDates

func (k *Item) FormatDates()

FormatDates converts all dates to UTC time

func (*Item) GetAverageTrueRange

func (k *Item) GetAverageTrueRange(period int64) ([]float64, error)

GetAverageTrueRange returns the Average True Range for the given period.

func (*Item) GetBollingerBands

func (k *Item) GetBollingerBands(period int64, nbDevUp, nbDevDown float64, m indicators.MaType) (*Bollinger, error)

GetBollingerBands returns Bollinger Bands for the given period.

func (*Item) GetClosePriceAtTime

func (k *Item) GetClosePriceAtTime(t time.Time) (float64, error)

GetClosePriceAtTime returns the close price of a candle at a given time

func (*Item) GetCorrelationCoefficient

func (k *Item) GetCorrelationCoefficient(other *Item, period int64) ([]float64, error)

GetCorrelationCoefficient returns GetCorrelation Coefficient against another candle data set for the given period.

func (*Item) GetExponentialMovingAverageOnClose

func (k *Item) GetExponentialMovingAverageOnClose(period int64) ([]float64, error)

GetExponentialMovingAverageOnClose returns the EMA on the close price set for the given period.

func (*Item) GetMoneyFlowIndex

func (k *Item) GetMoneyFlowIndex(period int64) ([]float64, error)

GetMoneyFlowIndex returns Money Flow Index for the given period.

func (*Item) GetMovingAverageConvergenceDivergenceOnClose

func (k *Item) GetMovingAverageConvergenceDivergenceOnClose(fast, slow, signal int64) (*MACD, error)

GetMovingAverageConvergenceDivergenceOnClose returns the MACD (macd, signal period vals, histogram) for the given price set and the parameters fast, slow signal time periods.

func (*Item) GetOHLC

func (k *Item) GetOHLC() *OHLC

GetOHLC returns the entire subset of candles as a friendly type for gct technical analysis usage.

func (*Item) GetOnBalanceVolume

func (k *Item) GetOnBalanceVolume() ([]float64, error)

GetOnBalanceVolume returns On Balance Volume.

func (*Item) GetRelativeStrengthIndexOnClose

func (k *Item) GetRelativeStrengthIndexOnClose(period int64) ([]float64, error)

GetRelativeStrengthIndexOnClose returns the relative strength index from the given price set and period.

func (*Item) GetSimpleMovingAverageOnClose

func (k *Item) GetSimpleMovingAverageOnClose(period int64) ([]float64, error)

GetSimpleMovingAverageOnClose returns MA the close prices set for the given period.

func (*Item) GetTWAP

func (k *Item) GetTWAP() (float64, error)

GetTWAP returns the time weighted average price for the specified period. NOTE: This assumes the most recent price is at the tail end of the slice. Based off: https://blog.quantinsti.com/twap/ Only returns one item as all other items are just the average price.

func (*Item) GetVWAPs

func (k *Item) GetVWAPs() ([]float64, error)

GetVWAPs returns the Volume Weighted Averages prices which are the cumulative average price with respect to the volume. NOTE: This assumes candles are sorted by time Based off: https://blog.quantinsti.com/vwap-strategy/

func (*Item) RemoveDuplicates

func (k *Item) RemoveDuplicates()

RemoveDuplicates removes any duplicate candles. NOTE: Filter-in-place is used in this function for optimization and to keep the slice reference pointer the same, if changed ExtendedRequest ConvertCandles functionality will break.

func (*Item) RemoveOutsideRange

func (k *Item) RemoveOutsideRange(start, end time.Time)

RemoveOutsideRange removes any candles outside the start and end date. NOTE: Filter-in-place is used in this function for optimization and to keep the slice reference pointer the same, if changed ExtendedRequest ConvertCandles functionality will break.

func (*Item) SortCandlesByTimestamp

func (k *Item) SortCandlesByTimestamp(desc bool)

SortCandlesByTimestamp sorts candles by timestamp

type MACD

type MACD struct {
	Results    []float64
	SignalVals []float64
	Histogram  []float64
}

MACD defines MACD values

type OHLC

type OHLC struct {
	Open   []float64
	High   []float64
	Low    []float64
	Close  []float64
	Volume []float64
}

OHLC is a connector for technical analysis usage

func (*OHLC) GetAveragePrice

func (o *OHLC) GetAveragePrice(element int) (float64, error)

GetAveragePrice returns the average price from the open, high, low and close

func (*OHLC) GetAverageTrueRange

func (o *OHLC) GetAverageTrueRange(period int64) ([]float64, error)

GetAverageTrueRange returns the Average True Range for the given period.

func (*OHLC) GetBollingerBands

func (o *OHLC) GetBollingerBands(period int64, nbDevUp, nbDevDown float64, m indicators.MaType) (*Bollinger, error)

GetBollingerBands returns Bollinger Bands for the given period.

func (*OHLC) GetCorrelationCoefficient

func (o *OHLC) GetCorrelationCoefficient(other *OHLC, period int64) ([]float64, error)

GetCorrelationCoefficient returns GetCorrelation Coefficient against another candle data set for the given period.

func (*OHLC) GetExponentialMovingAverage

func (o *OHLC) GetExponentialMovingAverage(option []float64, period int64) ([]float64, error)

GetExponentialMovingAverage returns the EMA on the supplied price set for the given period.

func (*OHLC) GetMoneyFlowIndex

func (o *OHLC) GetMoneyFlowIndex(period int64) ([]float64, error)

GetMoneyFlowIndex returns Money Flow Index for the given period.

func (*OHLC) GetMovingAverageConvergenceDivergence

func (o *OHLC) GetMovingAverageConvergenceDivergence(option []float64, fast, slow, signal int64) (*MACD, error)

GetMovingAverageConvergenceDivergence returns the MACD (macd, signal period vals, histogram) for the given price set and the parameters fast, slow signal time periods.

func (*OHLC) GetOnBalanceVolume

func (o *OHLC) GetOnBalanceVolume() ([]float64, error)

GetOnBalanceVolume returns On Balance Volume.

func (*OHLC) GetRelativeStrengthIndex

func (o *OHLC) GetRelativeStrengthIndex(option []float64, period int64) ([]float64, error)

GetRelativeStrengthIndex returns the relative strength index from the given price set and period.

func (*OHLC) GetSimpleMovingAverage

func (o *OHLC) GetSimpleMovingAverage(option []float64, period int64) ([]float64, error)

GetSimpleMovingAverage returns MA for the supplied price set for the given period.

func (*OHLC) GetTWAP

func (o *OHLC) GetTWAP() (float64, error)

GetTWAP returns the time weighted average price for the specified period.

func (*OHLC) GetTypicalPrice

func (o *OHLC) GetTypicalPrice(element int) (float64, error)

GetTypicalPrice returns the typical average price from the high, low and close values.

func (*OHLC) GetVWAPs

func (o *OHLC) GetVWAPs() ([]float64, error)

GetVWAPs returns the Volume Weighted Averages prices which are the cumulative average price with respect to the volume.

type Request

type Request struct {
	// Exchange refers to the exchange name
	Exchange string
	// Pair refers to the currency pair
	Pair currency.Pair
	// RequestFormatted refers to the currency pair formatted by the exchange
	// asset for outbound requests
	RequestFormatted currency.Pair
	// Asset refers to the asset type
	Asset asset.Item
	// ExchangeInterval refers to the interval that is used to construct the
	// client required interval, this will be less than or equal to the client
	// required interval.
	ExchangeInterval Interval
	// ClientRequired refers to the clients' actual required interval
	// needed.
	ClientRequired Interval
	// Start is the start time aligned to UTC and to the Required interval candle
	Start time.Time
	// End is the end time aligned to UTC and to the Required interval candle
	End time.Time
	// PartialCandle defines when a request's end time interval goes beyond
	// current time it potentially has a partially formed candle.
	PartialCandle bool
	// IsExtended denotes whether the candle request is for extended candles
	IsExtended bool
	// ProcessedCandles stores the candles that have been processed, but not converted
	// to the ClientRequiredInterval
	ProcessedCandles []Candle
	// RequestLimit is the potential maximum amount of candles that can be
	// returned
	RequestLimit int64
}

Request is a helper to request and convert time series to a required candle interval.

func CreateKlineRequest

func CreateKlineRequest(name string, pair, formatted currency.Pair, a asset.Item, clientRequired, exchangeInterval Interval, start, end time.Time, specificEndpointLimit int64) (*Request, error)

CreateKlineRequest generates a `Request` type for interval conversions supported by an exchange.

func (*Request) GetRanges

func (r *Request) GetRanges(limit uint32) (*IntervalRangeHolder, error)

GetRanges returns the date ranges for candle intervals broken up over requests

func (*Request) ProcessResponse

func (r *Request) ProcessResponse(timeSeries []Candle) (*Item, error)

ProcessResponse converts time series candles into a kline.Item type. This will auto convert from a lower to higher time series if applicable.

func (*Request) Size

func (r *Request) Size() int

Size returns the max length of return for pre-allocation.

Jump to

Keyboard shortcuts

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