talib4g

package module
v0.0.0-...-5264412 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2018 License: MIT Imports: 9 Imported by: 0

README

Talib4g

Talib4g is a library for technical analysis for Go! It provides a suite of tools and frameworks to analyze financial data and make trading decisions.

Features

  • Basic and advanced technical analysis indicators
  • Profit and trade analysis
  • Strategy building

Installation

$ go get github.com/sdcoffey/talib4g

Quickstart

series := talib4g.NewTimeSeries()

// fetch this from your preferred exchange
dataset := [][]string{
	// Timestamp, Open, Close, High, Low, volume
	{"1234567", "1", "2", "3", "5", "6"},
}

for _, datum := range dataset {
	start, _ := strconv.ParseInt(datum[0], 10, 64)
	period := talib4g.NewTimePeriodD(time.Unix(start, 0), time.Hour*24)

	candle := talib4g.NewCandle(period)
	candle.OpenPrice = big.NewFromString(datum[1])
	candle.ClosePrice = big.NewFromString(datum[2])
	candle.MaxPrice = big.NewFromString(datum[3])
	candle.MinPrice = big.NewFromString(datum[4])

	series.AddCandle(candle)
}

closePrices := talib4g.NewClosePriceIndicator(series)
movingAverage := talib4g.NewEMAIndicator(closePrices, 10) // Create an exponential moving average with a window of 10

fmt.Println(movingAverage.Calculate(0).FormattedString(2))

Creating trading strategies

indicator := talib4g.NewClosePriceIndicator(series)

// record trades on this object
record := talib4g.NewTradingRecord()

entryConstant := talib4g.NewConstantIndicator(30)
exitConstant := talib4g.NewConstantIndicator(10)

// Is satisfied when the price ema moves above 30 and the current position is new
entryRule := talib4g.And(
	talib4g.NewCrossUpIndicatorRule(entryConstant, indicator),
	talib4g.NewPositionNewRule())
	
// Is satisfied when the price ema moves below 10 and the current position is open
exitRule := talib4g.And(
	talib4g.NewCrossDownIndicatorRule(indicator, exitConstant),
	talib4g.NewPositionOpenRule()) 

strategy := talib4g.RuleStrategy{
	UnstablePeriod: 10, // Period before which ShouldEnter and ShouldExit will always return false
	EntryRule:      entryRule,
	ExitRule:       exitRule,
}

strategy.ShouldEnter(0, record) // returns false

Credits

Talib4g is heavily influenced by the great ta4j. Many of the ideas and frameworks in this library owe their genesis to the great work done over there.

License

Talib4g is released under the MIT license. See LICENSE for details.

Documentation

Index

Constants

View Source
const SimpleDateFormat = "01/02/2006"
View Source
const SimpleDateTimeFormat = "01/02/2006T15:04:05"

Variables

This section is empty.

Functions

func Abs

func Abs(b int) int

func Max

func Max(i, j int) int

func Min

func Min(i, j int) int

func Pow

func Pow(i, j int) int

Types

type Analysis

type Analysis interface {
	Analyze(*TradingRecord) float64
}

type AverageProfitAnalysis

type AverageProfitAnalysis string

func (AverageProfitAnalysis) Analyze

func (apa AverageProfitAnalysis) Analyze(record *TradingRecord) float64

type BuyAndHoldAnalysis

type BuyAndHoldAnalysis struct {
	*TimeSeries
	StartingMoney float64
}

func (BuyAndHoldAnalysis) Analyze

func (baha BuyAndHoldAnalysis) Analyze(record *TradingRecord) float64

type Candle

type Candle struct {
	Period     TimePeriod
	OpenPrice  big.Decimal `json:",string"`
	ClosePrice big.Decimal `json:",string"`
	MaxPrice   big.Decimal `json:",string"`
	MinPrice   big.Decimal `json:",string"`
	Volume     big.Decimal `json:",string"`
	TradeCount uint
}

func NewCandle

func NewCandle(period TimePeriod) (c *Candle)

func (*Candle) AddTrade

func (c *Candle) AddTrade(tradeAmount, tradePrice big.Decimal)

func (*Candle) String

func (c *Candle) String() string

type DecreaseRule

type DecreaseRule struct {
	Indicator
}

func (DecreaseRule) IsSatisfied

func (dr DecreaseRule) IsSatisfied(index int, record *TradingRecord) bool

type IncreaseRule

type IncreaseRule struct {
	Indicator
}

func (IncreaseRule) IsSatisfied

func (ir IncreaseRule) IsSatisfied(index int, record *TradingRecord) bool

type Indicator

type Indicator interface {
	Calculate(int) big.Decimal
}

func NewAverageGainsIndicator

func NewAverageGainsIndicator(indicator Indicator, window int) Indicator

Returns a new average gains indicator, which returns the average gains up until that index. @param price indicator should not be > 1 derivation removed from a timeseries, i.e., a ClosePriceIndicator, VolumeIndicator, etc

func NewAverageLossesIndicator

func NewAverageLossesIndicator(indicator Indicator, window int) Indicator

Returns a new average losses indicator, which returns the average losses up until that index. @param price indicator should not be > 1 derivation removed from a timeseries, i.e., a ClosePriceIndicator, VolumeIndicator, etc

func NewClosePriceIndicator

func NewClosePriceIndicator(series *TimeSeries) Indicator

func NewConstantIndicator

func NewConstantIndicator(constant float64) Indicator

func NewCrossIndicator

func NewCrossIndicator(upper, lower Indicator) Indicator

Returns a new CrossIndicator, which, given an index, determines whether a lower indicator has crossed an upper one

func NewCumulativeGainsIndicator

func NewCumulativeGainsIndicator(indicator Indicator, window int) Indicator

func NewCumulativeLossesIndicator

func NewCumulativeLossesIndicator(indicator Indicator, window int) Indicator

func NewDifferenceIndicator

func NewDifferenceIndicator(minuend, subtrahend Indicator) Indicator

func NewEMAIndicator

func NewEMAIndicator(indicator Indicator, window int) Indicator

Returns a new Exponential Moving Average Calculator http://www.investopedia.com/terms/e/ema.asp

func NewFixedIndicator

func NewFixedIndicator(vals ...float64) Indicator

func NewHighPriceIndicator

func NewHighPriceIndicator(series *TimeSeries) Indicator

func NewLowPriceIndicator

func NewLowPriceIndicator(series *TimeSeries) Indicator

func NewMACDHistogramIndicator

func NewMACDHistogramIndicator(macdIdicator Indicator, signalLinewindow int) Indicator

Returns a new Moving Average Convergence-Divergence histogram incicator, the result of which is the macd indicator minus it's @param signalLinewindow EMA http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:macd-histogram

func NewMACDIndicator

func NewMACDIndicator(baseIndicator Indicator, shortwindow, longwindow int) Indicator

Returns a new Moving Average Convergence-Divergence indicator http://www.investopedia.com/terms/m/macd.asp

func NewMeanDeviationIndicator

func NewMeanDeviationIndicator(indicator Indicator, window int) Indicator

Returns a new mean deviation indicator

func NewOpenPriceIndicator

func NewOpenPriceIndicator(series *TimeSeries) Indicator

func NewPercentChangeIndicator

func NewPercentChangeIndicator(indicator Indicator) Indicator

func NewRelativeStrengthIndexIndicator

func NewRelativeStrengthIndexIndicator(indicator Indicator, timeframe int) Indicator

func NewRelativeStrengthIndicator

func NewRelativeStrengthIndicator(indicator Indicator, timeframe int) Indicator

func NewRelativeVigorIndexIndicator

func NewRelativeVigorIndexIndicator(series *TimeSeries) Indicator

func NewRelativeVigorSignalLine

func NewRelativeVigorSignalLine(series *TimeSeries) Indicator

func NewSimpleMovingAverage

func NewSimpleMovingAverage(indicator Indicator, window int) Indicator

func NewTypicalPriceIndicator

func NewTypicalPriceIndicator(series *TimeSeries) Indicator

func NewVolumeIndicator

func NewVolumeIndicator(series *TimeSeries) Indicator

type LogTradesAnalysis

type LogTradesAnalysis struct {
	io.Writer
}

func (LogTradesAnalysis) Analyze

func (lta LogTradesAnalysis) Analyze(record *TradingRecord) float64

type NumTradesAnalysis

type NumTradesAnalysis string

func (NumTradesAnalysis) Analyze

func (nta NumTradesAnalysis) Analyze(record *TradingRecord) float64

type Order

type Order struct {
	Type          OrderSide
	Security      string
	Price         big.Decimal
	Amount        big.Decimal
	ExecutionTime time.Time
	FeePercentage big.Decimal
}

func NewOrder

func NewOrder(orderType OrderSide) (o *Order)

type OrderSide

type OrderSide int
const (
	BUY OrderSide = iota
	SELL
)

type OverIndicatorRule

type OverIndicatorRule struct {
	First  Indicator
	Second Indicator
}

func (OverIndicatorRule) IsSatisfied

func (this OverIndicatorRule) IsSatisfied(index int, record *TradingRecord) bool

type PercentGainAnalysis

type PercentGainAnalysis struct{}

func (PercentGainAnalysis) Analyze

func (pga PercentGainAnalysis) Analyze(record *TradingRecord) float64

type PeriodProfitAnalysis

type PeriodProfitAnalysis time.Duration

func (PeriodProfitAnalysis) Analyze

func (ppa PeriodProfitAnalysis) Analyze(record *TradingRecord) float64

type Position

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

A pair of two Order objects

func NewPosition

func NewPosition(openOrder *Order) (t *Position)

func (*Position) CostBasis

func (p *Position) CostBasis() big.Decimal

func (*Position) Enter

func (p *Position) Enter(order *Order)

func (*Position) EntranceOrder

func (p *Position) EntranceOrder() *Order

func (*Position) Exit

func (p *Position) Exit(order *Order)

func (*Position) ExitOrder

func (p *Position) ExitOrder() *Order

func (*Position) ExitValue

func (p *Position) ExitValue() big.Decimal

func (*Position) IsClosed

func (p *Position) IsClosed() bool

func (*Position) IsLong

func (p *Position) IsLong() bool

func (*Position) IsNew

func (p *Position) IsNew() bool

func (*Position) IsOpen

func (p *Position) IsOpen() bool

func (*Position) IsShort

func (p *Position) IsShort() bool

type ProfitableTradesAnalysis

type ProfitableTradesAnalysis string

func (ProfitableTradesAnalysis) Analyze

func (pta ProfitableTradesAnalysis) Analyze(record *TradingRecord) float64

type Rule

type Rule interface {
	IsSatisfied(index int, record *TradingRecord) bool
}

func And

func And(r1, r2 Rule) Rule

func NewCrossDownIndicatorRule

func NewCrossDownIndicatorRule(upper, lower Indicator) Rule

func NewCrossUpIndicatorRule

func NewCrossUpIndicatorRule(upper, lower Indicator) Rule

func NewPercentChangeRule

func NewPercentChangeRule(indicator Indicator, percent float64) Rule

func NewPositionNewRule

func NewPositionNewRule() Rule

func NewPositionOpenRule

func NewPositionOpenRule() Rule

func NewStopLossRule

func NewStopLossRule(series *TimeSeries, lossTolerance float64) Rule

Returns a new stop loss rule based on a timeseries and a loss tolerance The loss tolerance should be a number between -1 and 1, where negative values represent a loss and vice versa.

func Or

func Or(r1, r2 Rule) Rule

type RuleStrategy

type RuleStrategy struct {
	EntryRule      Rule
	ExitRule       Rule
	UnstablePeriod int
}

func (RuleStrategy) ShouldEnter

func (this RuleStrategy) ShouldEnter(index int, record *TradingRecord) bool

func (RuleStrategy) ShouldExit

func (this RuleStrategy) ShouldExit(index int, record *TradingRecord) bool

type StopLossRule

type StopLossRule struct {
	Indicator
	// contains filtered or unexported fields
}

func (StopLossRule) IsSatisfied

func (slr StopLossRule) IsSatisfied(index int, record *TradingRecord) bool

type Strategy

type Strategy interface {
	ShouldEnter(index int, record *TradingRecord) bool
	ShouldExit(index int, record *TradingRecord) bool
}

type TimePeriod

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

func NewTimePeriod

func NewTimePeriod(start, end time.Time) TimePeriod

func NewTimePeriodD

func NewTimePeriodD(start time.Time, period time.Duration) TimePeriod

func Parse

func Parse(timerange string) (tr TimePeriod, err error)

Support SimpleDateTimeFormat:SimpleDateTimeFormat SimpleDateTimeFormat: (to now) SimpleDateFormat: SimpleDateFormat:SimpleDateFormat

func (TimePeriod) Advance

func (tp TimePeriod) Advance(iterations int) TimePeriod

func (TimePeriod) Format

func (tp TimePeriod) Format(layout string) string

func (TimePeriod) Length

func (tp TimePeriod) Length() time.Duration

func (TimePeriod) Since

func (tp TimePeriod) Since(other TimePeriod) time.Duration

func (TimePeriod) String

func (tp TimePeriod) String() string

type TimeSeries

type TimeSeries struct {
	Candles []*Candle
}

func NewTimeSeries

func NewTimeSeries() (t *TimeSeries)

func RandomTimeSeries

func RandomTimeSeries(size int) *TimeSeries

func (*TimeSeries) AddCandle

func (ts *TimeSeries) AddCandle(candle *Candle) bool

func (*TimeSeries) LastCandle

func (ts *TimeSeries) LastCandle() *Candle

func (*TimeSeries) LastIndex

func (ts *TimeSeries) LastIndex() int

type TotalProfitAnalysis

type TotalProfitAnalysis float64

func (TotalProfitAnalysis) Analyze

func (tps TotalProfitAnalysis) Analyze(record *TradingRecord) float64

type TradingRecord

type TradingRecord struct {
	Trades []*Position
	// contains filtered or unexported fields
}

func NewTradingRecord

func NewTradingRecord() (t *TradingRecord)

func (*TradingRecord) CurrentPosition

func (this *TradingRecord) CurrentPosition() *Position

func (*TradingRecord) Enter

func (this *TradingRecord) Enter(price, amount, feePercentage big.Decimal, security string, time time.Time)

func (*TradingRecord) Exit

func (this *TradingRecord) Exit(price, amount, feePercentage big.Decimal, security string, time time.Time)

func (*TradingRecord) LastTrade

func (this *TradingRecord) LastTrade() *Position

type UnderIndicatorRule

type UnderIndicatorRule struct {
	First  Indicator
	Second Indicator
}

func (UnderIndicatorRule) IsSatisfied

func (this UnderIndicatorRule) IsSatisfied(index int, record *TradingRecord) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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