ats

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2019 License: MIT Imports: 27 Imported by: 1

README

goATS

Build Status

open Algorithm Trading Platform using golang

goATS inspired by abstract Broker/Feed from pyalgotrade, Order Type&Execution from InteractiveBrokers.

goATS is a abstract Broker/Feed service Library for go/lua/Python/Java Algorithm Tradin System. goATS works great with the pyalgotrade open source backtesting library.

The main function of goATS is to providing unified broker&feed service for backtesting & trading(real or paper), including:

  • simulation tick from Bar
  • backtesting with tick data
  • realtime quotes feed
  • history data feed, directly from feed or local cached
  • paper or real trading with broker
Documentation

Visit the docs on go-ats (http://godoc.org/github.com/kjx98/go-ats)

Documentation

Index

Constants

View Source
const (
	VmIdle int32 = iota
	VmStart
	VmRunning
	VmStoping
)

VmIdle ... vm is idle

Variables

This section is empty.

Functions

func DayDbCacheStatus

func DayDbCacheStatus() string

DayDbCacheStatus ... dump mysql Dayta cache status

func DigitFromInt

func DigitFromInt(v int, ndigit int) float64

func DigitToInt

func DigitToInt(v float64, ndigit int) int

func DukasCacheStatus

func DukasCacheStatus() string

DukasCacheStatus dump cache usage

func GetDB

func GetDB() *sql.DB

GetDB ... get DB handle

func InitSimBroker

func InitSimBroker(startT, endT time.Time, defFund float64)

InitSimBroker ... set default fund, startTime, endTime etc

func IsEquity

func IsEquity(code string) int

IsEquity ... get symbol type

func LoadBarFX

func LoadBarFX(pair string, period Period, startD, endD julian.JulianDay) (err error)

LoadBarFX .. load forex Bar data

func LoadDayBar

func LoadDayBar(symbol string, period Period, startD, endD julian.JulianDay) (err error)

LoadDayBar ... load Bar data for symbol

func NewSlice

func NewSlice(s Series) (res []float64)

NewSlice ... build slice from Series

func OpenDB

func OpenDB() (*sql.DB, error)

OpenDB ... open mysql, return DB handle

func RegisterBroker

func RegisterBroker(name string, inf Broker) error

RegisterBroker ... register broker with name

func RegisterStrategy

func RegisterStrategy(name string, inf Strategyer) error

RegisterStrategy should be called from init()

func TickFX2Bytes

func TickFX2Bytes(buf *TickFX) []byte

func ValidateTick

func ValidateTick(sym string) error

ValidateTick ... validate tick data timestamp in order

Types

type BarCache

type BarCache struct {
	Bars
	// contains filtered or unexported fields
}

BarCache ... only cache for non basePeriod Bars

type Bars

type Bars struct {
	Date   []timeT64
	Open   []float64
	High   []float64
	Low    []float64
	Close  []float64
	Volume []float64
	// contains filtered or unexported fields
}

Bars struct for talib

func (*Bars) RowString

func (b *Bars) RowString(idx int) string

RowString ... convert row date to string

func (*Bars) String

func (b *Bars) String() string

type Broker

type Broker interface {
	Open(ch chan<- QuoteEvent) (Broker, error) // on success return interface pointer
	Start(c Config) error                      // user/pwd, startDate/endDate ...
	Stop() error                               // stop broker, logout, cleanup
	SubscribeQuotes([]QuoteSubT) error

	Equity() float64                                                              // return equity value current
	Balance() float64                                                             // Balance after last settlement
	Cash() float64                                                                // available free cash
	FreeMargin() float64                                                          // availble free margin
	SendOrder(sym string, dir OrderDirT, qty int, prc float64, stopL float64) int // return oId >=0 on success
	CancelOrder(oID int) error                                                    // Cancel Order
	CloseOrder(oID int)
	GetOrder(oID int) *OrderType
	GetOrders() []int
	GetPosition(sym string) PositionType
	GetPositions() []PositionType
	TimeCurrent() DateTimeMs // return current time of broker server in millisecond timestamp
}

Broker ... interface for abstract broker

type Config

type Config map[string]interface{}

Config map string to empty interface

func (Config) GetFloat64

func (c Config) GetFloat64(key string, def float64) float64

GetFloat64 ... get flota64 config value

func (Config) GetInt

func (c Config) GetInt(key string, def int) int

GetInt ... get int config value

func (Config) GetString

func (c Config) GetString(key string, def string) string

GetString ... get string config value

func (Config) GetStrings

func (c Config) GetStrings(key string) []string

GetStrings ... get []string config value

func (Config) Put

func (c Config) Put(key string, v interface{})

Put store config value

type Context

type Context struct {
	Broker
	Config
	GetBars func(sym string, period Period) (res *Bars, err error)
}

Context ... context store broker and config

type DateTimeMs

type DateTimeMs int64

DateTimeMs ... millisecond since 1920/1/1

func JulianToDateTimeMs

func JulianToDateTimeMs(jDN julian.JulianDay) DateTimeMs

JulianToDateTimeMs ... convert jilian Day to DateTimeMs

func TimeToDateTimeMs

func TimeToDateTimeMs(dt time.Time) DateTimeMs

TimeToDateTimeMs ... convert time.Time to DateTimeMs

func (DateTimeMs) Millisecond

func (dtMs DateTimeMs) Millisecond() int

Millisecond ... return milli second 0..999

func (DateTimeMs) String

func (dtMs DateTimeMs) String() string

func (DateTimeMs) Time

func (dtMs DateTimeMs) Time() time.Time

Time returns the UTC Time corresponding to the given DateTimeMs time, sec

seconds and nsec nanoseconds since January 1, 1970 UTC.

func (DateTimeMs) Unix

func (dtMs DateTimeMs) Unix() int64

Unix return seconds from 1970/1/1 UTC

type DayTA

type DayTA struct {
	Date     julian.JulianDay
	Open     int32
	High     int32
	Low      int32
	Close    int32
	Turnover float32
	Volume   int64
}

func GetChart

func GetChart(sym string, startD, endD julian.JulianDay) (res []DayTA)

GetChart ... get []DayTA from mysql or cache

type MinFX

type MinFX struct {
	Time      timeT64
	Open      int32
	High      int32
	Low       int32
	Close     int32
	Ticks     int32
	Volume    float32
	SpreadMin uint16
	SpreadMax uint16
}

func LoadMinFX

func LoadMinFX(pair string, startD, endD julian.JulianDay, maxCnt int) (res []MinFX, err error)

LoadMinFX DukasCopy forex Min1 data

startD, endD		0 unlimit, or weekbase of date
maxCnt				0 unlimit

type MinTA

type MinTA struct {
	Time    timeT32
	Open    int32
	High    int32
	Low     int32
	Close   int32
	Volume  uint32
	UpVol   uint32
	DownVol uint32
}

type MinTAExt

type MinTAExt struct {
	Time     timeT32
	Avg      int32
	Turnover float32
	OpenInt  uint32
}

type OrderDirT

type OrderDirT int32

OrderDirT current only Buy/Sell, no hedge position

const (
	OrderDirBuy OrderDirT = iota
	OrderDirSell
	OrderDirCover
	OrderDirClose
)

OrderDirBuy ... Buy long open OrderDirSell ... Sell short open OrderDirCover ... Buy cover short OrderDirClose ... Sell close long

func (OrderDirT) IsOffset

func (orDir OrderDirT) IsOffset() bool

IsOffset ... return true for position close/offset

func (OrderDirT) Sign

func (orDir OrderDirT) Sign() int

Sign ... for order dir

return 1   for Buy
return -1  for Sell

func (OrderDirT) String

func (orDir OrderDirT) String() string

type OrderStatusT

type OrderStatusT int32

OrderStatusT ... order status

const (
	OrderNil OrderStatusT = iota
	OrderNew
	OrderAccept
	OrderPartFilled
	OrderFilled
	OrderCanceled
)

OrderNil ... nil order

func (OrderStatusT) String

func (oSt OrderStatusT) String() string

type OrderType

type OrderType struct {
	Symbol    string
	Price     float64
	StopPrice float64
	Dir       OrderDirT
	Qty       int
	QtyFilled int
	Magic     int
	Status    OrderStatusT
	AckTime   DateTimeMs
	DoneTime  DateTimeMs
	AvgPrice  float64
}

OrderType ... struct

Symbol  order symbol
Price	order price(or profit price if Stop not zero)
StopPrice	StopLoss price
Dir		OrderBuy, OrderSell
Qty		order quantity
QtyFilled

type Parameter

type Parameter struct {
	Name  string
	Value interface{}
}

Parameter could be int/uint/float like type

type Period

type Period int32

Period ... seconds for Bar time interval

const (
	// Min1 - 1 Minute time period
	Min1 Period = 60
	// Min3 - 3 Minute time period
	Min3 Period = 180
	// Min5 - 5 Minute time period
	Min5 Period = 300
	// Min15 - 15 Minute time period
	Min15 Period = 900
	// Min30 - 30 Minute time period
	Min30 Period = 1800
	// Hour1 - 60 Minute time period
	Hour1 Period = 3600
	// Hour2 - 2 hour time period
	Hour2 Period = 7200
	// Hour4 - 4 hour time period
	Hour4 Period = 14400
	// Hour8 - 8 hour time period
	Hour8 Period = 28800
	// Daily time period, using ymd/julianDay
	Daily Period = 86400
	// Weekly time period
	Weekly Period = 604800
	// Monthly time period, 30days, actual use ymd
	Monthly Period = 2592000
)

func (Period) String

func (per Period) String() string

type PositionType

type PositionType struct {
	Positions int
	PosFreeze int
	AvgPrice  float64 // average price for position
	// contains filtered or unexported fields
}

PositionType ... position for symbol of account

type QuoteEvent

type QuoteEvent struct {
	Symbol  string
	EventID int
}

QuoteEvent used by broker to notify quote/tick/bar update EventID 0 for quote/tick update, else bar period

type QuoteSubT

type QuoteSubT struct {
	Symbol    string
	QuotesPtr *Quotes
}

QuoteSubT ... subscribe quote struct

type Quotes

type Quotes struct {
	UpdateTime DateTimeMs
	TodayOpen  float64
	TodayHigh  float64
	TodayLow   float64
	Pclose     float64
	Last       float64
	Volume     int64
	Turnover   float64
	Bid        float64
	Ask        float64
	BidVol     int64
	AskVol     int64
}

Quotes ... No Level2 quotes yet

type Series

type Series interface {
	Len() int
	DataAt(i int) float64
}

Series data with int index Len return length of Series DataAt return Data at index i

if i >= 0,  data at index
else  data at index reverse order, -1 for last data

type Strategyer

type Strategyer interface {
	ParamSet() []Parameter               // Return parameter set for strategy
	Init(c *Context) (Strategyer, error) // Initialize strategy paramter, universe in c.Config
	OnTick(sym string)                   // sym tick/quotes updated
	OnBar(sym string, period Period)     // bar with period updated
	DeInit()                             // Destroy interface/state
}

Strategyer ... universe of Strategyer should never intersection one symbol/ticker can only be processed by one Strategyer

Context.Config items   "Universe":[]string, "Param":[]float64

type Symbol

type Symbol struct {
	Ticker        string
	Name          string
	StartDate     julian.JulianDay
	EndDate       julian.JulianDay
	AutoCloseDate julian.JulianDay
	Exchange      string
	// contains filtered or unexported fields
}

Symbol ...

symbol table for assets
StartDate, EndDate,	AutoCloseDate julianDay

func FindTicker

func FindTicker(ticker string) *Symbol

FindTicker ... get Symbol of ticker

type SymbolInfo

type SymbolInfo struct {
	Ticker string

	Upper float64
	Lower float64
	// contains filtered or unexported fields
}

SymbolInfo symbol traits of instrument fKey link Bars/DayTA/MinTA etc, index from 1 .. count

func GetSymbolInfo

func GetSymbolInfo(sym string) (SymbolInfo, error)

func (*SymbolInfo) CalcProfit

func (s *SymbolInfo) CalcProfit(openP, closeP float64, volume int) float64

CalcProfit calc order profit according to price and volume position

volume < 0 for short

func (*SymbolInfo) CalcRiskVolume

func (s *SymbolInfo) CalcRiskVolume(amt float64, riskPrice float64) float64

CalcRiskVolume ... calc order quantity according to price and value amount according to margin

func (*SymbolInfo) CalcVolume

func (s *SymbolInfo) CalcVolume(amt float64, p float64) float64

CalcVolume calc order quantity according to price and value amount in full margin

func (*SymbolInfo) Digits

func (s *SymbolInfo) Digits() int

func (*SymbolInfo) Divi

func (s *SymbolInfo) Divi() float64

func (*SymbolInfo) FastKey

func (s *SymbolInfo) FastKey() SymbolKey

FastKey for internal

func (*SymbolInfo) GetQuotes

func (s *SymbolInfo) GetQuotes() Quotes

GetQuotes return quotes for symbol

func (*SymbolInfo) Multi

func (s *SymbolInfo) Multi() float64

func (*SymbolInfo) PriceNormal

func (s *SymbolInfo) PriceNormal(p float64) float64

PriceNormal normal Price for order

func (*SymbolInfo) String

func (s *SymbolInfo) String() (res string)

func (*SymbolInfo) VolumeDigits

func (s *SymbolInfo) VolumeDigits() int

type SymbolKey

type SymbolKey int

SymbolKey ... fast key for symbol, based from 1

func (SymbolKey) SymbolInfo

func (fkey SymbolKey) SymbolInfo() (*SymbolInfo, error)

type TaSeries

type TaSeries interface {
	Len() int
	BarValue(i int) (Ti timeT64, Op, Hi, Lo, Cl float64, Vol float64)
}

TaSeries TA OHLCV

type Tick

type Tick struct {
	Time   timeT32
	Last   int32
	Volume uint32
}

type TickExt

type TickExt struct {
	Time     timeT32
	Bid      int32
	BidVol   uint32
	Ask      int32
	AskVol   uint32
	BidDepth int32
	AskDepth int32
	BidsVol  uint32
	AsksVol  uint32
}

type TickFX

type TickFX struct {
	Time DateTimeMs
	Bid  int32
	Ask  int32
}

func Bytes2TickFX

func Bytes2TickFX(buf []byte) *TickFX

func LoadTickFX

func LoadTickFX(pair string, startD, endD julian.JulianDay, maxCnt int) (res []TickFX, err error)

LoadTickFX ... load DukasCopy forex tick data

startD, endD		0 unlimit, or weekbase of date
maxCnt				0 unlimit

type TickHead

type TickHead struct {
	Time    timeT32 // timeStamp Base, timeT32 for first tick
	BaseP   int32   // BasePrice, Last for first tick or pclose
	Count   int32   // Tick/TickExt count
	BufSize int32   // BufSize for encoded(compressed)
}

TickHead ... used only for encode/decode

func (*TickHead) DecodeMinTA

func (tickHd *TickHead) DecodeMinTA(buf []byte) (ticks []MinTA, err error)

DecodeMinTA ... (* TickHead) DecodeMinTA([]Byte) ([]MinTA, error)

Decode/DeCompress MinTA Slice to byte slice

func (*TickHead) DecodeTick

func (tickHd *TickHead) DecodeTick(buf []byte) (ticks []Tick, err error)

DecodeTick ... (* TickHead) DecodeTick([]Byte) ([]Tick, error)

Decode/DeCompress Tick Slice to byte slice

func (*TickHead) DecodeTickExt

func (tickHd *TickHead) DecodeTickExt(buf []byte) (ticks []TickExt, err error)

DecodeTickExt ... (* TickHead) DecodeTickExt([]Byte) ([]TickExt, error)

Decode/DeCompress TickExt Slice to byte slice

func (*TickHead) EncodeMinTA

func (tickHd *TickHead) EncodeMinTA(mins []MinTA) (buf []byte, err error)

EncodeMinTA (* TickHead) EncodeMinTA([]MinTA) ([]byte, error)

Encode/Compress MinTA Slice to byte slice

func (*TickHead) EncodeTick

func (tickHd *TickHead) EncodeTick(ticks []Tick) (buf []byte, err error)

EncodeTick (* TickHead) EncodeTick([]Tick) ([]byte, error)

Encode/Compress Tick Slice to byte slice

func (*TickHead) EncodeTickExt

func (tickHd *TickHead) EncodeTickExt(ticks []TickExt) (buf []byte, err error)

EncodeTickExt (* TickHead) EncodeTickExt([]TickExt) ([]byte, error)

Encode/Compress TickExt Slice to byte slice

type TimeSeries

type TimeSeries interface {
	Len() int
	DataAt(timeT64) float64
	Index(timeT64) int
}

TimeSeries time as index

Jump to

Keyboard shortcuts

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