Skip to content

Commit

Permalink
Trade history, recent trades, live trade processing and storage (thra…
Browse files Browse the repository at this point in the history
…sher-corp#558)

* End of day commit moving packages and setting foundation into how trade processing will go

* Conformity

* tdd candle generation based on received trade data, renames orderbookbuffer back to buffer for now...

* Formalises test functions and designs the trade processor

* Theoretical amending old candles to allow any trades that were part of an old processed candle to be more accurate. Saving of candles will only occur on previous cycles, extending memory usage a bit longer

* Figures out sqlboiler for sqlite. Updates websocket entries to process trade data

* One more trade data

* Adds more exchange support

* Adds PSQL stuff

* Begins creating sql implementation

* End of day commit. Helper functions and understanding sql usage in GCT

* Adds delete and cleans up table design

* Finishes trades conceptually. Awaits candle data update in order to translate trades to candles

* Initial handling of trades in coinbene

* Proto

* Fixing of some bugs, attempting to address coinbene asset type ws issues

* Fixes up coinbene websocket implementation for the most part

* finalises coinbene websocket implementation. Adds new ability to parse currencies without a delimiter

* Implements rpc commands and adds testing

* updates the following to be compatible with trade data update: Theoretical amending old candles to allow any trades that were part of an old processed candle to be more accurate. Saving of candles will only occur on previous cycles, extending memory usage a bit longer

* Changes trade to be its own entity rather than attached to a websocket.

* Adds coverage to trades. Changes signature of `AddTradesToBuffer` to return error. Now automatically shuts down without need for channel listening. Will automatically start up again if it gets data

* Implements trade fetching at the wrapper level for a bunch of exchanges. Adds trade id to script updoot. Probably breaking change

* Implements trade fetching for all wrappers hurray hurrah. Updates all the tests

* Adds new interface func to get recent trades. Ensures GetExchangeHistory continues until conditions are met

* Adds new readme, tests all new wrapper endpoints, updates exchange_wrapper_issues to test new endpoints. Updates exchange_wrapper_coverage with new coverage... Fixes lame bug causing wrapper tests to fail from being poorly setup. Adds loopy loop to ensure that all data is captured when requesting exchange history

* Bugfix on psql migrations. Rebases latest changes, updates table design to use base and quote, updates trades to use exchange_name_id

* Adds new config field for saving trades to the database per exchange. Now exits trade processing when trade saving is not enabled. Similarly for wrapper, does not save if not enabled

* Minor bitfinex trade fixes. continues on buffer processing errors, now saves transactionid to the db

* Adds support for generating candles from candlesextended. May extend it further, idk

* Updates trade candles to be able to fill missing data with trades. Adds more tests. Also does a thing where you can forcefully override a candle based on internal trade data instead of API data

* Fixes bug where force deletions did not follow up with insertions. Adds force to candle commands

* Fixes specific exchange based issues. Extends recent trades to 24 hours where possible

* Fixes issue with saved tests. Fixes tests for trades. Adds parallel to tests. Pre-fixes people's nits

* Adds new GRPC functions to find out what data is missing from trades and candles. Fixes some assumptions from missing period code.

* Adds unique constraint. Fixes up niggling issues for wrappers and websockets

* Fixes issues with using unix times in the database trying to retrieve data via the CLI. Reduces save time to 15 seconds

* Updates trades to use timestamps instead of int64 unix

* Adds missing FTX wrapper implementation. Regens docs

* Linting the linters. Updating readme

* Adds new command to set whether an exchange can process trades

* Doc update

* Adds recent trades and historic trade endpoints to grpc

* formats pair_test.go to appease linter gods

* Addresses data race. Removes logging of missing intervals on unrelated function (now that it has its own rpc command). The buffer time isnt customisable, but I don't feel it needs to be at a config level at all really.

* Fixes a few niterinos regarding spacing, type conversion, a weird Bitmex 0 trade value error, unsubscriptions and cli command references

* Reduces map lookups. Adds base func and moves wrappers to use it

* Uses better currency formatter. Adds time based validation to trade history. Reverts configtest.json

* Reverts config and updates test names. Also WAYYYYY LESS SPAMMY

* oopsie doopsie missed a whoopsie

* mint flavoured lint

* Fixes issues caused by rebase

* Fixes issue with timestamps not converting properly from command to RPCServer. Adds new error type. Adds shorthand entries to some commands. Removes os.Exit from tests. Makes Gemini test rolling. Adds enabled exchange check to RPC function. Escapes timestamp on bitstamp. Renames var

* fixes whoopsie oopsie doopsie I forgot to remove code shoopsie

* missed a line

* 🎉 🎉 🎉Breaks everything in an end of day commit 🎉 🎉 🎉

* Modifies function 'createlocaloffset' to return a string instead. Uses strings for all time based start and end commands. Uses UTC times in RPC server and updates SQLITE to use formatted time based queries

* Adds concurrency-safe way of changing SaveTradeData and checking it. Fixes embarrassing typo

* End of day fix, adds bitfinex update to loop until either the return trades shows no new dates, or meets specifications. Fixes egregious typo

* Improves testing and handling of historical trades function

* Fixes tests after latest changes

* Fix potential fatal err now that db is enabled in test config now

* Fixes up some database settings to use a local engine instead of global var

* DELICIOUS LINT CHOCOLATE FIXES

* Fixes data race by slashing competitor's tyres

* Adds mock test fixes to allow for live and stored data test

* Removes verbosity in engine level tests. Adds new timezone format to highlight the timezone for RPC functions. Removes reference to Preix index fund

* Oopsie doopsie, fixed a whoopsie

* Loggers can no longer do data drag races on my lawn 👴

* Removes bad lock

* Addresses command nits. End of day conceptual commit, trying to calculate spans of time in the context of missing periods. Tests will fail

* Adds new stream response for retrieving trade history as it can take time to do. Unsuccessfully attempts to simplify time range calculation for missing trades response

* Adds new timeperiods package to calculate time periods, time ranges and whether data is in those ranges. Removes kline basic implementation of same concept

* Fixes lint issues. Fixes test. Moves trade cli commands to their own trade subcommands

* Updates lakebtc to no longer have gethistorictrades as it is unsupported. Adds more validation to rpc functions

* Removes requirement to have trades when testing trade wrapper functions. Doesn't really prove it works if there are no trades for a given currency in a time period.

* Addresses nits, runs linting fix and ensures a test is consistent

* Fix merge issues

* Moves sort to timeperiods. Adds test coverage. Fixes typo

* Removes log package in CLI

* Fixes `GetTrades` url

* Reorders all instances of validation occuring after settingup RPC connection

* Fixes test to ensure that it is setup before testing that it is setup

* Fixed issue with bool retrieval. Removes double append

* Fixes Binance times, fixes bitfinex sell sides, fixes huobi times, sorts all responses

* Fixes poloniex trade id consistency. Makes recent trade for poloniex consistent with others (15 minutes). Fixes coinbene. Fixes localbitcoins to use quote currency. Fixes coinut times. Updates huobi trade id, saves okgroup trades. Fixes bid and ask to buy and sell

* Removes websocket trades for lakebtc as it did not meet our requirements for processing. Adds new constraints to the database to ensure we have uniqueness on trades where ID doesn't exist and doesn't trigger errors for trades where the tid does

* Fixes migration for postgres to downscale properly

* Really really fixes the psql index changes

* Fixes broken tests

* Now with working tests and no pocket lint

* Makes the side column nullable with no more constraint for it. adds migrations and runs generation. comments lakebtc

* Lint & Sprüngli

* Updates zb to use more appropriate side

* Fixes oopsie

* Attempts to address a data race from globals

* Fixes build

* Fixes missed regen rpc files

* Updates readme to point to trade readme. Fixes exchange_wrapper_coverage wrapper count and untested panics, tests bitfinex funding pair test for `fUSD`, adds shiny new param `tradeprocessinginterval`

* mint flavoured lint

* Uses the real default to set the default value by default

* Fixes some extra tests surrounding email sending and number incompatibility

* Reverts test config

* re-adds gom2/usdt currency

* Fixes typo, don't look!

* Fixes minor codelingo pickups

* Adds more precision to handling of trade data from Kraken. Expands test

* interface christmas tree

* lint
  • Loading branch information
gloriousCode authored Oct 29, 2020
1 parent 1226399 commit 80bc8c7
Show file tree
Hide file tree
Showing 204 changed files with 53,533 additions and 8,379 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTORS
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ vadimzhukck | https://github.com/vadimzhukck
MadCozBadd | https://github.com/MadCozBadd
140am | https://github.com/140am
marcofranssen | https://github.com/marcofranssen
dackroyd | https://github.com/dackroyd
Rots | https://github.com/Rots
vazha | https://github.com/vazha
dackroyd | https://github.com/dackroyd
cranktakular | https://github.com/cranktakular
woshidama323 | https://github.com/woshidama323
crackcomm | https://github.com/crackcomm
Expand Down
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@ Join our slack to discuss all things related to GoCryptoTrader! [GoCryptoTrader
| BitMEX | Yes | Yes | NA |
| Bitstamp | Yes | Yes | No |
| Bittrex | Yes | No | NA |
| BTCMarkets | Yes | No | NA |
| BTCMarkets | Yes | Yes | NA |
| BTSE | Yes | Yes | NA |
| CoinbasePro | Yes | Yes | No|
| Coinbene | Yes | Yes | No |
| COINUT | Yes | Yes | NA |
| Exmo | Yes | NA | NA |
| FTX | Yes | Yes | No |
| CoinbasePro | Yes | Yes | No|
| Coinbene | Yes | No | No |
| GateIO | Yes | Yes | NA |
| Gemini | Yes | Yes | No |
| HitBTC | Yes | Yes | No |
| Huobi.Pro | Yes | Yes | NA |
| ItBit | Yes | NA | No |
| Kraken | Yes | Yes | NA |
| LakeBTC | Yes | Yes | NA |
| Lbank | Yes | No | NA |
| LakeBTC | Yes | No | NA |
| LocalBitcoins | Yes | NA | NA |
| OKCoin International | Yes | Yes | No |
| OKEX | Yes | Yes | No |
Expand Down Expand Up @@ -76,6 +76,7 @@ However, we welcome pull requests for any exchange which does not match this cri
+ Basic event trigger system.
+ OHLCV/Candle retrieval support. See [OHLCV](/docs/OHLCV.md).
+ Scripting support. See [gctscript](/gctscript/README.md).
+ Recent and historic trade processing. See [trades](/exchanges/trade/README.md).
+ WebGUI (discontinued).

## Planned Features
Expand Down Expand Up @@ -142,18 +143,18 @@ Binaries will be published once the codebase reaches a stable condition.
|User|Contribution Amount|
|--|--|
| [thrasher-](https://github.com/thrasher-) | 643 |
| [shazbert](https://github.com/shazbert) | 196 |
| [gloriousCode](https://github.com/gloriousCode) | 170 |
| [dependabot-preview[bot]](https://github.com/apps/dependabot-preview) | 69 |
| [shazbert](https://github.com/shazbert) | 197 |
| [gloriousCode](https://github.com/gloriousCode) | 171 |
| [dependabot-preview[bot]](https://github.com/apps/dependabot-preview) | 70 |
| [xtda](https://github.com/xtda) | 47 |
| [ermalguni](https://github.com/ermalguni) | 14 |
| [vadimzhukck](https://github.com/vadimzhukck) | 10 |
| [MadCozBadd](https://github.com/MadCozBadd) | 9 |
| [140am](https://github.com/140am) | 8 |
| [marcofranssen](https://github.com/marcofranssen) | 8 |
| [Rots](https://github.com/Rots) | 7 |
| [vazha](https://github.com/vazha) | 7 |
| [dackroyd](https://github.com/dackroyd) | 5 |
| [Rots](https://github.com/Rots) | 5 |
| [vazha](https://github.com/vazha) | 5 |
| [cranktakular](https://github.com/cranktakular) | 5 |
| [woshidama323](https://github.com/woshidama323) | 3 |
| [crackcomm](https://github.com/crackcomm) | 3 |
Expand Down
2 changes: 2 additions & 0 deletions cmd/apichecker/apicheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ func main() {
flag.Parse()
var err error
c := log.GenDefaultSettings()
log.RWM.Lock()
log.GlobalLogConfig = &c
log.RWM.Unlock()
log.SetupGlobalLogger()
configData, err = readFileData(jsonFile)
if err != nil {
Expand Down
6 changes: 4 additions & 2 deletions cmd/apichecker/apicheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ func TestMain(m *testing.M) {
testMode = true
c := log.GenDefaultSettings()
c.Enabled = convert.BoolPtr(true)
log.RWM.Lock()
log.GlobalLogConfig = &c
log.RWM.Unlock()
log.Infoln(log.Global, "set verbose to true for more detailed output")
var err error
configData, err = readFileData(jsonFile)
Expand Down Expand Up @@ -158,7 +160,7 @@ func TestAdd(t *testing.T) {
}
err := addExch("FalseName", htmlScrape, data2, false)
if err == nil {
t.Log("expected an error due to invalid path being parsed in")
t.Error("expected an error due to invalid path being parsed in")
}
}

Expand Down Expand Up @@ -635,7 +637,7 @@ func TestWriteAuthVars(t *testing.T) {
trelloCardID = "jdsfl"
err := writeAuthVars(testMode)
if err != nil {
t.Log(err)
t.Error(err)
}
}
}
Expand Down
78 changes: 78 additions & 0 deletions cmd/documentation/exchanges_templates/exchanges_trade_readme.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
{{define "exchanges trade" -}}
{{template "header" .}}
## Current Features for {{.Name}}

+ The trade package contains a processor for both REST and websocket trade history processing
+ Its primary purpose is to collect trade data from multiple sources and save it to the database's trade table
+ If you do not have database enabled, then trades will not be processed

### Requirements to save a trade to the database
+ Database has to be enabled
+ Under `config.json`, under your selected exchange, enable the field `saveTradeData`
+ This will enable trade processing to occur for that specific exchange
+ This can also be done via gRPC under the `SetExchangeTradeProcessing` command

### Usage
+ To send trade data to be processed, use the following example:
```
err := trade.AddTradesToBuffer(b.Name, trade.Data{
Exchange: b.Name,
TID: strconv.FormatInt(tradeData[i].TID, 10),
CurrencyPair: p,
AssetType: assetType,
Side: side,
Price: tradeData[i].Price,
Amount: tradeData[i].Amount,
Timestamp: tradeTS,
})
```
_b in this context is an `IBotExchange` implemented struct_

### Rules
+ If the trade processor has not started, it will automatically start upon being sent trade data.
+ The processor will add all received trades to a buffer
+ After 15 seconds, the trade processor will parse and save all trades on the buffer to the trade table
+ This is to save on constant writing to the database. Trade data, especially when received via websocket would cause massive issues on the round trip of saving data for every trade
+ If the processor has not received any trades in that 15 second timeframe, it will shut down.
+ Sending trade data to it later will automatically start it up again


## Exchange Support Table

| Exchange | Recent Trades via REST | Live trade updates via Websocket | Trade history via REST |
|----------|------|-----------|-----|
| Alphapoint | No | No | No |
| Binance| Yes | Yes | No |
| Bitfinex | Yes | Yes | Yes |
| Bitflyer | Yes | No | No |
| Bithumb | Yes | NA | No |
| BitMEX | Yes | Yes | Yes |
| Bitstamp | Yes | Yes | No |
| Bittrex | Yes | No | No |
| BTCMarkets | Yes | Yes | No |
| BTSE | Yes | Yes | No |
| Coinbene | Yes | Yes | No |
| CoinbasePro | Yes | Yes | No|
| COINUT | Yes | Yes | No |
| Exmo | Yes | NA | No |
| FTX | Yes | Yes | Yes |
| GateIO | Yes | Yes | No |
| Gemini | Yes | Yes | Yes |
| HitBTC | Yes | Yes | Yes |
| Huobi.Pro | Yes | Yes | No |
| ItBit | Yes | NA | No |
| Kraken | Yes | Yes | No |
| LakeBTC | Yes | No | No |
| Lbank | Yes | No | Yes |
| LocalBitcoins | Yes | NA | No |
| OKCoin International | Yes | Yes | No |
| OKEX | Yes | Yes | No |
| Poloniex | Yes | Yes | Yes |
| Yobit | Yes | NA | No |
| ZB.COM | Yes | Yes | No |


### Please click GoDocs chevron above to view current GoDoc information for this package
{{template "contributions"}}
{{template "donations" .}}
{{end}}
9 changes: 5 additions & 4 deletions cmd/documentation/root_templates/root_readme.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,21 @@ Join our slack to discuss all things related to GoCryptoTrader! [GoCryptoTrader
| BitMEX | Yes | Yes | NA |
| Bitstamp | Yes | Yes | No |
| Bittrex | Yes | No | NA |
| BTCMarkets | Yes | No | NA |
| BTCMarkets | Yes | Yes | NA |
| BTSE | Yes | Yes | NA |
| CoinbasePro | Yes | Yes | No|
| Coinbene | Yes | Yes | No |
| COINUT | Yes | Yes | NA |
| Exmo | Yes | NA | NA |
| FTX | Yes | Yes | No |
| CoinbasePro | Yes | Yes | No|
| Coinbene | Yes | No | No |
| GateIO | Yes | Yes | NA |
| Gemini | Yes | Yes | No |
| HitBTC | Yes | Yes | No |
| Huobi.Pro | Yes | Yes | NA |
| ItBit | Yes | NA | No |
| Kraken | Yes | Yes | NA |
| LakeBTC | Yes | Yes | NA |
| Lbank | Yes | No | NA |
| LakeBTC | Yes | No | NA |
| LocalBitcoins | Yes | NA | NA |
| OKCoin International | Yes | Yes | No |
| OKEX | Yes | Yes | No |
Expand Down Expand Up @@ -77,6 +77,7 @@ However, we welcome pull requests for any exchange which does not match this cri
+ Basic event trigger system.
+ OHLCV/Candle retrieval support. See [OHLCV](/docs/OHLCV.md).
+ Scripting support. See [gctscript](/gctscript/README.md).
+ Recent and historic trade processing. See [trades](/exchanges/trade/README.md).
+ WebGUI (discontinued).

## Planned Features
Expand Down
122 changes: 61 additions & 61 deletions cmd/exchange_template/test_file.tmpl
Original file line number Diff line number Diff line change
@@ -1,61 +1,61 @@
{{define "test"}}
package {{.Name}}

import (
"log"
"os"
"testing"

"github.com/thrasher-corp/gocryptotrader/config"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
)

// Please supply your own keys here to do authenticated endpoint testing
const (
apiKey = ""
apiSecret = ""
canManipulateRealOrders = false
)

var {{.Variable}} {{.CapitalName}}

func TestMain(m *testing.M) {
{{.Variable}}.SetDefaults()
cfg := config.GetConfig()
err := cfg.LoadConfig("../../testdata/configtest.json", true)
if err != nil {
log.Fatal(err)
}

exchCfg, err := cfg.GetExchangeConfig("{{.CapitalName}}")
if err != nil {
log.Fatal(err)
}

exchCfg.API.AuthenticatedSupport = true
{{ if .WS }} exchCfg.API.AuthenticatedWebsocketSupport = true {{ end }}
exchCfg.API.Credentials.Key = apiKey
exchCfg.API.Credentials.Secret = apiSecret

err = {{.Variable}}.Setup(exchCfg)
if err != nil {
log.Fatal(err)
}

os.Exit(m.Run())
}

// Ensures that this exchange package is compatible with IBotExchange
func TestInterface(t *testing.T) {
var e exchange.IBotExchange
if e = new({{.CapitalName}}); e == nil {
t.Fatal("unable to allocate exchange")
}
}

func areTestAPIKeysSet() bool {
return {{.Variable}}.ValidateAPICredentials()
}

// Implement tests for API endpoints below
{{end}}
{{define "test"}}
package {{.Name}}
import (
"log"
"os"
"testing"
"github.com/thrasher-corp/gocryptotrader/config"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
)
// Please supply your own keys here to do authenticated endpoint testing
const (
apiKey = ""
apiSecret = ""
canManipulateRealOrders = false
)
var {{.Variable}} {{.CapitalName}}
func TestMain(m *testing.M) {
{{.Variable}}.SetDefaults()
cfg := config.GetConfig()
err := cfg.LoadConfig("../../testdata/configtest.json", true)
if err != nil {
log.Fatal(err)
}
exchCfg, err := cfg.GetExchangeConfig("{{.CapitalName}}")
if err != nil {
log.Fatal(err)
}
exchCfg.API.AuthenticatedSupport = true
{{ if .WS }} exchCfg.API.AuthenticatedWebsocketSupport = true {{ end }}
exchCfg.API.Credentials.Key = apiKey
exchCfg.API.Credentials.Secret = apiSecret
err = {{.Variable}}.Setup(exchCfg)
if err != nil {
log.Fatal(err)
}
os.Exit(m.Run())
}
// Ensures that this exchange package is compatible with IBotExchange
func TestInterface(t *testing.T) {
var e exchange.IBotExchange
if e = new({{.CapitalName}}); e == nil {
t.Fatal("unable to allocate exchange")
}
}
func areTestAPIKeysSet() bool {
return {{.Variable}}.ValidateAPICredentials()
}
// Implement tests for API endpoints below
{{end}}
12 changes: 9 additions & 3 deletions cmd/exchange_template/wrapper_file.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/protocol"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
)
Expand Down Expand Up @@ -323,8 +324,13 @@ func ({{.Variable}} *{{.CapitalName}}) GetFundingHistory() ([]exchange.FundHisto
return nil, common.ErrNotYetImplemented
}

// GetExchangeHistory returns historic trade data within the timeframe provided.
func ({{.Variable}} *{{.CapitalName}}) GetExchangeHistory(p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]exchange.TradeHistory, error) {
// GetRecentTrades returns the most recent trades for a currency and asset
func ({{.Variable}} *{{.CapitalName}}) GetRecentTrades(p currency.Pair, assetType asset.Item) ([]trade.Data, error) {
return nil, common.ErrNotYetImplemented
}

// GetHistoricTrades returns historic trade data within the timeframe provided
func ({{.Variable}} *{{.CapitalName}}) GetHistoricTrades (p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]trade.Data, error) {
return nil, common.ErrNotYetImplemented
}

Expand Down
Loading

0 comments on commit 80bc8c7

Please sign in to comment.