Files
gocryptotrader/gctscript
Scott 80bc8c7e9e Trade history, recent trades, live trade processing and storage (#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

* 🎉 🎉 :tada: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
2020-10-29 13:00:02 +11:00
..
2020-01-23 13:54:04 +11:00
2020-07-24 13:18:09 +10:00

GoCryptoTrader package gctscript

Build Status Software License GoDoc Coverage Status Go Report Card

This gctscript package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Current Features for gctscript package

  • Execute scripts
  • Terminate scripts
  • Autoload scripts on bot startup
  • Current Exchange features supported:
    • Enabled Exchanges
    • Enabled currency pairs
    • Account information
    • Query Order
    • Submit Order
    • Cancel Order
    • Ticker
    • Orderbook

How to use

Prerequisites

To Enable database logging support you must have an active migrated database by following the database setup guide

Configuration

The gctscript configuration struct is currently:

type Config struct {
	Enabled       bool          `json:"enabled"`
	ScriptTimeout time.Duration `json:"timeout"`
	AllowImports  bool          `json:"allow_imports"`
	AutoLoad      []string      `json:"auto_load"`
	Verbose       bool          `json:"Verbose"`
}

With an example configuration being:

 "gctscript": {
  "enabled": true,
  "timeout": 600000000,
  "allow_imports": true,
  "auto_load": [],
  "debug": false
 },
Script Control
  • You can autoload scripts on bot start up by placing their name in the "auto_load" config entry

    "auto_load": ["one","two"]
    

    This will look in your GoCryptoTrader data directory in a folder called "scripts" for files one.gct and two.gct and autoload them

  • Manual control of scripts can be done via the gctcli command with support for the following:

    • Enable/Disable GCTScript:
     gctcli enablesubsystem "gctscript"
     gctcli disablesubsystem "gctscript"
    
    • Start/Execute:
      gctcli script execute <scriptname> <pathoverride>
      gctcli script execute "timer.gct" "~/gctscript"
    
      {
        "status": "ok",
        "data": "timer.gct executed"
      }
    
    • Stop:
      gctcli script stop <uuid>
      gctcli script stop 821bd73e-02b1-4974-9463-874cb49f130d
    
      {
        "status": "ok",
        "data": "821bd73e-02b1-4974-9463-874cb49f130d terminated"
      }
    
    • Status:
      gctcli script status 
    
      {
        "status": "ok",
        "scripts": [
          {
            "uuid": "821bd73e-02b1-4974-9463-874cb49f130d",
            "name": "timer.gct",
            "next_run": "2019-11-14 13:11:40.224919456 +1100 AEDT m=+91.062103259"
          }
        ]
      }
    
    • Read file:
      gctcli script read <filename>
      gctcli script read "timer.gct"
    
      {
        "status": "ok",
        "script": {
        "name": "timer.gct",
        "path": "/home/x/.gocryptotrader/scripts"
        },
        "data": "fmt := import(\"fmt\")\nt := import(\"times\")\n\nname := \"run\"\ntimer := \"5s\"\n\nload := func() {\n\tfmt.printf(\"5s %s\\n\",t.now())\n}\n\nload()\n"
      }
    
    • Query running script:
      gctcli script query <uuid>
      gctcli script query 821bd73e-02b1-4974-9463-874cb49f130d
      {
        "status": "ok",
        "script": {
        "UUID": "bf692e2d-fa1e-4d95-92fd-33d7634d3d77",
        "name": "timer.gct",
        "path": "/home/x/.gocryptotrader/scripts",
        "next_run": "2019-12-12 07:44:19.747572406 +1100 AEDT m=+16.782773385"
      },
      "data": "fmt := import(\"fmt\")\nt := import(\"times\")\n\nname := \"run\"\ntimer := \"5s\"\n\nload := func() {\n\tfmt.printf(\"5s %s\\n\",t.now())\n}\n\nload()\n"
      }
      load()  
    
    • Add script to autoload:
    gctcli script autoload add timer
    {
      "status": "success",
      "data": "script timer added to autoload list"
    }
    
    • Remove script from autoload:
      gctcli script autoload remove timer
      {
        "status": "success",
        "data": "script timer removed from autoload list"
      }
    
Scripting & Extending modules

The scripting engine utilises tengo an intro tutorial for it can be found here

Modules have been written so far linking up common exchange features including

  • Orderbook
  • Ticker
  • Order Management
  • Account information
  • Withdraw funds
  • Get Deposit Addresses

Extending or creating new modules:

Extending an existing module the exchange module for example is simple

  • Open required module
  • Add to exchangeModule map
  • Define function with signature (args ...objects.Object) (ret objects.Object, err error)

Similar steps can be taken to add a new module with a few adjustments

  • Open required GCT
  • Add module name to GCTModules map
GCT module methods

Current supported methods added and exposed to scripts are as follows:

accountinfo
-> exchange:string

depositaddress
-> exchange:string
-> currency:string

orderbook
-> exchange:string
-> currency pair:string
-> delimiter:string
-> asset:string

ticker
-> exchange:string
-> currency pair:string
-> delimiter:string
-> asset:string

pairs
-> exchange:string
-> enabled only:bool
-> asset:string

queryorder
-> exchange:string
-> order id:string

submitorder
-> exchange:string
-> currency pair:string
-> delimiter:string
-> order type:string
-> order side:string
-> price:float64
-> amount:float64
-> client_id:string

withdrawfiat
-> exchange:string
-> currency:string
-> description:string
-> amount:float64
-> bank id:string

withdrawcrypto
-> exchange:string
-> currency:string
-> address:string
-> address tag:string
-> amount:float64
-> fee:float64
-> description:string

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc