gotrader

package module
Version: v0.0.0-...-130b979 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2020 License: Apache-2.0 Imports: 12 Imported by: 0

README

gotrader

Overview

A golang package to automatize trading strategies. This package was mainly developed to trade FOREX, and it depends on fact that the broker should provide control over trades (single transactions). Examples of such brokers are Oanda and IG if using rest API's. In the other hand, the FIX protocol only allow to close or reduce positions (defined here as an aggregation of trades) which is not supported by the package yet.

Usage

Create a streategy that implements the Strategy interface:

type MyStrategy struct {
    engine gotrader.Engine
}

func (s *MyStrategy) SetEngine(engine gotrader.Engine) { // Engine will inject itself to the strategy
    s.engine = engine
}

func (s *MyStrategy) OnTick(tick *gotrader.Tick) {
    // Main Strategy logic
}

...

Then just instantiate a trading session with the strategy and client you need:

strategy := &MyStrategy{}

client := oanda.NewOandaClient("my-token", false)

session := gotrader.NewTradingSession(
		gotrader.Instruments([]string{
			"EUR_USD",
		}),
		gotrader.AccountID("my-account"),
)

session.SetStrategy(strategy).SetClient(client).Live()

if err := session.Start(); err != nil {
    logrus.Warn(err)
}

Included Clients

  • Oanda
  • Random Generator (testing)

TODO

  • Write tests for gotrader
  • Include more broker clients
  • Refactor to add the possibility to use FIX protocol on the clients (control over position only)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

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

Account represent the current account status. Mirrors the broker status.

func (*Account) Balance

func (a *Account) Balance() float64

func (*Account) ChargedFees

func (a *Account) ChargedFees() float64

func (*Account) Equity

func (a *Account) Equity() float64

func (*Account) HomeCurrency

func (a *Account) HomeCurrency() string

func (*Account) ID

func (a *Account) ID() string

func (*Account) Instrument

func (a *Account) Instrument(instrument string) *Instrument

func (*Account) Instruments

func (a *Account) Instruments() map[string]*Instrument

func (*Account) MarginFree

func (a *Account) MarginFree() float64

func (*Account) MarginUsed

func (a *Account) MarginUsed() float64

func (*Account) Time

func (a *Account) Time() time.Time

func (*Account) UnrealizedEffectiveProfit

func (a *Account) UnrealizedEffectiveProfit() float64

func (*Account) UnrealizedNetProfit

func (a *Account) UnrealizedNetProfit() float64

type AccountStatus

type AccountStatus struct {
	Currency              string
	Hedge                 Hedge
	Equity                float64
	Balance               float64
	UnrealizedGrossProfit float64
	MarginUsed            float64
	MarginFree            float64
	Leverage              float64
}

type BrokerClient

type BrokerClient interface {
	GetAccountStatus(accountID string) (AccountStatus, error)
	GetAvailableInstruments(accountID string) ([]InstrumentDetails, error)

	OpenMarketOrder(accountID, instrument string, units int32, side string) error
	CloseTrade(accountID, id string) error
	GetOpenTrades(accountID string) ([]TradeDetails, error)

	SubscribePrices(accountID string, instruments []InstrumentDetails, callback TickHandler) error
	SubscribeOrderFillNotifications(accountID string, orderFIllCallback OrderFillHandler) error
	SubscribeSwapChargeNotifications(accountID string, swapChargeCallback SwapChargeHandler) error
	SubscribeFundsTransferNotifications(accountID string, fundsTransferCallback FundsTransferHandler) error
}

type Engine

type Engine interface {
	Account() *Account
	Buy(instrument string, units int32)
	Sell(instrument string, units int32)
	CloseTrade(instrument string, id string)
	StopSession() // Gracefully stops trading session from strategy
}

Engine is the interface used for interaction from strategy. Is used to check the state of the account, open or close trades and to stop the session.

type FundsTransfer

type FundsTransfer struct {
	Ammount float64
	Time    time.Time
}

type FundsTransferHandler

type FundsTransferHandler func(funds *FundsTransfer)

type Hedge

type Hedge int

Hedge represents the type of hedging defined by the broker.

const (
	FullHedge Hedge = iota
	NoHedge
	HalfHedge
)

type Instrument

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

func (*Instrument) Ask

func (i *Instrument) Ask() float64

func (*Instrument) BaseCurrency

func (i *Instrument) BaseCurrency() string

func (*Instrument) Bid

func (i *Instrument) Bid() float64

func (*Instrument) ChargedFees

func (i *Instrument) ChargedFees() float64

func (*Instrument) Leverage

func (i *Instrument) Leverage() float64

func (*Instrument) LongPosition

func (i *Instrument) LongPosition() *Position

func (*Instrument) MarginUsed

func (i *Instrument) MarginUsed() float64

func (*Instrument) Name

func (i *Instrument) Name() string

func (*Instrument) PipLocation

func (i *Instrument) PipLocation() int

func (*Instrument) QuoteCurrency

func (i *Instrument) QuoteCurrency() string

func (*Instrument) ShortPosition

func (i *Instrument) ShortPosition() *Position

func (*Instrument) Spread

func (i *Instrument) Spread() float64

func (*Instrument) Trade

func (i *Instrument) Trade(id string) *Trade

func (*Instrument) TradeByOrder

func (i *Instrument) TradeByOrder(index int) *Trade

func (*Instrument) Trades

func (i *Instrument) Trades() <-chan *Trade

func (*Instrument) TradesByAscendingOrder

func (i *Instrument) TradesByAscendingOrder(tradesNumber int) <-chan *Trade

func (*Instrument) TradesByDescendingOrder

func (i *Instrument) TradesByDescendingOrder(tradesNumber int) <-chan *Trade

func (*Instrument) TradesNumber

func (i *Instrument) TradesNumber() int32

func (*Instrument) UnrealizedEffectiveProfit

func (i *Instrument) UnrealizedEffectiveProfit() float64

func (*Instrument) UnrealizedNetProfit

func (i *Instrument) UnrealizedNetProfit() float64

type InstrumentDetails

type InstrumentDetails struct {
	Name          string
	BaseCurrency  string
	QuoteCurrency string
	Leverage      float64
	PipLocation   int
}

type Logger

type Logger interface {
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Warn(args ...interface{})
	Warnf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
}

Logger is an interface of a logger behaviour used by gotrader, with it the user will be able to configure logging level and message format at free will. The idea is to have a generic interface already implemented by a by some logging packages, without importing them directly.

type Option

type Option func(p *sessionParameters)

Option represents trading session functional option

func AccountID

func AccountID(account string) Option

AccountID is the functional option to define the account where the session will operate

func HedgeType

func HedgeType(hedge Hedge) Option

HedgeType is the functional option to choose how hedge is calculated in the backtest engine.

func HomeCurrency

func HomeCurrency(ccy string) Option

HomeCurrency is the functional option to define home currency in the backtest engine.

func InitialBalance

func InitialBalance(value float64) Option

InitialBalance is the functional option to define the initial balance in the backtest engine.

func Instruments

func Instruments(instruments []string) Option

Instruments is the functional option to define the instruments to trade

func Leverage

func Leverage(leverage float64) Option

Leverage is the functional option to define account leverage in the backtest engine.

func SetLogger

func SetLogger(logger Logger) Option

SetLogger is the functional option to define which logger will be used by the engine.

type OrderFill

type OrderFill struct {
	Error       string
	TradeClose  bool
	OrderID     string
	TradeID     string
	Side        Side
	Instrument  InstrumentDetails
	Price       float64
	Units       int32
	Profit      float64
	ChargedFees float64
	Time        time.Time
}

type OrderFillHandler

type OrderFillHandler func(order *OrderFill)

type Position

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

Position represents the total exposure in a single side of an instrument. Is the aggregation of all the trades of that side.

func (*Position) AveragePrice

func (p *Position) AveragePrice() float64

func (*Position) ChargedFees

func (p *Position) ChargedFees() float64

func (*Position) MarginUsed

func (p *Position) MarginUsed() float64

func (*Position) Side

func (p *Position) Side() Side

func (*Position) Trade

func (p *Position) Trade(id string) *Trade

func (*Position) TradeByOrder

func (p *Position) TradeByOrder(index int) *Trade

func (*Position) Trades

func (p *Position) Trades() <-chan *Trade

func (*Position) TradesByAscendingOrder

func (p *Position) TradesByAscendingOrder(tradesNumber int) <-chan *Trade

func (*Position) TradesByDescendingOrder

func (p *Position) TradesByDescendingOrder(tradesNumber int) <-chan *Trade

func (*Position) TradesNumber

func (p *Position) TradesNumber() int32

func (*Position) Units

func (p *Position) Units() int32

func (*Position) UnrealizedEffectiveProfit

func (p *Position) UnrealizedEffectiveProfit() float64

func (*Position) UnrealizedNetProfit

func (p *Position) UnrealizedNetProfit() float64

type Side

type Side int

Side represents the type of position, which can be short or long

const (
	//Short represents a selling position
	Short Side = iota

	// Long represents a buying position
	Long
)

func (Side) String

func (s Side) String() string

type Strategy

type Strategy interface {
	Initialize()
	SetEngine(engine Engine)
	OnOrderFill(orderFill *OrderFill)
	OnTick(tick *Tick)
	OnStop()
}

Strategy is the interface that a strategy must implement in order to be used by this engine.

type SwapCharge

type SwapCharge struct {
	Charges []*TradeSwapCharge
	Time    time.Time
}

type SwapChargeHandler

type SwapChargeHandler func(charges *SwapCharge)

type Tick

type Tick struct {
	Instrument string
	Bid        float64
	Ask        float64
	Time       time.Time
}

type TickHandler

type TickHandler func(tick *Tick)

type Trade

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

Trade represents a transaction in a broker (execution of an order). Not all brokers have the possibility to operate over single trades, making impossible to use this engine in the current state.

func (*Trade) ChargedFees

func (t *Trade) ChargedFees() float64

ChargedFees returns the total charged fees, like rollovers.

func (*Trade) CurrentPrice

func (t *Trade) CurrentPrice() float64

CurrentPrice returns the current price of the trade/instrument.

func (*Trade) ID

func (t *Trade) ID() string

ID returns the ID of the trade.

func (*Trade) InstrumentName

func (t *Trade) InstrumentName() string

InstrumentName return the instrument name.

func (*Trade) MarginUsed

func (t *Trade) MarginUsed() float64

MarginUsed return the margin that the trade is using

func (*Trade) OpenPrice

func (t *Trade) OpenPrice() float64

OpenPrice returns the openning price of the trade.

func (*Trade) OpenTime

func (t *Trade) OpenTime() time.Time

OpenTime returns the open time of trade.

func (*Trade) Side

func (t *Trade) Side() Side

Side returns the side, it be either Long or Short

func (*Trade) Units

func (t *Trade) Units() int32

Units returns the total units that this trade is exposed.

func (*Trade) UnrealizedEffectiveProfit

func (t *Trade) UnrealizedEffectiveProfit() float64

UnrealizedEffectiveProfit returns the unrealized profit plus the charged fees.

func (*Trade) UnrealizedNetProfit

func (t *Trade) UnrealizedNetProfit() float64

UnrealizedNetProfit returns the unrealized profit.

type TradeDetails

type TradeDetails struct {
	ID          string
	Instrument  InstrumentDetails
	Side        Side
	Units       int32
	OpenPrice   float64
	ChargedFees float64
	OpenTime    time.Time
}

type TradeSwapCharge

type TradeSwapCharge struct {
	ID         string
	Ammount    float64
	Instrument InstrumentDetails
}

type TradingSession

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

TradingSession represents the entrypoint struct of the gotrader package, representing a trading session.

func NewTradingSession

func NewTradingSession(opts ...Option) *TradingSession

NewTradingSession is the TradingSession constructor.

func (*TradingSession) Backtest

func (s *TradingSession) Backtest() *TradingSession

Backtest defines that this is a backtesting session.

func (*TradingSession) Live

func (s *TradingSession) Live() *TradingSession

Live defines that this is a live session.

func (*TradingSession) SetClient

func (s *TradingSession) SetClient(client BrokerClient) *TradingSession

SetClient sets the client that will be used for comunication with the broker.

func (*TradingSession) SetStrategy

func (s *TradingSession) SetStrategy(strategy Strategy) *TradingSession

SetStrategy sets the strategy to trade.

func (*TradingSession) Start

func (s *TradingSession) Start() error

Start trading session.

Directories

Path Synopsis
clients

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to