funding

package
v0.0.0-...-83dca6d Latest Latest
Warning

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

Go to latest
Published: May 23, 2022 License: MIT Imports: 13 Imported by: 0

README

GoCryptoTrader Backtester: Funding package

Build Status Software License GoDoc Coverage Status Go Report Card

This funding package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Funding package overview

What does the funding package do?

The funding package is responsible for keeping track of all funds across all events during a backtesting run. It is backwards compatible with all existing backtesting strategies

What is the funding manager?

The funding manager is responsible for holding all funding Items and Pairs over the course of a backtesting run. It prevents funds from being overwritten and maintains relationships of currency pairs.

Consider the following example: Exchange Level Funding is disabled and Simultaneous Processing is disabled, so each currency in the .strat config will execute a strategy individually. If the pairs BTC-USDT, BNB-USDT and LTC-BTC are present, then the funding manager will ensure that none of the funds are shared between each of the currencies, even if they all share base or quote values.

Conversely, Exchange level funding and Simultaneous Processing is enabled, so each currency in the .strat file will be processed in one step per time interval. The pairs BTC-USDT, BNB-USDT and BTC-LTC can all share the same base or quote level funds and can make complex decisions on how that funding is used, such as allowing BTC-LTC to make a purchase if an indicator is strongest for that pair.

What is a funding Item?

A funding item holds the initial funding, current funding, reserved funding and transfer fees associated with an exchange, asset and currency. If it is a Pair, then the Item will be linked to the paired Item.

What is a funding Pair?

A funding Pair consists of two funding Items, the Base and Quote. If Exchange Level Funding is disabled, the Base and Quote are linked to each other and the funds cannot be shared with other Pairs or Items. If Exchange Level Funding is enabled, the pair can access the same funds as every other currency that shares the exchange and asset type.

What does Exchange Level Funding mean?

Exchange level funding allows funds to be shared during a backtesting run. If the strategy contains the two pairs BTC-USDT and BNB-USDT and the strategy sells 3 BTC for $100,000 USDT, then BNB-USDT can use that $100,000 USDT to make a purchase of $20,000 BNB. It is restricted to an exchange and asset type, so BTC used in spot, cannot be used in a futures contract (futures backtesting is not currently supported). However, the funding manager can transfer funds between exchange and asset types.

Having funding at the exchange level also allows for a finer degree of control while also being more realistic for strategic execution. A user can create a strategy with many pairs, such as BTC-USDT, LTC-BTC, DOGE-XRP and XRP-USDT, but only creating funding for USDT and still see the purchase of LTC or DOGE. Another strategy could start with funding in the Base currency. So an RSI strategy for BTC-USDT that has 3 BTC as funding will then start by selling rather than buying.

Why is Simultaneous Processing a prerequisite of Exchange Level Funding?

Simultaneous Processing allows a strategy to process multiple data signals for a single time period to be processed in one step. The reason Simultaneous Processing is required for Exchange Level Funding is that if it is disabled, all events are handled in a sequence. If any funding was to be shared in such a scenario, the first currency to be processed will always get the choice share of funding. Simultaneous Processing ensures the decision to spend funds for BTC-USDT over BNB-USDT is a measured decision, and not done by the order of currencies in a strategy config.

Can I transfer funds from one place to another?

Yes! Though it does use some things to consider.

  • It is handled at the strategy execution level, so when creating a strategy, you design the conditions in which funding may be transferred from one place to another.
    • For example, if an indicator is very strong on one exchange, but not another, you may wish to transfer funds to the strongest exchange to act upon
  • It comes with the assumption that a transfer is actually possible in the candle timeframe your strategy runs on.
    • For example, a 1 minute candle strategy likely would not be able to process a transfer of funds and have another exchange use it in that timeframe. So any positive results from such a strategy may not be reflected in real-world scenarios
  • You can only transfer to the same currency eg BTC from Binance to FTX, no conversions
  • You set the transfer fee in your config
Do I need to add funding settings to my config if Exchange Level Funding is disabled?

No. The already existing CurrencySettings will populate the funding manager with initial funds if Exchange Level Funding is disabled.

Strategy Settings
Key Description Example
Name The strategy to use rsi
UsesSimultaneousProcessing This denotes whether multiple currencies are processed simultaneously with the strategy function OnSimultaneousSignals. Eg If you have multiple CurrencySettings and only wish to purchase BTC-USDT when XRP-DOGE is 1337, this setting is useful as you can analyse both signal events to output a purchase call for BTC true
CustomSettings This is a map where you can enter custom settings for a strategy. The RSI strategy allows for customisation of the upper, lower and length variables to allow you to change them from 70, 30 and 14 respectively to 69, 36, 12 "custom-settings": { "rsi-high": 70, "rsi-low": 30, "rsi-period": 14 }
UseExchangeLevelFunding This allows shared exchange funds to be used in your strategy. Requires UsesSimultaneousProcessing to be set to true to use false
ExchangeLevelFunding This is a list of funding definitions if UseExchangeLevelFunding is set to true See below table
Funding Config Settings
Key Description Example
ExchangeName The exchange to set funds. See here for a list of supported exchanges Binance
Asset The asset type to set funds. Typically, this will be spot, however, see this package for the various asset types GoCryptoTrader supports spot
Currency The currency to set funds BTC
InitialFunds The initial funding for the currency 1337
TransferFee If your strategy utilises transferring of funds via the Funding Manager, this is deducted upon doing so 0.005
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrFundsNotFound used when funds are requested but the funding is not found in the manager
	ErrFundsNotFound = errors.New("funding not found")
	// ErrAlreadyExists used when a matching item or pair is already in the funding manager
	ErrAlreadyExists = errors.New("funding already exists")
	// ErrUSDTrackingDisabled used when attempting to track USD values when disabled
	ErrUSDTrackingDisabled = errors.New("USD tracking disabled")
)

Functions

This section is empty.

Types

type FundManager

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

FundManager is the benevolent holder of all funding levels across all currencies used in the backtester

func SetupFundingManager

func SetupFundingManager(usingExchangeLevelFunding, disableUSDTracking bool) *FundManager

SetupFundingManager creates the funding holder. It carries knowledge about levels of funding across all execution handlers and enables fund transfers

func (*FundManager) AddItem

func (f *FundManager) AddItem(item *Item) error

AddItem appends a new funding item. Will reject if exists by exchange asset currency

func (*FundManager) AddPair

func (f *FundManager) AddPair(p *Pair) error

AddPair adds a pair to the fund manager if it does not exist

func (*FundManager) AddUSDTrackingData

func (f *FundManager) AddUSDTrackingData(k *kline.DataFromKline) error

AddUSDTrackingData adds USD tracking data to a funding item only in the event that it is not USD and there is data

func (*FundManager) CreateSnapshot

func (f *FundManager) CreateSnapshot(t time.Time)

CreateSnapshot creates a Snapshot for an event's point in time as funding.snapshots is a map, it allows for the last event in the chronological list to establish the canon at X time

func (*FundManager) Exists

func (f *FundManager) Exists(item *Item) bool

Exists verifies whether there is a funding item that exists with the same exchange, asset and currency

func (*FundManager) GenerateReport

func (f *FundManager) GenerateReport() *Report

GenerateReport builds report data for result HTML report

func (*FundManager) GetFundingForEAC

func (f *FundManager) GetFundingForEAC(exch string, a asset.Item, c currency.Code) (*Item, error)

GetFundingForEAC This will construct a funding based on the exchange, asset, currency code

func (*FundManager) GetFundingForEAP

func (f *FundManager) GetFundingForEAP(exch string, a asset.Item, p currency.Pair) (*Pair, error)

GetFundingForEAP This will construct a funding based on the exchange, asset, currency pair

func (*FundManager) GetFundingForEvent

func (f *FundManager) GetFundingForEvent(ev common.EventHandler) (*Pair, error)

GetFundingForEvent This will construct a funding based on a backtesting event

func (*FundManager) IsUsingExchangeLevelFunding

func (f *FundManager) IsUsingExchangeLevelFunding() bool

IsUsingExchangeLevelFunding returns if using usingExchangeLevelFunding

func (*FundManager) Reset

func (f *FundManager) Reset()

Reset clears all settings

func (*FundManager) Transfer

func (f *FundManager) Transfer(amount decimal.Decimal, sender, receiver *Item, inclusiveFee bool) error

Transfer allows transferring funds from one pretend exchange to another

func (*FundManager) USDTrackingDisabled

func (f *FundManager) USDTrackingDisabled() bool

USDTrackingDisabled clears all settings

type IFundTransferer

type IFundTransferer interface {
	IsUsingExchangeLevelFunding() bool
	Transfer(decimal.Decimal, *Item, *Item, bool) error
	GetFundingForEAC(string, asset.Item, currency.Code) (*Item, error)
	GetFundingForEvent(common.EventHandler) (*Pair, error)
	GetFundingForEAP(string, asset.Item, currency.Pair) (*Pair, error)
}

IFundTransferer allows for funding amounts to be transferred implementation can be swapped for live transferring

type IFundingManager

type IFundingManager interface {
	Reset()
	IsUsingExchangeLevelFunding() bool
	GetFundingForEAC(string, asset.Item, currency.Code) (*Item, error)
	GetFundingForEvent(common.EventHandler) (*Pair, error)
	GetFundingForEAP(string, asset.Item, currency.Pair) (*Pair, error)
	Transfer(decimal.Decimal, *Item, *Item, bool) error
	GenerateReport() *Report
	AddUSDTrackingData(*kline.DataFromKline) error
	CreateSnapshot(time.Time)
	USDTrackingDisabled() bool
}

IFundingManager limits funding usage for portfolio event handling

type IPairReader

type IPairReader interface {
	BaseInitialFunds() decimal.Decimal
	QuoteInitialFunds() decimal.Decimal
	BaseAvailable() decimal.Decimal
	QuoteAvailable() decimal.Decimal
}

IPairReader is used to limit pair funding functions to readonly

type IPairReleaser

type IPairReleaser interface {
	IncreaseAvailable(decimal.Decimal, order.Side)
	Release(decimal.Decimal, decimal.Decimal, order.Side) error
}

IPairReleaser limits funding usage for exchange event handling

type IPairReserver

type IPairReserver interface {
	IPairReader
	CanPlaceOrder(order.Side) bool
	Reserve(decimal.Decimal, order.Side) error
}

IPairReserver limits funding usage for portfolio event handling

type Item

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

Item holds funding data per currency item

func CreateItem

func CreateItem(exch string, a asset.Item, ci currency.Code, initialFunds, transferFee decimal.Decimal) (*Item, error)

CreateItem creates a new funding item

func (*Item) BasicEqual

func (i *Item) BasicEqual(exch string, a asset.Item, currency, pairedCurrency currency.Code) bool

BasicEqual checks for equality via passed in values

func (*Item) CanPlaceOrder

func (i *Item) CanPlaceOrder() bool

CanPlaceOrder checks if the item has any funds available

func (*Item) Equal

func (i *Item) Equal(item *Item) bool

Equal checks for equality via an Item to compare to

func (*Item) IncreaseAvailable

func (i *Item) IncreaseAvailable(amount decimal.Decimal)

IncreaseAvailable adds funding to the available amount

func (*Item) MatchesCurrency

func (i *Item) MatchesCurrency(c currency.Code) bool

MatchesCurrency checks that an item's currency is equal

func (*Item) MatchesExchange

func (i *Item) MatchesExchange(item *Item) bool

MatchesExchange checks that an item's exchange is equal

func (*Item) MatchesItemCurrency

func (i *Item) MatchesItemCurrency(item *Item) bool

MatchesItemCurrency checks that an item's currency is equal

func (*Item) Release

func (i *Item) Release(amount, diff decimal.Decimal) error

Release reduces the amount of funding reserved and adds any difference back to the available amount

func (*Item) Reserve

func (i *Item) Reserve(amount decimal.Decimal) error

Reserve allocates an amount of funds to be used at a later time it prevents multiple events from claiming the same resource

type ItemSnapshot

type ItemSnapshot struct {
	Time          time.Time
	Available     decimal.Decimal
	USDClosePrice decimal.Decimal
	USDValue      decimal.Decimal
}

ItemSnapshot holds USD values to allow for tracking across backtesting results

type Pair

type Pair struct {
	Base  *Item
	Quote *Item
}

Pair holds two currencies that are associated with each other

func CreatePair

func CreatePair(base, quote *Item) (*Pair, error)

CreatePair adds two funding items and associates them with one another the association allows for the same currency to be used multiple times when usingExchangeLevelFunding is false. eg BTC-USDT and LTC-USDT do not share the same USDT level funding

func (*Pair) BaseAvailable

func (p *Pair) BaseAvailable() decimal.Decimal

BaseAvailable returns the available funds from the base in a currency pair

func (*Pair) BaseInitialFunds

func (p *Pair) BaseInitialFunds() decimal.Decimal

BaseInitialFunds returns the initial funds from the base in a currency pair

func (*Pair) CanPlaceOrder

func (p *Pair) CanPlaceOrder(side order.Side) bool

CanPlaceOrder does a > 0 check to see if there are any funds to place an order with changes which currency to affect based on the order side

func (*Pair) IncreaseAvailable

func (p *Pair) IncreaseAvailable(amount decimal.Decimal, side order.Side)

IncreaseAvailable adds funding to the available amount changes which currency to affect based on the order side

func (*Pair) QuoteAvailable

func (p *Pair) QuoteAvailable() decimal.Decimal

QuoteAvailable returns the available funds from the quote in a currency pair

func (*Pair) QuoteInitialFunds

func (p *Pair) QuoteInitialFunds() decimal.Decimal

QuoteInitialFunds returns the initial funds from the quote in a currency pair

func (*Pair) Release

func (p *Pair) Release(amount, diff decimal.Decimal, side order.Side) error

Release reduces the amount of funding reserved and adds any difference back to the available amount changes which currency to affect based on the order side

func (*Pair) Reserve

func (p *Pair) Reserve(amount decimal.Decimal, side order.Side) error

Reserve allocates an amount of funds to be used at a later time it prevents multiple events from claiming the same resource changes which currency to affect based on the order side

type Report

type Report struct {
	DisableUSDTracking        bool
	UsingExchangeLevelFunding bool
	Items                     []ReportItem
	USDTotalsOverTime         map[time.Time]ItemSnapshot
}

Report holds all funding data for result reporting

type ReportItem

type ReportItem struct {
	Exchange             string
	Asset                asset.Item
	Currency             currency.Code
	TransferFee          decimal.Decimal
	InitialFunds         decimal.Decimal
	FinalFunds           decimal.Decimal
	USDInitialFunds      decimal.Decimal
	USDInitialCostForOne decimal.Decimal
	USDFinalFunds        decimal.Decimal
	USDFinalCostForOne   decimal.Decimal
	Snapshots            []ItemSnapshot

	USDPairCandle *kline.DataFromKline
	Difference    decimal.Decimal
	ShowInfinite  bool
	PairedWith    currency.Code
}

ReportItem holds reporting fields

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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