Files
gocryptotrader/database/repository/candle/candle.go
Scott 197ef2df21 Feature: Data history manager engine subsystem (#693)
* Adds lovely initial concept for historical data doer

* Adds ability to save tasks. Adds config. Adds startStop to engine

* Has a database microservice without use of globals! Further infrastructure design. Adds readme

* Commentary to help design

* Adds migrations for database

* readme and adds database models

* Some modelling that doesn't work end of day

* Completes datahistoryjob sql.Begins datahistoryjobresult

* Adds datahistoryjob functions to retreive job results. Adapts subsystem

* Adds process for upserting jobs and job results to the database

* Broken end of day weird sqlboiler crap

* Fixes issue with SQL generation.

* RPC generation and addition of basic upsert command

* Renames types

* Adds rpc functions

* quick commit before context swithc. Exchanges aren't being populated

* Begin the tests!

* complete sql tests. stop failed jobs. CLI command creation

* Defines rpc commands

* Fleshes out RPC implementation

* Expands testing

* Expands testing, removes double remove

* Adds coverage of data history subsystem, expands errors and nil checks

* Minor logic improvement

* streamlines datahistory test setup

* End of day minor linting

* Lint, convert simplify, rpc expansion, type expansion, readme expansion

* Documentation update

* Renames for consistency

* Completes RPC server commands

* Fixes tests

* Speeds up testing by reducing unnecessary actions. Adds maxjobspercycle config

* Comments for everything

* Adds missing result string. checks interval supported. default start end cli

* Fixes ID problem. Improves binance trade fetch. job ranges are processed

* adds dbservice coverage. adds rpcserver coverage

* docs regen, uses dbcon interface, reverts binance, fixes races, toggle manager

* Speed up tests, remove bad global usage, fix uuid check

* Adds verbose. Updates docs. Fixes postgres

* Minor changes to logging and start stop

* Fixes postgres db tests, fixes postgres column typo

* Fixes old string typo,removes constraint,error parsing for nonreaders

* prevents dhm running when table doesn't exist. Adds prereq documentation

* Adds parallel, rmlines, err fix, comment fix, minor param fixes

* doc regen, common time range check and test updating

* Fixes job validation issues. Updates candle range checker.

* Ensures test cannot fail due to time.Now() shenanigans

* Fixes oopsie, adds documentation and a warn

* Fixes another time test, adjusts copy

* Drastically speeds up data history manager tests via function overrides

* Fixes summary bug and better logs

* Fixes local time test, fixes websocket tests

* removes defaults and comment,updates error messages,sets cli command args

* Fixes FTX trade processing

* Fixes issue where jobs got stuck if data wasn't returned but retrieval was successful

* Improves test speed. Simplifies trade verification SQL. Adds command help

* Fixes the oopsies

* Fixes use of query within transaction. Fixes trade err

* oopsie, not needed

* Adds missing data status. Properly ends job even when data is missing

* errors are more verbose and so have more words to describe them

* Doc regen for new status

* tiny test tinkering

* str := string("Removes .String()").String()

* Merge fixups

* Fixes a data race discovered during github actions

* Allows websocket test to pass consistently

* Fixes merge issue preventing datahistorymanager from starting via config

* Niterinos cmd defaults and explanations

* fixes default oopsie

* Fixes lack of nil protection

* Additional oopsie

* More detailed error for validating job exchange
2021-07-01 16:21:48 +10:00

351 lines
9.0 KiB
Go

package candle
import (
"context"
"database/sql"
"encoding/csv"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/thrasher-corp/gocryptotrader/database"
modelPSQL "github.com/thrasher-corp/gocryptotrader/database/models/postgres"
modelSQLite "github.com/thrasher-corp/gocryptotrader/database/models/sqlite3"
"github.com/thrasher-corp/gocryptotrader/database/repository"
"github.com/thrasher-corp/gocryptotrader/database/repository/exchange"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/sqlboiler/boil"
"github.com/thrasher-corp/sqlboiler/queries/qm"
)
// Series returns candle data
func Series(exchangeName, base, quote string, interval int64, asset string, start, end time.Time) (out Item, err error) {
if exchangeName == "" || base == "" || quote == "" || asset == "" || interval <= 0 {
return out, errInvalidInput
}
queries := []qm.QueryMod{
qm.Where("base = ?", strings.ToUpper(base)),
qm.Where("quote = ?", strings.ToUpper(quote)),
qm.Where("interval = ?", interval),
qm.Where("asset = ?", strings.ToLower(asset)),
}
exchangeUUID, errS := exchange.UUIDByName(exchangeName)
if errS != nil {
return out, errS
}
queries = append(queries, qm.Where("exchange_name_id = ?", exchangeUUID.String()))
if repository.GetSQLDialect() == database.DBSQLite3 {
queries = append(queries, qm.Where("timestamp between ? and ?", start.UTC().Format(time.RFC3339), end.UTC().Format(time.RFC3339)))
retCandle, errC := modelSQLite.Candles(queries...).All(context.Background(), database.DB.SQL)
if errC != nil {
return out, errC
}
for x := range retCandle {
t, errT := time.Parse(time.RFC3339, retCandle[x].Timestamp)
if errT != nil {
return out, errT
}
out.Candles = append(out.Candles, Candle{
Timestamp: t,
Open: retCandle[x].Open,
High: retCandle[x].High,
Low: retCandle[x].Low,
Close: retCandle[x].Close,
Volume: retCandle[x].Volume,
})
}
} else {
queries = append(queries, qm.Where("timestamp between ? and ?", start.UTC(), end.UTC()))
retCandle, errC := modelPSQL.Candles(queries...).All(context.Background(), database.DB.SQL)
if errC != nil {
return out, errC
}
for x := range retCandle {
out.Candles = append(out.Candles, Candle{
Timestamp: retCandle[x].Timestamp,
Open: retCandle[x].Open,
High: retCandle[x].High,
Low: retCandle[x].Low,
Close: retCandle[x].Close,
Volume: retCandle[x].Volume,
})
}
}
if len(out.Candles) < 1 {
return out, fmt.Errorf("%w: %s %s %s %v %s", ErrNoCandleDataFound, exchangeName, base, quote, interval, asset)
}
out.ExchangeID = exchangeName
out.Interval = interval
out.Base = base
out.Quote = quote
out.Asset = asset
return out, err
}
// DeleteCandles will delete all existing matching candles
func DeleteCandles(in *Item) (int64, error) {
if database.DB.SQL == nil {
return 0, database.ErrDatabaseSupportDisabled
}
if len(in.Candles) < 1 {
return 0, errNoCandleData
}
ctx := context.Background()
queries := []qm.QueryMod{
qm.Where("base = ?", strings.ToUpper(in.Base)),
qm.Where("quote = ?", strings.ToUpper(in.Quote)),
qm.Where("interval = ?", in.Interval),
qm.Where("asset = ?", strings.ToLower(in.Asset)),
qm.Where("exchange_name_id = ?", in.ExchangeID),
}
if repository.GetSQLDialect() == database.DBSQLite3 {
queries = append(queries, qm.Where("timestamp between ? and ?", in.Candles[0].Timestamp.UTC().Format(time.RFC3339), in.Candles[len(in.Candles)-1].Timestamp.UTC().Format(time.RFC3339)))
return deleteSQLite(ctx, queries)
}
queries = append(queries, qm.Where("timestamp between ? and ?", in.Candles[0].Timestamp.UTC(), in.Candles[len(in.Candles)-1].Timestamp.UTC()))
return deletePostgres(ctx, queries)
}
func deleteSQLite(ctx context.Context, queries []qm.QueryMod) (int64, error) {
retCandle, err := modelSQLite.Candles(queries...).All(context.Background(), database.DB.SQL)
if err != nil {
return 0, err
}
var tx *sql.Tx
tx, err = database.DB.SQL.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
var totalDeleted int64
totalDeleted, err = retCandle.DeleteAll(ctx, tx)
if err != nil {
errRB := tx.Rollback()
if errRB != nil {
log.Errorln(log.DatabaseMgr, errRB)
}
return 0, err
}
err = tx.Commit()
if err != nil {
return 0, err
}
return totalDeleted, nil
}
func deletePostgres(ctx context.Context, queries []qm.QueryMod) (int64, error) {
retCandle, err := modelPSQL.Candles(queries...).All(context.Background(), database.DB.SQL)
if err != nil {
return 0, err
}
var tx *sql.Tx
tx, err = database.DB.SQL.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
var totalDeleted int64
totalDeleted, err = retCandle.DeleteAll(ctx, tx)
if err != nil {
errRB := tx.Rollback()
if errRB != nil {
log.Errorln(log.DatabaseMgr, errRB)
}
return 0, err
}
err = tx.Commit()
if err != nil {
return 0, err
}
return totalDeleted, nil
}
// Insert series of candles
func Insert(in *Item) (uint64, error) {
if database.DB.SQL == nil {
return 0, database.ErrDatabaseSupportDisabled
}
if len(in.Candles) < 1 {
return 0, errNoCandleData
}
ctx := context.Background()
tx, err := database.DB.SQL.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
var totalInserted uint64
if repository.GetSQLDialect() == database.DBSQLite3 {
totalInserted, err = insertSQLite(ctx, tx, in)
} else {
totalInserted, err = insertPostgresSQL(ctx, tx, in)
}
if err != nil {
errRB := tx.Rollback()
if errRB != nil {
log.Errorln(log.DatabaseMgr, errRB)
}
return 0, err
}
err = tx.Commit()
if err != nil {
return 0, err
}
return totalInserted, nil
}
func insertSQLite(ctx context.Context, tx *sql.Tx, in *Item) (uint64, error) {
var totalInserted uint64
for x := range in.Candles {
var tempCandle = modelSQLite.Candle{
ExchangeNameID: in.ExchangeID,
Base: strings.ToUpper(in.Base),
Quote: strings.ToUpper(in.Quote),
Interval: strconv.FormatInt(in.Interval, 10),
Asset: strings.ToLower(in.Asset),
Timestamp: in.Candles[x].Timestamp.UTC().Format(time.RFC3339),
Open: in.Candles[x].Open,
High: in.Candles[x].High,
Low: in.Candles[x].Low,
Close: in.Candles[x].Close,
Volume: in.Candles[x].Volume,
}
tempUUID, err := uuid.NewV4()
if err != nil {
return 0, err
}
tempCandle.ID = tempUUID.String()
err = tempCandle.Insert(ctx, tx, boil.Infer())
if err != nil {
return 0, err
}
if totalInserted < math.MaxUint64 {
totalInserted++
}
}
return totalInserted, nil
}
func insertPostgresSQL(ctx context.Context, tx *sql.Tx, in *Item) (uint64, error) {
var totalInserted uint64
for x := range in.Candles {
var tempCandle = modelPSQL.Candle{
ExchangeNameID: in.ExchangeID,
Base: strings.ToUpper(in.Base),
Quote: strings.ToUpper(in.Quote),
Interval: in.Interval,
Asset: strings.ToLower(in.Asset),
Timestamp: in.Candles[x].Timestamp,
Open: in.Candles[x].Open,
High: in.Candles[x].High,
Low: in.Candles[x].Low,
Close: in.Candles[x].Close,
Volume: in.Candles[x].Volume,
}
err := tempCandle.Upsert(ctx, tx, true, []string{"timestamp", "exchange_name_id", "base", "quote", "interval", "asset"}, boil.Infer(), boil.Infer())
if err != nil {
return 0, err
}
if totalInserted < math.MaxUint64 {
totalInserted++
}
}
return totalInserted, nil
}
// InsertFromCSV load a CSV list of candle data and insert into database
func InsertFromCSV(exchangeName, base, quote string, interval int64, asset, file string) (uint64, error) {
csvFile, err := os.Open(file)
if err != nil {
return 0, err
}
defer func() {
err = csvFile.Close()
if err != nil {
log.Errorln(log.Global, err)
}
}()
csvData := csv.NewReader(csvFile)
exchangeUUID, err := exchange.UUIDByName(exchangeName)
if err != nil {
return 0, err
}
tempCandle := &Item{
ExchangeID: exchangeUUID.String(),
Base: base,
Quote: quote,
Interval: interval,
Asset: asset,
}
for {
row, errCSV := csvData.Read()
if errCSV != nil {
if errCSV == io.EOF {
break
}
return 0, errCSV
}
tempTick := Candle{}
v, errParse := strconv.ParseInt(row[0], 10, 32)
if errParse != nil {
return 0, errParse
}
tempTick.Timestamp = time.Unix(v, 0).UTC()
if tempTick.Timestamp.IsZero() {
err = fmt.Errorf("invalid timestamp received on row %v", row)
break
}
tempTick.Volume, err = strconv.ParseFloat(row[1], 64)
if err != nil {
break
}
tempTick.Open, err = strconv.ParseFloat(row[2], 64)
if err != nil {
break
}
tempTick.High, err = strconv.ParseFloat(row[3], 64)
if err != nil {
break
}
tempTick.Low, err = strconv.ParseFloat(row[4], 64)
if err != nil {
break
}
tempTick.Close, err = strconv.ParseFloat(row[5], 64)
if err != nil {
break
}
tempCandle.Candles = append(tempCandle.Candles, tempTick)
}
if err != nil {
return 0, err
}
return Insert(tempCandle)
}