Files
gocryptotrader/backtester/report/report.go
Scott f929b4d51e backtester: Futures handling & FTX Cash and Carry example strategy (#930)
* implements futures functions and GRPC functions on new branch

* lint and test fixes

* Fix uneven split pnl. Adds collateral weight test. docs. New clear func

* Test protection if someone has zero collateral

* Uses string instead of double for accuracy

* Fixes old code panic

* context, match, docs

* Addresses Shazniterinos, var names, expanded tests

* Returns subaccount name, provides USD values when offlinecalc

* Fixes oopsie

* Fixes cool bug which allowed made up subaccount results

* Subaccount override on FTX, subaccount results for collateral

* Strenghten collateral account info checks. Improve FTX test

* English is my first language

* Fixes oopsies

* Adds some conceptual futures order details to track PNL

* Initial design of future order processing in the backtester

* Introduces futures concept for collateral and spot/futures config diffs

* Fixes most tests

* Simple designs for collateral funding pair concept

* Expands interface use so much it hurts

* Implements more collateral interfaces

* Adds liquidation, adds strategy, struggles with Binance

* Attempts at getting FTX to work

* Adds calculatePNL as a wrapper function and adds an `IsFutures` asset check

* Successfully loads backtester with collateral currency

* Fails to really get much going for supporting futures

* Merges master changes

* Fleshes out how FTX processes collateral

* Further FTX collateral workings

* hooks up more ftx collateral and pnl calculations

* more funcs to flesh out handling

* Adds more links, just can't fit the pieces together :(

* Greatly expands futures order processing

* Fleshes out position tracker to also handle asset and exchange +testing

* RM linkedOrderID. rn positioncontroller, unexport

* Successfully tracks futures order positions

* Fails to calculate PNL

* Calculates pnl from orders accurately with exception to flipping orders

* Calculates PNL from orders

* Adds another controller layer to make it ez from orderstore

* Backtester now compiles. Adds test coverage

* labels things add scaling collateral test

* Calculates pnl in line with fees

* Mostly accurate PNL, with exception to appending with diff prices

* Adds locks, adds rpc function

* grpc implementations

* Gracefully handles rpc function

* beautiful tests!

* rejiggles tests to polish

* Finishes FTX testing, adds comments

* Exposes collateral calculations to rpc

* Adds commands and testing for rpcserver.go functions

* Increase testing and fix up backtester code

* Returns cool changes to original branch

* end of day fixes

* Fixing some tests

* Fixing tests 🎉

* Fixes all the tests

* Splits the backtester setup and running into different files

* Merge, minor fixes

* Messing with some strategy updates

* Failed understanding at collateral usage

* Begins the creation of cash and carry strategy

* Adds underlying pair, adds filldependentevent for futures

* Completes fill prerequsite event implementation. Can't short though

* Some bug fixes

* investigating funds

* CAN NOW CREATE A SHORT ORDER

* Minor change in short size

* Fixes for unrealised PNL & collateral rendering

* Fixes lint and tests

* Adds some verbosity

* Updates to pnl calc

* Tracks pnl for short orders, minor update to strategy

* Close and open event based on conditions

* Adds pnl data for currency statistics

* Working through PNL calculation automatically. Now panics

* Adds tracking, is blocked from design

* Work to flesh out closing a position

* vain attempts at tracking zeroing out bugs

* woww, super fun new subloggers 🎉

* Begins attempt at automatically handling contracts and collateral based on direction

* Merge master + fixes

* Investigating issues with pnl and holdings

* Minor pnl fixes

* Fixes future position sizing, needs contract sizing

* Can render pnl results, focussing on funding statistics

* tracking candles for futures, but why not btc

* Improves funding statistics

* Colours and stats

* Fixes collateral and snapshot bugs

* Completes test

* Fixes totals bug

* Fix double buy, expand stats, fixes usd totals, introduce interface

* Begins report formatting and calculations

* Appends pnl to receiving curr. Fixes map[time]. accurate USD

* Improves report output rendering

* PNL stats in report. New tests for futures

* Fixes existing tests before adding new coverage

* Test coverage

* Completes portfolio coverage

* Increase coverage exchange, portfolio. fix size bug. NEW CHART

* WHAT IS GOING ON WITH PNL

* Fixes PNL calculation. Adds ability to skip om futures tracking

* minor commit before merge

* Adds basic liquidation to backtester

* Changes liquidation to order based

* Liquidationnnnnn

* Further fleshes out liquidations

* Completes liquidations in a honorable manner. Adds AppendReasonf

* Beginnings of spot futures gap chart. Needs to link currencies to render difference

* Removes fake liquidation. Adds cool new chart

* Fixes somet tests,allows for zero fee value v nil distinction,New tests

* Some annoying test fixes that took too long

* portfolio coverage

* holding coverage, privatisation funding

* Testwork

* boring tests

* engine coverage

* More backtesting coverage

* Funding, strategy, report test coverage

* Completes coverage of report package

* Documentation, fixes some assumptions on asset errors

* Changes before master merge

* Lint and Tests

* defaults to non-coloured rendering

* Chart rendering

* Fixes surprise non-local-lints

* Niterinos to the extremeos

* Fixes merge problems

* The linter splintered across the glinting plinths

* Many nits addressed. Now sells spot position on final candle

* Adds forgotten coverage

* Adds ability to size futures contracts to match spot positions.

* fixes order sell sizing

* Adds tests to sizing. Fixes charting issue

* clint splintered the linters with flint

* Improves stats, stat rendering

* minifix

* Fixes tests and fee bug

* Merge fixeroos

* Microfixes

* Updates orderPNL on first Correctly utilises fees. Adds committed funds

* New base funcs. New order summary

* Fun test updates

* Fix logo colouring

* Fixes niteroonies

* Fix report

* BAD COMMIT

* Fixes funding issues.Updates default fee rates.Combines cashcarry case

* doc regen

* Now returns err

* Fixes sizing bug issue introduced in PR

* Fixes fun fee/total US value bug

* Fix chart bug. Show log charts with disclaimer

* sellside fee

* fixes fee and slippage view

* Fixed slippage price issue

* Fixes calculation and removes rendering

* Fixes stats and some rendering

* Merge fix

* Fixes merge issues

* go mod tidy, lint updates

* New linter attempt

* Version bump in appveyor and makefile

* Regex filename, config fixes, template h2 fixes

* Removes bad stats.

* neatens config builder. Moves filename generator

* Fixes issue where linter wants to fix my spelling

* Fixes pointers and starts
2022-06-30 15:43:41 +10:00

233 lines
7.5 KiB
Go

package report
import (
"fmt"
"html/template"
"os"
"path/filepath"
"strings"
"time"
"github.com/shopspring/decimal"
"github.com/thrasher-corp/gocryptotrader/backtester/common"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/log"
)
// GenerateReport sends final data from statistics to a template
// to create a lovely final report for someone to view
func (d *Data) GenerateReport() error {
log.Info(common.Report, "generating report")
err := d.enhanceCandles()
if err != nil {
return err
}
for i := range d.OriginalCandles {
for j := range d.OriginalCandles[i].Candles {
if d.OriginalCandles[i].Candles[j].ValidationIssues == "" {
continue
}
d.Warnings = append(d.Warnings, Warning{
Exchange: d.OriginalCandles[i].Exchange,
Asset: d.OriginalCandles[i].Asset,
Pair: d.OriginalCandles[i].Pair,
Message: fmt.Sprintf("candle data %v", d.OriginalCandles[i].Candles[j].ValidationIssues),
})
}
}
for i := range d.EnhancedCandles {
if len(d.EnhancedCandles[i].Candles) >= maxChartLimit {
d.EnhancedCandles[i].IsOverLimit = true
d.EnhancedCandles[i].Candles = d.EnhancedCandles[i].Candles[:maxChartLimit]
}
}
if d.Statistics.FundingStatistics != nil {
d.HoldingsOverTimeChart, err = createHoldingsOverTimeChart(d.Statistics.FundingStatistics.Items)
if err != nil {
return err
}
if !d.Statistics.FundingStatistics.Report.DisableUSDTracking {
d.USDTotalsChart, err = createUSDTotalsChart(d.Statistics.FundingStatistics.TotalUSDStatistics.HoldingValues, d.Statistics.FundingStatistics.Items)
if err != nil {
return err
}
}
}
if d.Statistics.HasCollateral {
d.PNLOverTimeChart, err = createPNLCharts(d.Statistics.ExchangeAssetPairStatistics)
if err != nil {
return err
}
d.FuturesSpotDiffChart, err = createFuturesSpotDiffChart(d.Statistics.ExchangeAssetPairStatistics)
if err != nil {
return err
}
}
tmpl := template.Must(
template.ParseFiles(d.TemplatePath),
)
fn := d.Config.Nickname
if fn != "" {
fn += "-"
}
fn += d.Statistics.StrategyName + "-"
fn += time.Now().Format("2006-01-02-15-04-05")
fileName, err := common.GenerateFileName(fn, "html")
if err != nil {
return err
}
var f *os.File
f, err = os.Create(
filepath.Join(d.OutputPath,
fileName,
),
)
if err != nil {
return err
}
defer func() {
err = f.Close()
if err != nil {
log.Error(common.Report, err)
}
}()
err = tmpl.Execute(f, d)
if err != nil {
return err
}
log.Infof(common.Report, "successfully saved report to %v", filepath.Join(d.OutputPath, fileName))
return nil
}
// AddKlineItem appends a SET of candles for the report to enhance upon
// generation
func (d *Data) AddKlineItem(k *kline.Item) {
d.OriginalCandles = append(d.OriginalCandles, k)
}
// UpdateItem updates an existing kline item for LIVE data usage
func (d *Data) UpdateItem(k *kline.Item) {
if len(d.OriginalCandles) == 0 {
d.OriginalCandles = append(d.OriginalCandles, k)
} else {
d.OriginalCandles[0].Candles = append(d.OriginalCandles[0].Candles, k.Candles...)
d.OriginalCandles[0].RemoveDuplicates()
}
}
// enhanceCandles will enhance candle data with order information allowing
// report charts to have annotations to highlight buy and sell events
func (d *Data) enhanceCandles() error {
if len(d.OriginalCandles) == 0 {
return errNoCandles
}
if d.Statistics == nil {
return errStatisticsUnset
}
d.Statistics.RiskFreeRate = d.Statistics.RiskFreeRate.Mul(decimal.NewFromInt(100))
for intVal := range d.OriginalCandles {
lookup := d.OriginalCandles[intVal]
enhancedKline := EnhancedKline{
Exchange: lookup.Exchange,
Asset: lookup.Asset,
Pair: lookup.Pair,
Interval: lookup.Interval,
Watermark: fmt.Sprintf("%s - %s - %s", strings.Title(lookup.Exchange), lookup.Asset.String(), lookup.Pair.Upper()), // nolint // Title usage
}
statsForCandles :=
d.Statistics.ExchangeAssetPairStatistics[lookup.Exchange][lookup.Asset][lookup.Pair]
if statsForCandles == nil {
continue
}
requiresIteration := false
if len(statsForCandles.Events) != len(d.OriginalCandles[intVal].Candles) {
requiresIteration = true
}
for j := range d.OriginalCandles[intVal].Candles {
_, offset := time.Now().Zone()
tt := d.OriginalCandles[intVal].Candles[j].Time.Add(time.Duration(offset) * time.Second)
enhancedCandle := DetailedCandle{
UnixMilli: tt.UTC().UnixMilli(),
Open: d.OriginalCandles[intVal].Candles[j].Open,
High: d.OriginalCandles[intVal].Candles[j].High,
Low: d.OriginalCandles[intVal].Candles[j].Low,
Close: d.OriginalCandles[intVal].Candles[j].Close,
Volume: d.OriginalCandles[intVal].Candles[j].Volume,
VolumeColour: "rgba(50, 204, 30, 0.5)",
}
if j != 0 {
if d.OriginalCandles[intVal].Candles[j].Close < d.OriginalCandles[intVal].Candles[j-1].Close {
enhancedCandle.VolumeColour = "rgba(232, 3, 3, 0.5)"
}
}
if !requiresIteration {
if statsForCandles.Events[intVal].Time.Equal(d.OriginalCandles[intVal].Candles[j].Time) &&
(statsForCandles.Events[intVal].SignalEvent == nil || statsForCandles.Events[intVal].SignalEvent.GetDirection() == order.MissingData) &&
len(enhancedKline.Candles) > 0 {
enhancedCandle.copyCloseFromPreviousEvent(&enhancedKline)
}
} else {
for k := range statsForCandles.Events {
if statsForCandles.Events[k].SignalEvent.GetTime().Equal(d.OriginalCandles[intVal].Candles[j].Time) &&
statsForCandles.Events[k].SignalEvent.GetDirection() == order.MissingData &&
len(enhancedKline.Candles) > 0 {
enhancedCandle.copyCloseFromPreviousEvent(&enhancedKline)
}
}
}
for k := range statsForCandles.FinalOrders.Orders {
if statsForCandles.FinalOrders.Orders[k].Order == nil ||
!statsForCandles.FinalOrders.Orders[k].Order.Date.Equal(d.OriginalCandles[intVal].Candles[j].Time) {
continue
}
// an order was placed here, can enhance chart!
enhancedCandle.MadeOrder = true
enhancedCandle.OrderAmount = decimal.NewFromFloat(statsForCandles.FinalOrders.Orders[k].Order.Amount)
enhancedCandle.PurchasePrice = statsForCandles.FinalOrders.Orders[k].Order.Price
enhancedCandle.OrderDirection = statsForCandles.FinalOrders.Orders[k].Order.Side
if enhancedCandle.OrderDirection == order.Buy {
enhancedCandle.Colour = "green"
enhancedCandle.Position = "aboveBar"
enhancedCandle.Shape = "arrowDown"
} else if enhancedCandle.OrderDirection == order.Sell {
enhancedCandle.Colour = "red"
enhancedCandle.Position = "belowBar"
enhancedCandle.Shape = "arrowUp"
}
enhancedCandle.Text = enhancedCandle.OrderDirection.String()
break
}
enhancedKline.Candles = append(enhancedKline.Candles, enhancedCandle)
}
d.EnhancedCandles = append(d.EnhancedCandles, enhancedKline)
}
return nil
}
func (d *DetailedCandle) copyCloseFromPreviousEvent(ek *EnhancedKline) {
// if the data is missing, ensure that all values just continue the previous candle's close price visually
d.Open = ek.Candles[len(ek.Candles)-1].Close
d.High = ek.Candles[len(ek.Candles)-1].Close
d.Low = ek.Candles[len(ek.Candles)-1].Close
d.Close = ek.Candles[len(ek.Candles)-1].Close
d.Colour = "white"
d.Position = "aboveBar"
d.Shape = "arrowDown"
d.Text = order.MissingData.String()
}
// UseDarkMode sets whether to use a dark theme by default
// for the html generated report
func (d *Data) UseDarkMode(use bool) {
d.UseDarkTheme = use
}