Documentation
¶
Index ¶
- Constants
- Variables
- func Abs(b int) int
- func CashToShares(assetPrice big.Decimal, cash big.Decimal) big.Decimal
- func Max(i, j int) int
- func Min(i, j int) int
- func Pow(i, j int) int
- type Account
- func (a *Account) Deposit(cash big.Decimal)
- func (a *Account) Equity() big.Decimal
- func (a *Account) ExecuteOrder(order *Order) error
- func (a *Account) ExportSnapshot(period TimePeriod) *AccountSnapshot
- func (a *Account) HasSufficientFunds(order *Order) bool
- func (a *Account) OpenPosition(security string) (*Position, bool)
- func (a *Account) UpdatePrices(prices Pricing)
- func (a *Account) Withdraw(cash big.Decimal) error
- type AccountHistory
- func (ah *AccountHistory) AccountEquityAsIndicator() Indicator
- func (ah *AccountHistory) AnnualizedReturn() big.Decimal
- func (ah *AccountHistory) AnnualizedVolatility() big.Decimal
- func (ah *AccountHistory) ApplySnapshot(accountSnapshot *AccountSnapshot, pricingSnapshot *PricingSnapshot) error
- func (ah *AccountHistory) ExportAnalysisSummaryYaml(filepath string) error
- func (ah *AccountHistory) ExportMonthlyGainsYaml(filepath string) error
- func (ah *AccountHistory) ExportSnapshotsYaml(filepath string) error
- func (ah *AccountHistory) LastIndex() int
- func (ah *AccountHistory) MonthlyPercentGains() []ReturnPeriod
- func (ah *AccountHistory) PercentGain() big.Decimal
- func (ah *AccountHistory) PriceAtIndex(security string, index int) (big.Decimal, bool)
- func (ah *AccountHistory) TotalProfit() big.Decimal
- type AccountSnapshot
- type Allocations
- type Allocator
- type Backtest
- type Candle
- type DecreaseRule
- type DerivativeIndicator
- type IncreaseRule
- type Indicator
- func NewAroonDownIndicator(indicator Indicator, window int) Indicator
- func NewAroonUpIndicator(indicator Indicator, window int) Indicator
- func NewAverageGainsIndicator(indicator Indicator, window int) Indicator
- func NewAverageLossesIndicator(indicator Indicator, window int) Indicator
- func NewAverageTrueRangeIndicator(series *TimeSeries, window int) Indicator
- func NewBinaryFrequencyIndicator(indicators []Indicator, window int, threshold float64) Indicator
- func NewBollingerLowerBandIndicator(indicator Indicator, window int, sigma float64) Indicator
- func NewBollingerUpperBandIndicator(indicator Indicator, window int, sigma float64) Indicator
- func NewCCIIndicator(ts *TimeSeries, window int) Indicator
- func NewClosePriceIndicator(series *TimeSeries) Indicator
- func NewConstantIndicator(constant float64) Indicator
- func NewCumulativeGainsIndicator(indicator Indicator, window int) Indicator
- func NewCumulativeLossesIndicator(indicator Indicator, window int) Indicator
- func NewDifferenceIndicator(minuend, subtrahend Indicator) Indicator
- func NewEMAIndicator(indicator Indicator, window int) Indicator
- func NewFastStochasticIndicator(series *TimeSeries, timeframe int) Indicator
- func NewFixedIndicator(vals ...float64) Indicator
- func NewGainIndicator(indicator Indicator) Indicator
- func NewHighPriceIndicator(series *TimeSeries) Indicator
- func NewKeltnerChannelLowerIndicator(series *TimeSeries, window int) Indicator
- func NewKeltnerChannelUpperIndicator(series *TimeSeries, window int) Indicator
- func NewLocalExtremaIndicator(indicator Indicator, window int, length int) Indicator
- func NewLossIndicator(indicator Indicator) Indicator
- func NewLowPriceIndicator(series *TimeSeries) Indicator
- func NewMACDHistogramIndicator(macdIdicator Indicator, signalLinewindow int) Indicator
- func NewMACDIndicator(baseIndicator Indicator, shortwindow, longwindow int) Indicator
- func NewMMAIndicator(indicator Indicator, window int) Indicator
- func NewMaximumDrawdownIndicator(indicator Indicator, window int, length int) Indicator
- func NewMaximumValueIndicator(ind Indicator, window int) Indicator
- func NewMeanDeviationIndicator(indicator Indicator, window int) Indicator
- func NewMinimumValueIndicator(ind Indicator, window int) Indicator
- func NewOpenPriceIndicator(series *TimeSeries) Indicator
- func NewPercentChangeIndicator(indicator Indicator) Indicator
- func NewRateOfChangeIndicator(indicator Indicator, window int) Indicator
- func NewRelativeStrengthIndexIndicator(indicator Indicator, timeframe int) Indicator
- func NewRelativeStrengthIndicator(indicator Indicator, timeframe int) Indicator
- func NewRelativeVigorIndexIndicator(series *TimeSeries) Indicator
- func NewRelativeVigorSignalLine(series *TimeSeries) Indicator
- func NewSimpleMovingAverage(indicator Indicator, window int) Indicator
- func NewSlowStochasticIndicator(k Indicator, window int) Indicator
- func NewStandardDeviationIndicator(ind Indicator) Indicator
- func NewSupertrendIndicator(series *TimeSeries, window int, multiplier int) Indicator
- func NewTrendlineIndicator(indicator Indicator, window int) Indicator
- func NewTrueRangeIndicator(series *TimeSeries) Indicator
- func NewTypicalPriceIndicator(series *TimeSeries) Indicator
- func NewVarianceIndicator(ind Indicator) Indicator
- func NewVolumeIndicator(series *TimeSeries) Indicator
- func NewWindowedPercentChangeIndicator(indicator Indicator, window int) Indicator
- func NewWindowedStandardDeviationIndicator(ind Indicator, window int) Indicator
- type MarketSnapshot
- type NaiveAllocator
- type Order
- type OrderSide
- type OrderStatus
- type OrderType
- type OverIndicatorRule
- type Position
- type PositionSnapshot
- type Pricing
- type PricingSnapshot
- type ReturnPeriod
- type Rule
- type Strategy
- type TimeInForce
- type TimePeriod
- func (tp TimePeriod) Advance(iterations int) TimePeriod
- func (tp TimePeriod) Format(layout string) string
- func (tp TimePeriod) In(location *time.Location) TimePeriod
- func (tp TimePeriod) Length() time.Duration
- func (tp TimePeriod) Since(other TimePeriod) time.Duration
- func (tp TimePeriod) String() string
- func (tp TimePeriod) UTC() TimePeriod
- type TimeSeries
- type TradePlan
- type TradingState
- type UnderIndicatorRule
Examples ¶
Constants ¶
const ( SimpleDateTimeFormat = "01/02/2006T15:04:05" SimpleDateFormat = "01/02/2006" SimpleTimeFormat = "15:04:05" SimpleDateFormatV2 = "2006-01-02" )
Constants representing basic, human-readable and writable date formats
Variables ¶
var ( SimpleTimeFomatRegex = regexp.MustCompile(`T\d{2}:\d{2}:\d{2}`) SimpleDateFormatV2Regex = regexp.MustCompile(`\d{4}-\d{2}-\d{2}`) )
Constants representing regexes for parsing datetimes
Functions ¶
Types ¶
type Account ¶
Account is an object describing a trading account, including trading record, open positions and current cash on hand.
func (*Account) Equity ¶
Calculates the total equity of the account including unrealized equity for open positions
func (*Account) ExecuteOrder ¶
Execute an order against the account
func (*Account) ExportSnapshot ¶
func (a *Account) ExportSnapshot(period TimePeriod) *AccountSnapshot
Exports a snapshot of the current account state to be used in the account history and analysis tooling.
func (*Account) HasSufficientFunds ¶
Checks whether the account has enough funds to execute an order. We assume there is always enough funds for a sell order since the system is currently long only.
func (*Account) OpenPosition ¶
CurrentPosition returns the current position in this record
func (*Account) UpdatePrices ¶
Updates prices for all open positions. If a price is not provided for a given position its price is not updated
type AccountHistory ¶
type AccountHistory struct {
Securities []string
Prices []*PricingSnapshot
Snapshots []*AccountSnapshot
}
The AccountHistory contains a record of point in time account snapshots as well as a list of all of the Securities tracked by the account over time.
func NewAccountHistory ¶
func NewAccountHistory() *AccountHistory
func (*AccountHistory) AccountEquityAsIndicator ¶ added in v1.0.2
func (ah *AccountHistory) AccountEquityAsIndicator() Indicator
Derive an Indicator from the account history equity.
func (*AccountHistory) AnnualizedReturn ¶ added in v1.0.2
func (ah *AccountHistory) AnnualizedReturn() big.Decimal
Get the annualized return of the account equity
func (*AccountHistory) AnnualizedVolatility ¶ added in v1.0.2
func (ah *AccountHistory) AnnualizedVolatility() big.Decimal
Calculate the annualized volatility of the account's equity.
func (*AccountHistory) ApplySnapshot ¶
func (ah *AccountHistory) ApplySnapshot(accountSnapshot *AccountSnapshot, pricingSnapshot *PricingSnapshot) error
Add a new account and pricing snapshot to the history.
func (*AccountHistory) ExportAnalysisSummaryYaml ¶ added in v1.0.10
func (ah *AccountHistory) ExportAnalysisSummaryYaml(filepath string) error
Exports an analysis summary to yaml for viewing and analysis.
func (*AccountHistory) ExportMonthlyGainsYaml ¶ added in v1.0.10
func (ah *AccountHistory) ExportMonthlyGainsYaml(filepath string) error
Exports the monthly gains to yaml for viewing and analysis.
func (*AccountHistory) ExportSnapshotsYaml ¶ added in v1.0.10
func (ah *AccountHistory) ExportSnapshotsYaml(filepath string) error
Exports the account snapshots in a readable yaml format for viewing and analysis.
func (*AccountHistory) LastIndex ¶
func (ah *AccountHistory) LastIndex() int
Helper function to return the last index of snapshot data.
func (*AccountHistory) MonthlyPercentGains ¶ added in v1.0.9
func (ah *AccountHistory) MonthlyPercentGains() []ReturnPeriod
Returns broken down by month
func (*AccountHistory) PercentGain ¶
func (ah *AccountHistory) PercentGain() big.Decimal
Total percent gain of the account history.
func (*AccountHistory) PriceAtIndex ¶
Helper function to return a price at a given snapshot index.
func (*AccountHistory) TotalProfit ¶
func (ah *AccountHistory) TotalProfit() big.Decimal
Total profit of the account history.
type AccountSnapshot ¶
type AccountSnapshot struct {
Period TimePeriod `yaml:"period"`
Equity big.Decimal `yaml:"equity"`
Cash big.Decimal `yaml:"cash"`
Positions []*PositionSnapshot `yaml:"positions"`
}
An AccountSnapshot provides the point in time state of an account and its positions.
type Allocations ¶
Allocations are simply a map of securities and their fraction of allocation. All item's fraction in the map should add up to 1.0.
type Allocator ¶
type Allocator interface {
Allocate(index int, strategies []Strategy) Allocations
AllocateWithAccount(index int, strategies []Strategy, account *Account) Allocations
}
An allocator is a functional component which provides a portfolio allocation across many Securities. A list of strategy structures is passed in to calculate the allocations based on rule analysis or timeseries data. All outputted allocation fractions will add up to 1.0 (big.ONE).
type Backtest ¶
type Backtest struct {
// contains filtered or unexported fields
}
The Backtest is a holder struct to run a simulated trading strategy against an account.
func NewBacktest ¶
Create a new backtest with the provided strategies, allocator, and starting account. All strategies are assumed to be normalized and have the same length, indexes, and periods.
func (*Backtest) Run ¶
func (b *Backtest) Run() (*AccountHistory, error)
Run the backtest from start to finish.
type Candle ¶
type Candle struct {
Period TimePeriod
OpenPrice big.Decimal
ClosePrice big.Decimal
MaxPrice big.Decimal
MinPrice big.Decimal
Volume big.Decimal
TradeCount uint
}
Candle represents basic market information for a security over a given time period
func NewCandle ¶
func NewCandle(period TimePeriod) (c *Candle)
NewCandle returns a new *Candle for a given time period
type DecreaseRule ¶
type DecreaseRule struct {
Indicator
}
DecreaseRule is satisfied when the given Indicator at the given index is less than the value at the previous index.
func (DecreaseRule) IsSatisfied ¶
func (dr DecreaseRule) IsSatisfied(index int) bool
IsSatisfied returns true when the given Indicator at the given index is less than the value at the previous index.
type DerivativeIndicator ¶
type DerivativeIndicator struct {
Indicator Indicator
}
DerivativeIndicator returns an indicator that calculates the derivative of the underlying Indicator. The derivative is defined as the difference between the value at the previous index and the value at the current index. Eg series [1, 1, 2, 3, 5, 8] -> [0, 0, 1, 1, 2, 3]
type IncreaseRule ¶
type IncreaseRule struct {
Indicator
}
IncreaseRule is satisfied when the given Indicator at the given index is greater than the value at the previous index.
func (IncreaseRule) IsSatisfied ¶
func (ir IncreaseRule) IsSatisfied(index int) bool
IsSatisfied returns true when the given Indicator at the given index is greater than the value at the previous index.
type Indicator ¶
Indicator is an interface that describes a methodology by which to analyze a trading record for a specific property or trend. For example. MovingAverageIndicator implements the Indicator interface and, for a given index in the timeSeries, returns the current moving average of the prices in that series.
func NewAroonDownIndicator ¶
NewAroonDownIndicator returns a derivative indicator that will return a value based on the number of ticks since the lowest price in the window https://www.investopedia.com/terms/a/aroon.asp
Note: this indicator should be constructed with a either a LowPriceIndicator or a derivative thereof
func NewAroonUpIndicator ¶
NewAroonUpIndicator returns a derivative indicator that will return a value based on the number of ticks since the highest price in the window https://www.investopedia.com/terms/a/aroon.asp
Note: this indicator should be constructed with a either a HighPriceIndicator or a derivative thereof
func NewAverageGainsIndicator ¶
NewAverageGainsIndicator Returns a new average gains indicator, which returns the average gains in the given window based on the given indicator.
func NewAverageLossesIndicator ¶
NewAverageLossesIndicator Returns a new average losses indicator, which returns the average losses in the given window based on the given indicator.
func NewAverageTrueRangeIndicator ¶
func NewAverageTrueRangeIndicator(series *TimeSeries, window int) Indicator
NewAverageTrueRangeIndicator returns a base indicator that calculates the average true range of the underlying over a window https://www.investopedia.com/terms/a/atr.asp
func NewBinaryFrequencyIndicator ¶ added in v1.0.2
Binary Frequency is a specialized indicator which returns the number of times an indicator was greater than a defined threshold over a lookback window.
func NewBollingerLowerBandIndicator ¶
NewBollingerLowerBandIndicator returns a a derivative indicator which returns the lower bound of a bollinger band on the underlying indicator
func NewBollingerUpperBandIndicator ¶
NewBollingerUpperBandIndicator a a derivative indicator which returns the upper bound of a bollinger band on the underlying indicator
func NewCCIIndicator ¶
func NewCCIIndicator(ts *TimeSeries, window int) Indicator
NewCCIIndicator Returns a new Commodity Channel Index Indicator http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci
func NewClosePriceIndicator ¶
func NewClosePriceIndicator(series *TimeSeries) Indicator
NewClosePriceIndicator returns an Indicator which returns the close price of a candle for a given index
func NewConstantIndicator ¶
NewConstantIndicator returns an indicator which always returns the same value for any index. It's useful when combined with other, fluxuating indicators to determine when an indicator has crossed a threshold.
func NewCumulativeGainsIndicator ¶
NewCumulativeGainsIndicator returns a derivative indicator which returns all gains made in a base indicator for a given window.
func NewCumulativeLossesIndicator ¶
NewCumulativeLossesIndicator returns a derivative indicator which returns all losses in a base indicator for a given window.
func NewDifferenceIndicator ¶
NewDifferenceIndicator returns an indicator which returns the difference between one indicator (minuend) and a second indicator (subtrahend).
func NewEMAIndicator ¶
NewEMAIndicator returns a derivative indicator which returns the average of the current and preceding values in the given windowSize, with values closer to current index given more weight. A more in-depth explanation can be found here: http://www.investopedia.com/terms/e/ema.asp
func NewFastStochasticIndicator ¶
func NewFastStochasticIndicator(series *TimeSeries, timeframe int) Indicator
NewFastStochasticIndicator returns a derivative Indicator which returns the fast stochastic indicator (%K) for the given window. https://www.investopedia.com/terms/s/stochasticoscillator.asp
func NewFixedIndicator ¶
NewFixedIndicator returns an indicator with a fixed set of values that are returned when an index is passed in
func NewGainIndicator ¶
NewGainIndicator returns a derivative indicator that returns the gains in the underlying indicator in the last bar, if any. If the delta is negative, zero is returned
func NewHighPriceIndicator ¶
func NewHighPriceIndicator(series *TimeSeries) Indicator
NewHighPriceIndicator returns an Indicator which returns the high price of a candle for a given index
func NewKeltnerChannelLowerIndicator ¶
func NewKeltnerChannelLowerIndicator(series *TimeSeries, window int) Indicator
func NewKeltnerChannelUpperIndicator ¶
func NewKeltnerChannelUpperIndicator(series *TimeSeries, window int) Indicator
func NewLocalExtremaIndicator ¶ added in v1.0.2
Defines an indicator to determine local extrema (minima/maxima). This indicator is really useful for post analysis and calculating things like max drawdown. It is *NOT* good for live trading as it uses a lookback to find the local extrema when an roc switches direction.
This indicator can be useful for identification of "boxes" or "bases" in an asset/security where it is not critical that the extrema be identified immediately.
Right now, the entire extrema slice is computed during creation, so we need the total length of data to compute as a param. This is required because for a given index to be considered a local extrema, we potentially need to look both in front of and behind it.
func NewLossIndicator ¶
NewLossIndicator returns a derivative indicator that returns the losses in the underlying indicator in the last bar, if any. If the delta is positive, zero is returned
func NewLowPriceIndicator ¶
func NewLowPriceIndicator(series *TimeSeries) Indicator
NewLowPriceIndicator returns an Indicator which returns the low price of a candle for a given index
func NewMACDHistogramIndicator ¶
NewMACDHistogramIndicator returns a derivative Indicator based on the MACDIndicator, the result of which is the macd indicator minus it's signalLinewindow EMA. A more in-depth explanation can be found here: http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:macd-histogram
func NewMACDIndicator ¶
NewMACDIndicator returns a derivative Indicator which returns the difference between two EMAIndicators with long and short windows. It's useful for gauging the strength of price movements. A more in-depth explanation can be found here: http://www.investopedia.com/terms/m/macd.asp
func NewMMAIndicator ¶
NewMMAIndicator returns a derivative indciator which returns the modified moving average of the underlying indictator. An in-depth explanation can be found here: https://en.wikipedia.org/wiki/Moving_average#Modified_moving_average
func NewMaximumDrawdownIndicator ¶
Revamped maximum drawdown indicator which uses a local extrema calculation to find the difference between almost absolute peaks and valleys over time.
Each "peak" and "valley" are paired to introduce a single "drawdown"
func NewMaximumValueIndicator ¶
NewMaximumValueIndicator returns a derivative Indicator which returns the maximum value present in a given window. Use a window value of -1 to include all values in the underlying indicator.
func NewMeanDeviationIndicator ¶
NewMeanDeviationIndicator returns a derivative Indicator which returns the mean deviation of a base indicator in a given window. Mean deviation is an average of all values on the base indicator from the mean of that indicator.
func NewMinimumValueIndicator ¶
NewMinimumValueIndicator returns a derivative Indicator which returns the minimum value present in a given window. Use a window value of -1 to include all values in the underlying indicator.
func NewOpenPriceIndicator ¶
func NewOpenPriceIndicator(series *TimeSeries) Indicator
NewOpenPriceIndicator returns an Indicator which returns the open price of a candle for a given index
func NewPercentChangeIndicator ¶
NewPercentChangeIndicator returns a derivative indicator which returns the percent change (positive or negative) made in a base indicator up until the given indicator
func NewRateOfChangeIndicator ¶ added in v1.0.2
The rate of change indicator calculates the total change over a window divided by the number of candles in the window.
func NewRelativeStrengthIndexIndicator ¶
NewRelativeStrengthIndexIndicator returns a derivative Indicator which returns the relative strength index of the base indicator in a given time frame. A more in-depth explanation of relative strength index can be found here: https://www.investopedia.com/terms/r/rsi.asp
func NewRelativeStrengthIndicator ¶
NewRelativeStrengthIndicator returns a derivative Indicator which returns the relative strength of the base indicator in a given time frame. Relative strength is the average again of up periods during the time frame divided by the average loss of down period during the same time frame
func NewRelativeVigorIndexIndicator ¶
func NewRelativeVigorIndexIndicator(series *TimeSeries) Indicator
NewRelativeVigorIndexIndicator returns an Indicator which returns the index of the relative vigor of the prices of a sercurity. Relative Vigor Index is simply the difference of the previous four days' close and open prices divided by the difference between the previous four days high and low prices. A more in-depth explanation of relative vigor index can be found here: https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/relative-vigor-index
func NewRelativeVigorSignalLine ¶
func NewRelativeVigorSignalLine(series *TimeSeries) Indicator
NewRelativeVigorSignalLine returns an Indicator intended to be used in conjunction with Relative vigor index, which returns the average value of the last 4 indices of the RVI indicator.
func NewSimpleMovingAverage ¶
NewSimpleMovingAverage returns a derivative Indicator which returns the average of the current value and preceding values in the given windowSize.
func NewSlowStochasticIndicator ¶
NewSlowStochasticIndicator returns a derivative Indicator which returns the slow stochastic indicator (%D) for the given window. https://www.investopedia.com/terms/s/stochasticoscillator.asp
func NewStandardDeviationIndicator ¶
NewStandardDeviationIndicator calculates the standard deviation of a base indicator. See https://www.investopedia.com/terms/s/standarddeviation.asp
func NewSupertrendIndicator ¶
func NewSupertrendIndicator(series *TimeSeries, window int, multiplier int) Indicator
NewSupertrendIndicator returns a derivative indicator which calculates the well-known supertrend indicator which is based on trend detection using a combination of the average true range (ATR) and the high/low prices of an asset over a defined window.
The typical accepted multipler value is 3.
func NewTrendlineIndicator ¶
NewTrendlineIndicator returns an indicator whose output is the slope of the trend line given by the values in the window.
func NewTrueRangeIndicator ¶
func NewTrueRangeIndicator(series *TimeSeries) Indicator
NewTrueRangeIndicator returns a base indicator which calculates the true range at the current point in time for a series https://www.investopedia.com/terms/a/atr.asp
func NewTypicalPriceIndicator ¶
func NewTypicalPriceIndicator(series *TimeSeries) Indicator
NewTypicalPriceIndicator returns an Indicator which returns the typical price of a candle for a given index. The typical price is an average of the high, low, and close prices for a given candle.
func NewVarianceIndicator ¶
NewVarianceIndicator provides a way to find the variance in a base indicator, where variances is the sum of squared deviations from the mean at any given index in the time series.
func NewVolumeIndicator ¶
func NewVolumeIndicator(series *TimeSeries) Indicator
NewVolumeIndicator returns an indicator which returns the volume of a candle for a given index
func NewWindowedPercentChangeIndicator ¶ added in v1.0.2
The window percent change indicator calculates the change percentage over a fixed lookback window.
func NewWindowedStandardDeviationIndicator ¶
NewWindowedStandardDeviationIndicator returns a indicator which calculates the standard deviation of the underlying indicator over a window
type MarketSnapshot ¶ added in v1.0.3
type MarketSnapshot struct {
Pricing Pricing
TradingState map[string]TradingState
}
MarketSnapshot encompasses useful market state info such as pricing and trading state, which is needed for decision making when using techan with a broker during live trading
type NaiveAllocator ¶
type NaiveAllocator struct {
// contains filtered or unexported fields
}
The naive allocator will proportionally allocate to all strategies which are triggered. A maximum position and total allocation can be provided in order to limit single position size and how much of a given portfolio is allocated.
func NewNaiveAllocator ¶
func NewNaiveAllocator(maxSinglePositionFraction big.Decimal, maxTotalPositionFraction big.Decimal) *NaiveAllocator
Sets up a new naive allocator. if any of the maximum fractions exceed 1.0, then 1.0 will be used. If the max single fraction exceeds the total fraction, then it will be set at the total fraction.
func (*NaiveAllocator) Allocate ¶
func (na *NaiveAllocator) Allocate(index int, strategies []Strategy) Allocations
Perform a naive allocation which simply gives an equal portion of allocation to all strategies whose rules are satisfied.
func (*NaiveAllocator) AllocateWithAccount ¶ added in v1.0.6
func (na *NaiveAllocator) AllocateWithAccount(index int, strategies []Strategy, account *Account) Allocations
Perform a naive allocation, but take into account which positions are currently open with an account. This will also only include an allocation for a new position if the strategy has an entry on this index. This avoids allocating a trade at a sub-optimal entrypoint.
type Order ¶
type Order struct {
ID string
Side OrderSide
Security string
ContractID int
Price big.Decimal
Type OrderType
FilledAmount big.Decimal
Amount big.Decimal
TimeInForce TimeInForce
ExecutionTime time.Time
Status OrderStatus
}
Order represents a trade execution (buy or sell) with associated metadata.
type OrderSide ¶
type OrderSide string
OrderSide is a simple enumeration representing the side of an Order (buy or sell)
type OrderStatus ¶ added in v1.0.6
type OrderStatus string
OrderStatus defines the state of an order with a broker
const ( PENDING OrderStatus = "Pending" FILLED OrderStatus = "Filled" CANCELLED OrderStatus = "Cancelled" OTHER OrderStatus = "Other" )
type OrderType ¶ added in v1.0.3
type OrderType string
OrderType defines common order types accepted by brokers
type OverIndicatorRule ¶
OverIndicatorRule is a rule where the First Indicator must be greater than the Second Indicator to be Satisfied
func (OverIndicatorRule) IsSatisfied ¶
func (oir OverIndicatorRule) IsSatisfied(index int) bool
IsSatisfied returns true when the First Indicator is greater than the Second Indicator
type Position ¶
type Position struct {
Security string
Side OrderSide
Amount big.Decimal
AvgEntryPrice big.Decimal
Price big.Decimal
}
Positions holds iformation about an open position
func NewPosition ¶
NewPosition returns a new Position with the passed-in order as the open order
func (*Position) ExecuteOrder ¶
ExecuteOrder takes a new order to apply to the position and inceases/deducts the amount from the current position. If a buy order is placed, it will also recalculate the average entry price for the position. In all cases, if the order results in a difference to the cash value of the account placing the order a positive (for sells) or negative (for buys) big.Decimal is returned to denote how the account's cash should be modified.
This function will also update the price of the position to that of the order. Prices can always be synced outside of this function using UpdatePrice.
Only long positions are supported currently.
func (*Position) ExportSnapshot ¶
func (p *Position) ExportSnapshot() *PositionSnapshot
export a snapshot of this position at the current state.
func (*Position) IsClosed ¶
Returns if the position is closed, meaning there is currently a zero amount.
func (*Position) UnrealizedEquity ¶
Calculate the unrealized equity of an open position
func (*Position) UnrealizedGain ¶
Computes the unrealized gain since the posiion was entered.
func (*Position) UpdatePrice ¶
Update the current price to reflect realtime values and to calculate unrealized gains/equity
type PositionSnapshot ¶
type PositionSnapshot struct {
Security string `yaml:"security"`
Side OrderSide `yaml:"side"`
Amount big.Decimal `yaml:"amount"`
Price big.Decimal `yaml:"price"`
UnrealizedGain big.Decimal `yaml:"unrealized_gain"`
}
Snapshot of position used to document account history
type PricingSnapshot ¶
type PricingSnapshot struct {
Period TimePeriod
Prices Pricing
}
The PricingSnapshot provides point in time pricing information for all tracked securities, including the bechmark if used. The period for each snapshot should match a period supplied in an account snapshot.
type ReturnPeriod ¶ added in v1.0.9
type ReturnPeriod struct {
Period TimePeriod `yaml:"period"`
PercentGain big.Decimal `yaml:"percent_gain"`
TotalProfit big.Decimal `yaml:"total_profit"`
}
Measures the return for a given period (such as a year, month etc) for analysis.
type Rule ¶
Rule is an interface describing an algorithm by which a set of criteria may be satisfied
func And ¶
And returns a new rule whereby BOTH of the passed-in rules must be satisfied for the rule to be satisfied
func NewCrossDownIndicatorRule ¶
NewCrossDownIndicatorRule returns a new rule that is satisfied when the upper indicator has crossed below the lower indicator.
func NewCrossUpIndicatorRule ¶
NewCrossUpIndicatorRule returns a new rule that is satisfied when the lower indicator has crossed above the upper indicator.
func NewPercentChangeRule ¶
NewPercentChangeRule returns a rule whereby the given Indicator must have changed by a given percentage to be satisfied. You should specify percent as a float value between -1 and 1
type Strategy ¶
type Strategy struct {
Security string
Timeseries TimeSeries
Indicators map[string]Indicator
Rule Rule
}
A strategy is a holder struct which bundles the raw timeseries data, indicators, and rules used to make trading decisions for a given security. The strategy can be used to calculate allocations and map algo trading triggers over time.
type TimeInForce ¶ added in v1.0.3
type TimeInForce string
TimeInForce defines how long an order is good for before it is auto cancelled
const ( GTC TimeInForce = "GTC" OPG TimeInForce = "OPG" DAY TimeInForce = "DAY" IOC TimeInForce = "IOC" )
TimeInForce option enumerations
type TimePeriod ¶
TimePeriod is a simple struct that describes a period of time with a Start and End time
func NewTimePeriod ¶
func NewTimePeriod(start time.Time, period time.Duration) TimePeriod
NewTimePeriod returns a TimePeriod starting at the given time and ending at the given time plus the given duration
func Parse
deprecated
func Parse(timerange string) (tr TimePeriod, err error)
Parse takes a string in one of the following formats and returns a new TimePeriod, and optionally, an error
Deprecated: Please use ParseTimePeriod instead
func ParseTimePeriod ¶
func ParseTimePeriod(period string) (TimePeriod, error)
ParseTimePeriod parses two datetimes as one string and returns it as a TimePeriod.
Note that if you were previously using Parse, the date format has changed to something more rfc3339-like (yyyy-mm-dd) Will accept any combination of date and time for either side. Omitting the right hand side will result in a time period ending in time.Now()
Example ¶
// Any separator between two times is valid
parseable := "2009-01-20T12:00:00 -- 2017-01-20T12:00:00"
timePeriod, err := ParseTimePeriod(parseable)
if err != nil {
return
}
fmt.Println(timePeriod.Start.Year(), timePeriod.End.Year())
Output: 2009 2017
func (TimePeriod) Advance ¶
func (tp TimePeriod) Advance(iterations int) TimePeriod
Advance will return a new TimePeriod with the start and end periods moved forwards or backwards in time in accordance with the number of iterations given.
Example: A timePeriod that is one hour long, starting at unix time 0 and ending at unix time 3600, and advanced by one, will return a time period starting at unix time 3600 and ending at unix time 7200
func (TimePeriod) Format ¶
func (tp TimePeriod) Format(layout string) string
Format returns the string representation of this timePeriod in the given format
func (TimePeriod) In ¶
func (tp TimePeriod) In(location *time.Location) TimePeriod
In returns a copy of TimePeriod tp with both start and end times' location set to the specified location
func (TimePeriod) Length ¶
func (tp TimePeriod) Length() time.Duration
Length returns the length of the period as a time.Duration value
func (TimePeriod) Since ¶
func (tp TimePeriod) Since(other TimePeriod) time.Duration
Since returns the amount of time elapsed since the end of another TimePeriod as a time.Duration value
func (TimePeriod) String ¶
func (tp TimePeriod) String() string
func (TimePeriod) UTC ¶
func (tp TimePeriod) UTC() TimePeriod
UTC returns a copy of TimePeriod tp with both start and end times' location set to UTC
type TimeSeries ¶
type TimeSeries struct {
Candles []*Candle
}
TimeSeries represents an array of candles
func NewTimeSeries ¶
func NewTimeSeries() (t *TimeSeries)
NewTimeSeries returns a new, empty, TimeSeries
func (*TimeSeries) AddCandle ¶
func (ts *TimeSeries) AddCandle(candle *Candle) bool
AddCandle adds the given candle to this TimeSeries if it is not nil and after the last candle in this timeseries. If the candle is added, AddCandle will return true, otherwise it will return false.
func (*TimeSeries) LastCandle ¶
func (ts *TimeSeries) LastCandle() *Candle
LastCandle will return the lastCandle in this series, or nil if this series is empty
func (*TimeSeries) LastIndex ¶
func (ts *TimeSeries) LastIndex() int
LastIndex will return the index of the last candle in this series
type TradePlan ¶
type TradePlan []Order
A trade plan is a list of orders to be executed in the order they appear.
func CreateTradePlan ¶
func CreateTradePlan(allocations Allocations, pricing Pricing, account *Account) (*TradePlan, error)
A trade plan is created by calculating the diff between the current account positions and the desired allocations provided.
type TradingState ¶ added in v1.0.3
type TradingState int
TradingState is used in the MarketSnapshot to convey whether the market for each Security is open, closed, or halted
const ( OPEN TradingState = iota CLOSED HALTED )
Possible trading states
type UnderIndicatorRule ¶
UnderIndicatorRule is a rule where the First Indicator must be less than the Second Indicator to be Satisfied
func (UnderIndicatorRule) IsSatisfied ¶
func (uir UnderIndicatorRule) IsSatisfied(index int) bool
IsSatisfied returns true when the First Indicator is less than the Second Indicator
Source Files
¶
- account.go
- account_history.go
- account_history_analysis.go
- allocator.go
- backtest.go
- cached_indicator.go
- candle.go
- finutils.go
- indicator.go
- indicator_aroon.go
- indicator_average.go
- indicator_average_true_range.go
- indicator_basic.go
- indicator_binary_frequency.go
- indicator_bollinger_band.go
- indicator_cci.go
- indicator_constant.go
- indicator_derivative.go
- indicator_difference.go
- indicator_exponential_moving_average.go
- indicator_fixed.go
- indicator_gains.go
- indicator_keltner_channel.go
- indicator_local_extrema.go
- indicator_macd.go
- indicator_maximum_drawdown.go
- indicator_maximum_value.go
- indicator_mean_deviation.go
- indicator_minimum_value.go
- indicator_modified_moving_average.go
- indicator_rate_of_change.go
- indicator_relative_strength.go
- indicator_relative_vigor_index.go
- indicator_simple_moving_average.go
- indicator_standard_deviation.go
- indicator_stochastic_oscillator.go
- indicator_supertrend.go
- indicator_trend.go
- indicator_true_range.go
- indicator_variance.go
- indicator_windowed_percent_change.go
- indicator_windowed_standard_deviation.go
- market_snapshot.go
- math.go
- order.go
- position.go
- pricing.go
- rule.go
- rule_cross.go
- rule_increase_decrease.go
- strategy.go
- testutils.go
- timeperiod.go
- timeseries.go
- trade_plan.go
- trading_state.go