malgova

package module
v0.0.0-...-7e0ddd7 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2020 License: BSD-3-Clause Imports: 9 Imported by: 0

README

malgova

warning : "work-in-progress"

Algo backtest go-module, to help with writing day trading strategies for NSE Level 1 / Level 2 datasets. This go-module uses the kstreamdb for tick-data, https://github.com/sivamgr/kstreamdb . For recording market-data using zerodha Kite API, refer to kbridge tool available at, https://github.com/sivamgr/mercury

go get

go get github.com/sivamgr/malgova

AlgoStrategy Interface

Algo strategies written in go should fully implement the malgova.AlgoStrategy interface as defined below

// AlgoStrategy Interface
type AlgoStrategy interface {
	Setup(symbol string, b *Book) []string
	OnTick(t kstreamdb.TickData, b *Book)
	OnPeriodic(t time.Time, b *Book) // Invokes every sec
	OnClose(b *Book)
}

Order Book

the Order-Book is passed to algo-strategies callback. Orders can be placed or position shall be exit through the methods exposed by the book

Example

package main

import (
	"fmt"
	"time"

	"github.com/markcheno/go-talib"
	"github.com/sivamgr/kstreamdb"
	"github.com/sivamgr/malgova"
)

// Momento AlgoStrategy
type Momento struct {
	symbol      string
	candles1min *malgova.CandlesData
}

// Setup method, should return list of symbols it need to subscribe for tickdata
func (a *Momento) Setup(symbol string, b *malgova.Book) []string {
	symbolsToSubscribe := make([]string, 0)
	a.symbol = symbol

	//set up data aggregation.
	a.candles1min = malgova.NewCandlesData(60)

	// add symbols needed to subscribe
	symbolsToSubscribe = append(symbolsToSubscribe, symbol)
	b.AllocateCash(10000)
	return symbolsToSubscribe
}
// OnDayStart method
func (a *Momento) OnDayStart(b *malgova.Book) {
}

// OnDayEnd method
func (a *Momento) OnDayEnd(b *malgova.Book) {
}


// OnTick Method
func (a *Momento) OnTick(t kstreamdb.TickData, b *malgova.Book) {
	if t.TradingSymbol == a.symbol {
		// update data aggregation on tick
		a.candles1min.Update(t)
	}
}

// OnPeriodic method
func (a *Momento) OnPeriodic(t time.Time, b *malgova.Book) {
	if a.cs1m.HasChanged(t) && len(a.cs1m.Close) > 15 {
		ltp := a.cs1m.LTP
		ma1 := talib.Sma(a.cs1m.High, 15)
		ma2 := talib.Ema(a.cs1m.Close, 15)
		ma3 := talib.Sma(a.cs1m.Low, 15)
		if b.IsBookClean() && talib.Crossover(ma2, ma1) {
			quantityToBuy := int(b.Cash / ltp)
			b.Buy(quantityToBuy)
		}
		if b.InPosition() && talib.Crossunder(ma2, ma3) {
			b.Exit()
		}
	}
}

// OnClose method
func (a *Momento) OnClose(b *malgova.Book) {
	b.Exit()
}

func main() {
	db := kstreamdb.SetupDatabase("/home/pi/test-data/")
	bt := malgova.BacktestEngine{}
	bt.RegisterAlgo(Momento{})
	bt.Run(&db, nil)
	for _, s := range bt.Scores() {
		fmt.Println(s)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AlgoScore

type AlgoScore struct {
	AlgoName string
	Symbol   string
	// stats and scores
	OrdersCount          int
	TradesCount          int
	TradesWon            int
	TradesLost           int
	WinStreak            int
	LossStreak           int
	NetPnl               float64
	NetPnlPercentAverage float64
	NetPnlPercentStdDev  float64

	SQN float64
}

AlgoScore struct

func (AlgoScore) String

func (t AlgoScore) String() string

type AlgoStrategy

type AlgoStrategy interface {
	Setup(symbol string, b *Book) []string
	OnDayStart(b *Book)
	OnDayEnd(b *Book)
	OnTick(t kstreamdb.TickData, b *Book)
	OnPeriodic(t time.Time, b *Book) // Invokes every sec
	OnClose(b *Book)
}

AlgoStrategy Interface

type BacktestEngine

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

BacktestEngine struct

func (*BacktestEngine) RegisterAlgo

func (bt *BacktestEngine) RegisterAlgo(a interface{})

RegisterAlgo BacktestEngine

func (*BacktestEngine) Run

func (bt *BacktestEngine) Run(feed *kstreamdb.DB, oms OrderManager)

Run BacktestEngine

func (*BacktestEngine) RunAlgoBetweenDate

func (bt *BacktestEngine) RunAlgoBetweenDate(feed *kstreamdb.DB, oms OrderManager, algoName string, startDate time.Time, endDate time.Time)

RunAlgoBetweenDate method

func (*BacktestEngine) Scores

func (bt *BacktestEngine) Scores() []AlgoScore

Scores returns the scores calculated

type Book

type Book struct {
	CashAllocated        float64
	Cash                 float64
	Position             int
	IsMarketOrder        bool
	PendingOrderQuantity int
	PendingOrderPrice    float64
	OrderCount           int
}

Book struct

func (*Book) AllocateCash

func (b *Book) AllocateCash(Money float64)

AllocateCash book

func (*Book) Buy

func (b *Book) Buy(Qty int)

Buy Order

func (*Book) Exit

func (b *Book) Exit()

Exit all position

func (*Book) InPosition

func (b *Book) InPosition() bool

InPosition check

func (*Book) IsBookClean

func (b *Book) IsBookClean() bool

IsBookClean check

func (*Book) IsOrderWaiting

func (b *Book) IsOrderWaiting() bool

IsOrderWaiting check

func (*Book) QuantityAffordable

func (b *Book) QuantityAffordable(Price float64) int

QuantityAffordable book

func (*Book) Sell

func (b *Book) Sell(Qty int)

Sell Order

type CandleStick

type CandleStick struct {
	T time.Time
	O float64
	H float64
	L float64
	C float64
	V uint32
}

CandleStick struct

type CandlesData

type CandlesData struct {
	Candles []CandleStick
	Open    []float64
	High    []float64
	Low     []float64
	Close   []float64
	Volume  []float64
	LTP     float64
	// contains filtered or unexported fields
}

CandlesData struct

func NewCandlesData

func NewCandlesData(periodInSeconds int) *CandlesData

NewCandlesData Instantiates a CandlesData Buffer

func (*CandlesData) HasChanged

func (f *CandlesData) HasChanged(t time.Time) bool

HasChanged method, call with timestamp, to harvest candless return true is a new candle is formed

func (*CandlesData) Update

func (f *CandlesData) Update(t kstreamdb.TickData)

Update method

type Engine

type Engine interface {
	RegisterAlgo(algo interface{})
	Run(feed *kstreamdb.DB, oms OrderManager)
	SubscribeChannel(Symbol string, a AlgoStrategy)
}

Engine Interface

type OrderFlowMonitor

type OrderFlowMonitor struct {
	LastTick               kstreamdb.TickData
	TotalBidsQuantityTaken uint32
	TotalAsksQuantityTaken uint32
	TicksUpdated           uint32
	Prices                 map[uint32]*PriceCell
	Bids                   [5]kstreamdb.DepthItem
	Asks                   [5]kstreamdb.DepthItem
}

OrderFlowMonitor struct

func NewOrderFlowMonitor

func NewOrderFlowMonitor() *OrderFlowMonitor

NewOrderFlowMonitor creates a new orderflow monitor

func (*OrderFlowMonitor) GetPriceCell

func (r *OrderFlowMonitor) GetPriceCell(p float32) *PriceCell

GetPriceCell returns the price cell

func (*OrderFlowMonitor) Reset

func (r *OrderFlowMonitor) Reset()

Reset resets Bids/Asks

func (*OrderFlowMonitor) StringifyPriceCell

func (r *OrderFlowMonitor) StringifyPriceCell(p float32) string

StringifyPriceCell Stringify the Price Bucket

func (*OrderFlowMonitor) StringifyTotals

func (r *OrderFlowMonitor) StringifyTotals() string

StringifyTotals stringyfies total

func (*OrderFlowMonitor) Update

func (r *OrderFlowMonitor) Update(t kstreamdb.TickData)

Update processes the tick

type OrderManager

type OrderManager interface {
	PlaceLimitOrder(symbol string, qty int, price float64, a AlgoStrategy)
	PlaceMarketOrder(symbol string, qty int, price float64, a AlgoStrategy)
}

OrderManager Interface

type PlaybackFeed

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

PlaybackFeed struct

func (*PlaybackFeed) Run

func (f *PlaybackFeed) Run(fCallback func(t kstreamdb.TickData))

Run PlaybackFeed

func (*PlaybackFeed) SetDate

func (f *PlaybackFeed) SetDate(dt time.Time)

SetDate for PlaybackFeed

func (*PlaybackFeed) Setup

func (f *PlaybackFeed) Setup(kdbPath string)

Setup PlaybackFeed

type PriceCell

type PriceCell struct {
	BidQuantityTaken uint32
	AskQuantityTaken uint32
	VolumeTraded     uint32
}

PriceCell struct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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