Files
gocryptotrader/backtester/report/report.go
Scott 017cdf1384 Backtester: Live trading upgrades (#1023)
* Modifications for a smoother live run

* Fixes data appending

* Successfully allows multi-currency live trading. Adds multiple currencies to live DCA strategy

* Attempting to get cash and carry working

* Poor attempts at sorting out data and appending it properly with USD in mind

* =designs new live data handler

* Updates cash and carry strat to work

* adds test coverage. begins closeallpositions function

* Updates cash and carry to work live

* New kline.Event type. Cancels orders on close. Rn types

* =Fixes USD funding issue

* =fixes tests

* fixes tests AGAIN

* adds coverage to close all orders

* crummy tests, should override

* more tests

* more tests

* more coverage

* removes scourge of currency.Pair maps. More tests

* missed currency stuff

* Fixes USD data issue & collateral issue. Needs to close ALL orders

* Now triggers updates on the very first data entry

* All my problems are solved now????

* fixes tests, extends coverage

* there is some really funky candle stuff going on

* my brain is melting

* better shutdown management, fixes freezing bug

* fixes data duplication issues, adds retries to requests

* reduces logging, adds verbose options

* expands coverage over all new functionality

* fixes fun bug from curr == curr to curr.Equal(curr)

* fixes setup issues and tests

* starts adding external wallet amounts for funding

* more setup for assets

* setup live fund calcs and placing orders

* successfully performs automated cash and carry

* merge fixes

* funding properly set at all times

* fixes some bugs, need to address currencystatistics still

* adds 'appeneded' trait, attempts to fix some stats

* fixes stat bugs, adds cool new fetchfees feature

* fixes terrible processing bugs

* tightens realorder stats, sadly loses some live stats

* this actually sets everything correctly for bothcd ..cd ..cd ..cd ..cd ..!

* fix tests

* coverage

* beautiful new test coverage

* docs

* adds new fee getter delayer

* commits from the correct directory

* Lint

* adds verbose to fund manager

* Fix bug in t2b2 strat. Update dca live config. Docs

* go mod tidy

* update buf

* buf + test improvement

* Post merge fixes

* fixes surprise offset bug

* fix sizing restrictions for cash and carry

* fix server lints

* merge fixes

* test fixesss

* lintle fixles

* slowloris

* rn run to task, bug fixes, close all on close

* rpc lint and fixes

* bugfix: order manager not processing orders properly

* somewhat addresses nits

* absolutely broken end of day commit

* absolutely massive knockon effects from nits

* massive knockon effects continue

* fixes things

* address remaining nits

* jk now fixes things

* addresses the easier nits

* more nit fixers

* more niterinos addressederinos

* refactors holdings and does some nits

* so buf

* addresses some nits, fixes holdings bugs

* cleanup

* attempts to fix alert chans to prevent many chans waiting?

* terrible code, will revert

* to be reviewed in detail tomorrow

* Fixes up channel system

* smashes those nits

* fixes extra candles, fixes collateral bug, tests

* fixes data races, introduces reflection

* more checks n tests

* Fixes cash and carry issues. Fixes more cool bugs

* fixes ~typer~ typo

* replace spot strats from ftx to binance

* fixes all the tests I just destroyed

* removes example path, rm verbose

* 1) what 2) removes FTX references from the Backtester

* renamed, non-working strategies

* Removes FTX references almost as fast as sbf removes funds

* regen docs, add contrib names,sort contrib names

* fixes merge renamings

* Addresses nits. Fixes setting API credentials. Fixes Binance limit retrieval

* Fixes live order bugs with real orders and without

* Apply suggestions from code review

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>

* Update backtester/engine/live.go

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>

* Update backtester/engine/live.go

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>

* Update backtester/config/strategyconfigbuilder/main.go

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>

* updates docs

* even better docs

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>
2023-01-05 13:03:17 +11:00

240 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 {
if d.TemplatePath == "" || d.OutputPath == "" {
return nil
}
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
}
// SetKlineData updates an existing kline item for LIVE data usage
func (d *Data) SetKlineData(k *kline.Item) error {
if len(d.OriginalCandles) == 0 {
d.OriginalCandles = append(d.OriginalCandles, k)
return nil
}
for i := range d.OriginalCandles {
err := d.OriginalCandles[i].EqualSource(k)
if err != nil {
continue
}
d.OriginalCandles[i].Candles = append(d.OriginalCandles[i].Candles, k.Candles...)
d.OriginalCandles[i].RemoveDuplicateCandlesByTime()
return nil
}
d.OriginalCandles = append(d.OriginalCandles, k)
return nil
}
// 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:staticcheck // Ignore Title usage warning
}
statsForCandles :=
d.Statistics.ExchangeAssetPairStatistics[lookup.Exchange][lookup.Asset][lookup.Pair.Base.Item][lookup.Pair.Quote.Item]
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) {
cp := ek.Candles[len(ek.Candles)-1].Close
// if the data is missing, ensure that all values just continue the previous candle's close price visually
d.Open = cp
d.High = cp
d.Low = cp
d.Close = cp
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
}