kate

package
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const MMR = 0.005

MMR - maintenance margin rate

Variables

This section is empty.

Functions

This section is empty.

Types

type BacktestOptions

type BacktestOptions struct {
	TradedPair         string //Must follow the format: BTC/USD, ETH/USDT ...
	Market             MarketType
	MakerFeePercentage float64
	TakerFeePercentage float64
	// contains filtered or unexported fields
}

BacktestOptions is general settings for running a backtest

type Backtester

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

Backtester allows backtesting trading strategies on crypto markets

func NewBacktester

func NewBacktester(mystrategy Strategy, dataHandler *DataHandler) *Backtester

NewBacktester creates a new backtester instance that allows running trading simulations on crypto markets

func NewCustomizedBacktester

func NewCustomizedBacktester(mystrategy Strategy, dataHandler *DataHandler, options BacktestOptions) *Backtester

NewCustomizedBacktester creates a new customized backtester instance that allows running trading simulations on crypto markets

func (*Backtester) Run

func (bt *Backtester) Run() *Statistics

Run executes a trading simulation for the provided configuration on the Backtester

func (*Backtester) SetBalance

func (bt *Backtester) SetBalance(amount float64)

SetBalance defines the initial balance that will be used when trading

func (*Backtester) SetFixedTradeAmount

func (bt *Backtester) SetFixedTradeAmount(amount float64)

SetFixedTradeAmount defines a fixed value that will be used to open every position when trading

func (*Backtester) SetSlippagePercentage

func (bt *Backtester) SetSlippagePercentage(slippagePercent float64)

SetSlippagePercentage define a slippage that tries to better emulate the real trading market

type CoinMarket

type CoinMarket struct {
	Market   MarketType
	MakerFee float64
	TakerFee float64
}

CoinMarket is the handler that allows trading simulation of COIN Margined crypto assets

type DataHandler

type DataHandler struct {
	Prices []DataPoint
}

DataHandler is a wrapper that packages the required data for running backtesting simulation.

func PricesFromCSV

func PricesFromCSV(csvFilePath string) (*DataHandler, error)

PricesFromCSV reads all csv data in the OHLCV format to the DataHandler and returns if a error occurred

type DataPoint

type DataPoint struct {
	Event
	// contains filtered or unexported fields
}

DataPoint is a unit that encapsulates OHLCV price data

func (DataPoint) Close

func (candle DataPoint) Close() float64

Close is the finish price when a candlestick has concluded

func (DataPoint) High

func (candle DataPoint) High() float64

High is the highest price reached between the time a candlestick is open and closed

func (DataPoint) Low

func (candle DataPoint) Low() float64

Low is the lowest price reached between the time a candlestick is open and closed

func (DataPoint) Open

func (candle DataPoint) Open() float64

Open is the starting price for a candlestick

func (DataPoint) Volume

func (candle DataPoint) Volume() float64

Volume is the amount of assets traded in the timeframe for the current candlestick

type Direction

type Direction int

Direction denotes the trade direction that a Position can have

const (
	//LONG denotes the trade direction that earns when the price moves upwards
	LONG Direction = iota
	//SHORT denotes the trade direction that earns when the price moves downwards
	SHORT
)

type Event

type Event interface{}

Event represents a action that will be processed by the eventloop

type EventQueue

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

EventQueue is a queue of events that can be processed when executing a backtest

func (*EventQueue) AddEvent

func (queue *EventQueue) AddEvent(evt Event)

AddEvent inserts a new event into the end of the queue

func (*EventQueue) HasNext

func (queue *EventQueue) HasNext() bool

HasNext checks if there at least one event in the queue

func (*EventQueue) NextEvent

func (queue *EventQueue) NextEvent() Event

NextEvent returns the next event in the qeue, a nil value denotes a empty qeue

type ExchangeHandler

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

ExchangeHandler emulates to behavior of a crypto exchange accepting and tracking orders/trades.

func NewExchangeHandler

func NewExchangeHandler(market MarketType, makerFeePercent, takerFeePercent, percentagePerTrade float64) *ExchangeHandler

NewExchangeHandler creates a new exchange handler that emulates exchange functionality

func (*ExchangeHandler) OpenMarketOrder

func (handler *ExchangeHandler) OpenMarketOrder(tradeDirection Direction, leverage uint) error

OpenMarketOrder opens a new position with a market order if there is no positions already opened

func (*ExchangeHandler) SetBalance

func (handler *ExchangeHandler) SetBalance(amount float64)

SetBalance sets the balance that will be used to trade

func (*ExchangeHandler) SetSlipage

func (handler *ExchangeHandler) SetSlipage(slipagePercent float64)

SetSlipage defines the slipage in the price on all orders of type market

func (*ExchangeHandler) SetStoploss

func (handler *ExchangeHandler) SetStoploss(price float64) error

SetStoploss defines a stoploss that closes the open position completely when the price is reached. The stoploss triggered is a market order

func (*ExchangeHandler) SetTakeProfit

func (handler *ExchangeHandler) SetTakeProfit(price float64) error

SetTakeProfit defines a new takeprofit for the current open position

type MarketHandler

type MarketHandler interface {
	// contains filtered or unexported methods
}

MarketHandler describes market expecific functionality

type MarketType

type MarketType int

MarketType is a type of market that can be traded ( USDFutures, CoinMarginedFutures, Spot, ...)

const (
	//CoinMarginedFutures is a type of market that uses and earns coins as the main currency
	CoinMarginedFutures MarketType = iota
	//USDFutures is a type of market that uses and earns USD/USDT as the main currency
	USDFutures
	//Spot is a type of market that represents the direct exchange of crypto assets
	Spot
)

type OHLCV

type OHLCV interface {
	//Close is the finish price when a candlestick has concluded
	Close() float64

	//Open is the starting price for a candlestick
	Open() float64

	//High is the highest price reached between the time a candlestick is open and closed
	High() float64

	//Low is the lowest price reached between the time a candlestick is open and closed
	Low() float64

	//Volume is the amount of assets traded in the timeframe for the current candlestick
	Volume() float64
}

OHLCV - Represents a datapoint in candle format that contain Open,High, Low, Close prices and Volume data

type OpenPositionEvt

type OpenPositionEvt struct {
	Event
	Direction Direction
	Leverage  uint
	OrderType OrderType
}

OpenPositionEvt is a event to open a simulated position

type OrderType

type OrderType int

OrderType denotes how/when a execution of a position is made on the exchange. To know more check: https://www.binance.com/en/support/articles/360033779452

const (
	//MARKET is a type of order that executes immediately at the best price
	MARKET OrderType = iota
	//LIMIT is a type of order that executes when the traget price is reached
	LIMIT
)

type Position

type Position struct {
	Direction              Direction
	Size                   float64 //total size of the position including leverage
	Leverage               uint    //the multiplier for increasing the total traded position
	Margin                 float64 //the amount of collateral in COIN that is backing the position
	EntryPrice, ClosePrice float64
	Stoploss, TakeProfit   float64
	UnrealizedPNL          float64
	RealizedPNL            float64
	TotalFeePaid           float64
	LiquidationPrice       float64
}

Position is the representation of a traded position

type PositionTransition

type PositionTransition int

PositionTransition are the possible ways a position can change its state

const (
	//MakerTransition is the transition when a limit/takeprofit orders is executed on a position
	MakerTransition PositionTransition = iota
	//TakerTransition is the transition when a market/stoploss order is executed on a position
	TakerTransition
	//Liquidation is the transition when a liquidation is triggered on a open position
	Liquidation
)

type Statistics

type Statistics struct {
	ROIPercentage   float64
	NetProfit       float64
	SharpeRatio     float64
	WinRate         float64 //Percentage of wins'
	ProfitFactor    float64 //Ratio of the total profit to the total loss
	MaxDrawdown     float64 //Percentage for the maximum drawdown after applying the strategy
	TotalTrades     int
	TotalDataPoints int
	TradeHistory    []*Position
	BalanceHistory  []float64
}

Statistics are the results based on trades executed on a backtest run

func (*Statistics) String added in v0.0.10

func (s *Statistics) String() string

type StoplossEvt

type StoplossEvt struct {
	Event
	Price float64
}

StoplossEvt is a event to set a stoploss

type Strategy

type Strategy interface {

	//PreProcessIndicators is the first function called when a new price data is available allowing the strategy
	//to precalculate indicators and make them available for reuse
	PreProcessIndicators(latestPrice DataPoint)

	//OpenNewPosition check if a position should be open
	//the latestPrices represent the most recent price data as defined in the window of the backtest
	OpenNewPosition(latestPrice DataPoint) *OpenPositionEvt

	//SetStoploss [Optional] defines a price where a stoploss will be triggered closing the position in loss
	//The SetStoploss is called with updated unrealizedPnl everytime new price data is available
	//A return value of -1 denotes that no stoploss will be set
	SetStoploss(openPosition Position) *StoplossEvt

	//SetTakeProfit defines a price where a takeprofit will be triggered closing the position in profit
	//The SetStoploss is called with updated unrealizedPnl everytime new price data is available
	//A return value of -1 denotes that no takeprofit will be set
	SetTakeProfit(openPosition Position) *TakeProfitEvt
}

Strategy defines how/when trades should be opened and how stoploss/takeprofits should be set in a simulated run

type TakeProfitEvt

type TakeProfitEvt struct {
	Event
	Price float64
}

TakeProfitEvt is a event to set a takeprofit

type USDMarket

type USDMarket struct {
	Market   MarketType
	MakerFee float64
	TakerFee float64
}

USDMarket is the handler that allows trading simulation of USD Margined crypto assets

Jump to

Keyboard shortcuts

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