Files
gocryptotrader/gctscript/wrappers/validator/validator.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

286 lines
6.8 KiB
Go

package validator
import (
"context"
"math/rand"
"time"
"github.com/thrasher-corp/gocryptotrader/core"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/account"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/deposit"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
)
const (
validatorOpen float64 = 5000
validatorHigh float64 = 6000
validatorLow float64 = 5500
validatorClose float64 = 5700
validatorVol float64 = 10
)
// Exchanges validator for test execution/scripts
func (w Wrapper) Exchanges(enabledOnly bool) []string {
if enabledOnly {
return []string{
"hello world",
}
}
return []string{
"nope",
}
}
// IsEnabled returns if requested exchange is enabled or disabled
func (w Wrapper) IsEnabled(exch string) (v bool) {
if exch == exchError.String() {
return
}
return true
}
// Orderbook validator for test execution/scripts
func (w Wrapper) Orderbook(ctx context.Context, exch string, pair currency.Pair, item asset.Item) (*orderbook.Base, error) {
if exch == exchError.String() {
return nil, errTestFailed
}
return &orderbook.Base{
Exchange: exch,
Asset: item,
Pair: pair,
Bids: []orderbook.Item{
{
Amount: 1,
Price: 1,
},
},
Asks: []orderbook.Item{
{
Amount: 1,
Price: 1,
},
},
}, nil
}
// Ticker validator for test execution/scripts
func (w Wrapper) Ticker(ctx context.Context, exch string, pair currency.Pair, item asset.Item) (*ticker.Price, error) {
if exch == exchError.String() {
return nil, errTestFailed
}
return &ticker.Price{
Last: 1,
High: 2,
Low: 3,
Bid: 4,
Ask: 5,
Volume: 6,
QuoteVolume: 7,
PriceATH: 8,
Open: 9,
Close: 10,
Pair: pair,
ExchangeName: exch,
AssetType: item,
LastUpdated: time.Now(),
}, nil
}
// Pairs validator for test execution/scripts
func (w Wrapper) Pairs(exch string, _ bool, _ asset.Item) (*currency.Pairs, error) {
if exch == exchError.String() {
return nil, errTestFailed
}
pairs, err := currency.NewPairsFromStrings([]string{"btc_usd",
"btc_aud",
"btc_ltc"})
if err != nil {
return nil, err
}
return &pairs, nil
}
// QueryOrder validator for test execution/scripts
func (w Wrapper) QueryOrder(ctx context.Context, exch, _ string, _ currency.Pair, _ asset.Item) (*order.Detail, error) {
if exch == exchError.String() {
return nil, errTestFailed
}
pair, err := currency.NewPairFromString("BTCAUD")
if err != nil {
return nil, err
}
return &order.Detail{
Exchange: exch,
AccountID: "hello",
OrderID: "1",
Pair: pair,
Side: order.Ask,
Type: order.Limit,
Date: time.Now(),
Status: order.Cancelled,
Price: 1,
Amount: 2,
ExecutedAmount: 1,
RemainingAmount: 0,
Fee: 0,
Trades: []order.TradeHistory{
{
TID: "",
Price: 1,
Amount: 2,
Exchange: exch,
Type: order.Limit,
Side: order.Ask,
Fee: 0,
Description: "",
},
},
}, nil
}
// SubmitOrder validator for test execution/scripts
func (w Wrapper) SubmitOrder(ctx context.Context, o *order.Submit) (*order.SubmitResponse, error) {
if o == nil {
return nil, errTestFailed
}
if o.Exchange == exchError.String() {
return nil, errTestFailed
}
resp, err := o.DeriveSubmitResponse(o.Exchange)
if err != nil {
return nil, err
}
resp.Status = order.Rejected
if o.Exchange == "true" {
resp.Status = order.New
}
return resp, nil
}
// CancelOrder validator for test execution/scripts
func (w Wrapper) CancelOrder(ctx context.Context, exch, orderid string, cp currency.Pair, a asset.Item) (bool, error) {
if exch == exchError.String() {
return false, errTestFailed
}
if orderid == "" {
return false, errTestFailed
}
if !cp.IsEmpty() && cp.IsInvalid() {
return false, errTestFailed
}
if a != asset.Empty && !a.IsValid() {
return false, errTestFailed
}
return true, nil
}
// AccountInformation validator for test execution/scripts
func (w Wrapper) AccountInformation(ctx context.Context, exch string, assetType asset.Item) (account.Holdings, error) {
if exch == exchError.String() {
return account.Holdings{}, errTestFailed
}
return account.Holdings{
Exchange: exch,
Accounts: []account.SubAccount{
{
ID: exch,
AssetType: assetType,
Currencies: []account.Balance{
{
Currency: currency.Code{
Item: &currency.Item{
ID: 0,
FullName: "Bitcoin",
Symbol: "BTC",
Role: 1,
AssocChain: "",
},
},
Total: 100,
Hold: 0,
},
},
},
},
}, nil
}
// DepositAddress validator for test execution/scripts
func (w Wrapper) DepositAddress(exch, chain string, _ currency.Code) (*deposit.Address, error) {
if exch == exchError.String() {
return nil, errTestFailed
}
return &deposit.Address{Address: core.BitcoinDonationAddress}, nil
}
// WithdrawalCryptoFunds validator for test execution/scripts
func (w Wrapper) WithdrawalCryptoFunds(ctx context.Context, r *withdraw.Request) (out string, err error) {
if r.Exchange == exchError.String() {
return r.Exchange, errTestFailed
}
return "", nil
}
// WithdrawalFiatFunds validator for test execution/scripts
func (w Wrapper) WithdrawalFiatFunds(ctx context.Context, _ string, r *withdraw.Request) (out string, err error) {
if r.Exchange == exchError.String() {
return r.Exchange, errTestFailed
}
return "123", nil
}
// OHLCV returns open high low close volume candles for requested exchange/pair/asset/start & end time
func (w Wrapper) OHLCV(ctx context.Context, exch string, p currency.Pair, a asset.Item, start, end time.Time, i kline.Interval) (kline.Item, error) {
if exch == exchError.String() {
return kline.Item{}, errTestFailed
}
var candles []kline.Candle
candles = append(candles, kline.Candle{
Time: start,
Open: validatorOpen,
High: validatorHigh,
Low: validatorLow,
Close: validatorClose,
Volume: validatorVol,
})
for x := 1; x < 200; x++ {
r := validatorLow + rand.Float64()*(validatorHigh-validatorLow) //nolint:gosec // no need to import crypo/rand
candle := kline.Candle{
Time: candles[x-1].Time.Add(-i.Duration()),
Open: r,
High: r,
Low: r,
Close: r,
Volume: r,
}
candles = append(candles, candle)
}
return kline.Item{
Exchange: exch,
Pair: p,
Asset: a,
Interval: i,
Candles: candles,
}, nil
}