Commit Graph

27 Commits

Author SHA1 Message Date
Ryan O'Hara-Reid
4e135c9590 logger: reduce go routine generation (#992)
* logger: reduce go routine generation

* logger: shift most of processing and prep work to the worker pool, add pool for fields because each log we are pushing the struct to the heap, has better segregation now and includes a buffer in scope instead of relying on a pool

* logger: shift fmt package calls to worker pool

* logger: conform tests to new design

* linter: fix issues

* Update log/logger_test.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* Update log/logger_test.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* UN-GLORIOUS: nits

* logger: Handle config variable

* logger: NITERINOS BY GLORIOUS CODE

* logger: revert

* glorious: nits

* Panic at the disco: fix

* Panic at the disco: fix

* logger: make sure logger closed and job channel emptied on start up error

* fix tests

* logger: reduce globals

* logger: finished reduces globals, reduce workers to one too keep everything in line.

* logger: remove comments

* logger/exhchange: linter issues

* db/test: fix linter

* logger: add tests shift wait before unlock

* logger: consolidate worker code; fix linter issue and make sure we can sustain writing for external testing.

* logger: fix race and warn for conflict in config

* logger: fix name and add to tests

* logger: remove zero value field

* glorious: panic fix and removal of code

* logger: reinstate channels in close

* logger: shift reinstate processing to SetupGlobalLogger

* logger: segregate config.json from internal log.Config

* logger: fix silly mistake that is silly

* engine: Add protection for nil issues and implement new constructor in tests

* logger: Force singular mutex usage throughout package, throw away funcs that are not used outside of this package, unexport a bunch. Fix tests.

* logger: actually set advanced settings

* Update log/loggers.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* Update log/loggers.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* Update log/loggers.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* Update log/loggers.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* Update log/logger_multiwriter.go

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>

* glorious: nits

* logger: test issue when not purging temp file and contents

* loggertest: add more protections for the panics

* linter: fix

* glorious: nits

* cleanup

* logger: linter fix

* linter: fix(?) :/

* linter: revert change

* linter: fix

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io>
2022-10-24 11:46:18 +11:00
Adrian Gallagher
68588560e3 CI: Bump go version, linters and fix minor issues (#1010)
* Bump golang, golangci-lint versions and fix issues

* Add -fno-stack-protector

* Fix AppVeyor golangci-lint ver

* Nitters

* Nitters round 2
2022-08-17 11:37:22 +10:00
Adrian Gallagher
9a4eb9de84 CI: Fix golangci-lint linter issues, add prealloc linter and bump version depends for Go 1.18 (#915)
* Bump CI versions

* Specifically set go version as 1.17.x bumps it to 1.18

* Another

* Adjust AppVeyor

* Part 1 of linter issues

* Part 2

* Fix various linters and improvements

* Part 3

* Finishing touches

* Tests and EqualFold

* Fix nitterinos plus bonus requester jobs bump for exchanges with large number of tests

* Fix nitterinos and bump golangci-lint timeout for AppVeyor

* Address nits, ensure all books are returned on err due to syncer regression

* Fix the wiggins

* Fix duplication

* Fix nitterinos
2022-04-20 13:45:15 +10:00
Ryan O'Hara-Reid
ac692b04f4 log: fix bug, expand test coverage and slightly optimize (#847)
* log: fix bugs expand coverage and optimise

* log: fix linter issues

* log: fix linter issue and pack methods in same file

* log: drop defer

* logger: move global check inside getfields  and remove unused test function

* logger: Increase note thanks @gloriouscode

* logger: wrap error with writer type

* logger: change variable name

* logger: change variable names and remove validsublogger func as it doesn't add functionality over a standard map call

* logs: error when unsupported output is applied on setup calls

* logs: add glorious suggestion

* logger: add protection to reduce olympic gold medal races

* logger: fix linter issues

* log: glorious niterinos
2021-11-30 16:43:27 +11:00
Adrian Gallagher
f0d45aa1d2 golangci-lint/CI: Bump versions and introduce new linters (#798)
* golangci-lint/CI: Bump versions

Fix remaining linter issues

* Specifically set AppVeyor version

* Fix the infamous typos 👀

* Add go env cmd to AppVeyor

* Add go version cmd to AppVeyor

* Specify AppVeyor image, adjust linters

* Update go get to go install due to deprecation

* Bump golangci-lint timeout time for AppVeyor

* Change NW contract to NQ

* Address nitters

* GetRandomPair -> Pair{}

* Address nits

* Address time nitterinos plus additional tweaks

* More time inception upgrades!

* Bending time and space
2021-10-14 16:38:53 +11:00
Scott
48434dfd46 Feature: Candle conversion & Candle validation (#716)
* Remove old concept. Introduce new job types and candle scaling

* Adds extra processing, commands

* new concept for queued jobs. Jobs can pause. New commands to manage status

* =End of day commit designing tables and implementing prerequisites further.

* Adds postgres data history relations

* Fixes table design for sqlite. Fixes all issues from merge

* Fixes craziness of database design. Adds some functions to get related jobs

* Fixes errors

* Updates some documentation, manages prerequisite jobs a little better, adds rpc funcs

* Fixes database design and adjust repo functions

* Tests database relationship

* Test coverage of new job functions

* Finishes coverage of new functions

* Commands and RPC coverage

* New database modifications for new job types

* Adds db support of new columns. Adds conversion validation. lint

* command blurb changes

* Allows websocket test to pass consistently

* Fixes merge issue preventing datahistorymanager from starting via config

* Minor fixes for different job type processing

* Fixes rangeholder issue, fixes validation, does not address jobs not starting or wrong status

* Fixes database tests, but at what cost. Fixes dhm tests

* Fixes dhj completion issue. Adds prerequisite by nickname

* Fixes validation processing. Adds db tests and validation

* Fixes validation job processing range

* Fixes trade sql. Reduces defaults. Validation processing and errors

* Updates cli job commands. adds validation decimal. fix job validation

* Expands run job handling and tests

* Validation work

* Fixes validation processing

* candle relations. new job type. updating database design

* Adds secondary exchange support. Sets stage for candle override

* Re adds accidentally deleted relationship

* Updates loading and saving candles to have relationship data when relevant

* Now validates and replaces candle data appropriately

* Fixes getting and setting datahistory data. Neatens DHM

* Test coverage

* Updates proto for new db types. New test coverage. Secondary exchange work

* Investigation into never-ending validation jobs. Now that intervals are ruled out, now need to complete the job....

* Fixes issues with validation job completion. Fixes validation volume issue for secondary exchange

* Adds candle warning support to the backtester

* Fixes warnings

* lint and begin docs

* Documentation updates. Final testing changes

* Minor fixes

* docs, prerequisite checks, more testing

* Fixes binance trade test. Rename err

* Documentation fixes. Figure fixes

* documentation update

* Fixes remote PSQL tests

* Fix binance mock test

* Remove unnecessary JSON

* regen proto

* Some minor nit fixes

* Var usage, query sorting, log improving, sql mirroring

* Extra coverage

* Experimental removal of m.jobs and mutex. Fix messaging

* Fixes error

* Lint fixes, command description improvements. More isRunning gates

* description improvements

* Lint

* BUFF regenerate

* Rough concept to fix insertions taking up long periods of time

* New calculation for trade data. Adds batch saving

This also adds an experimental request feature to shut down lingering requests. However, its uncertain whether or not this is having any impact. Initially thought it was the trades that was taking time and not SQL. Will investigate further

* Removes experimental requester. Adds documentation. Fixes typo

* rm unused error

* re-adds more forgotten contributors

* Now with proper commit count
2021-08-05 10:27:27 +10:00
Scott
63257ce4ca Improvement: Speeding up slow tests (#707)
* Speeds up tests

* Reduces time.Sleeps, lowers CreateTestBot complexity. Breaks things

* Removal of unecessary config reads. Parallel tests. Lower times

* Speeds up recent trades results

* mini update

* zoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooom

* Removes the dupes

* Lint

* post cherrypick

* Fix rare kraken data race

* Fixes banking global issues. Fixes postgres trades

* rmline for appveyor test

* Expands timeout in event that channel is closed before send

* Fix data race

* No rows, no bows and definitely no shows

* Removes parallel from createsnapshot tests

* Extends timedmutext test a smidge. Exchange fatality

* Shorter end timeframe and bigger candle
2021-07-07 12:42:03 +10:00
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
Scott
5ea5245afb Improvement: Subsystem separation (#664)
* Initial codes for a trade tracker

* Moving everything in a broken fashion

* Removes tradetracker. Removes some errors for subsystems

* Cleans up some subsystems, renames stuttering types. Removes some global Bot usage

* More basic subsystem renaming and file moving

* Removes engine dependency from events,ntpserver,ordermanager,comms manager

* Exports eventManager, fixes rpcserver. puts rpcserver back for now

* Removes redundant error message, further removes engine dependencies

* experimental end of day interface usage

* adds ability to build the application

* Withdraw and event manager handling

* cleans up apiserver and communications manager

* Cleans up some start/setup processes. Though should separate

* More consistency with Setup Start Stop IsRunning funcs

* Final consistency pass before testing phase

* Fixes engine tests. Fixes stop nil issue

* api server tests

* Communications manager testing

* Connection manager tests and nilsubsystem error

* End of day currencypairsyncer tests

* Adds databaseconnection/databaseconnection_test.go

* Adds withdrawal manager tests

* Deposit address testing. Moved orderbook sync first as its more important

* Adds test for event manager

* More full eventmanager testing

* Adds testfile. Enables skipped test.

* ntp manager tests

* Adds ordermanager tests, Extracts a whole new subsystem from engine and fanangles import cycles

* Adds websocket routine manager tests

* Basic portfolio manager testing

* Fixes issue with currency pair sync startup

* Fixes issue with event manager startup

* Starts the order manager before backtester starts

* Fixes fee tests. Expands testing. Doesnt fix races

* Fixes most test races

* Resolves data races

* Fixes subsystem test issues

* currency pair syncer coverage tests

* Refactors portfolio. Fixes tests. Withdraw validation

Portfolio didn't need to exist with a portfolio manager. Now the porfolio manager
is in charge how the portfolio is handled and all portfolio functions are attached
to the base instead of just exported at the package level

Withdrawal validation occurred at the exchange level when it can just be run at the
withdrawal manager level. All withdrawal requests go through that endpoint

* lint -fix

* golang lint fixes

* lints and comments everything

* Updates GCT logo, adds documentation for some subsystems

* More documentation and more logo updates

* Fixes backtesting and apiserver errors encountered

* Fixes errors and typos from reviewing

* More minor fixes

* Changes %h verb to %w

* reverbs to %s

* Humbly begins reverting to more flat engine package

The main reasoning for this is that the subsystem split doesn't make sense
in a golang environment. The subsystems are only meant to be used with engine
and so by placing them in a non-engine area, it does not work and is
inconsistent with the rest of the application's package layout.

This will begin salvaging the changes made by reverting to a flat
engine package, but maintaining the consistent designs introduced.
Further, I will look to remove any TestMains and decrease the scope
of testing to be more local and decrease the issues that have been
caused from our style of testing.

* Manages to re-flatten things. Everything is within its own file

* mini fixes

* Fixes tests and data races and lints

* Updates docs tool for engine to create filename readmes

* os -> ioutil

* remove err

* Appveyor version increase test

* Removes tCleanup as its unsupported on appveyor

* Adds stuff that I thought was in previous merge master commit

* Removes cancel from test

* Fixes really fun test-exclusive data race

* minor nit fixes

* niterinos

* docs gen

* rm;rf test

* Remove typoline. expands startstop helper. Splits apiserver

* Removes accidental folder

* Uses update instead of replace for order upsert

* addresses nits. Renames files. Regenerates documentation.

* lint and removal of comments

* Add new test for default scenario

* Fixes typo

* regen docs
2021-05-31 10:17:12 +10:00
Adrian Gallagher
051675255d CI: Add support for GitHub actions (#680)
* Add initial workflows config

* Add PSQL service

* Add 32bit and frontend jobs

* Add gcc-multilib and fix typo

* Fix backtester test for linux/unix filesystem errors and npm commands

* 32-bit Add -race to purposefully throw an error to ensure envs are set correctly (will revert)

* Revert "32-bit Add -race to purposefully throw an error to ensure envs are set correctly (will revert)"

This reverts commit b97e66c49fca859f8738e01107f96f9ca4040b2e.

* Bump workers count for orderbook processing

* Remove comments to trigger 32-bit cache hit after job success

* Cancel addition plus version bump, spawn more overlords

* Update build badge to Github Actions

* Brach -> Branch
2021-05-06 14:35:05 +10:00
Scott
46f71952f9 Feature: GoCryptoTrader Backtester (#622)
* Backtester: event handler completed, basic back tester support is working

* Backtester: support for ticker data added, general code clean up, start of risk & size manageR

* Backtester: WIP

* Me: I am going to write tests and comment as I go this time, also me: doesn't write any tests or comments as i go

* Backtester: work on orderbook system to track orders, increased test coverage

* Backtester: further test coverage, output json, start of js chart output

* Backtester: test coverage, output strat name

* Backtester: WIP

* WIP backtest charts

* WIP on template

* Backtester: further test coverage added

* Backtester: WIP

* backtester: attempting easier to read template for backtesting output

* comments, and tests

* Backtester: end of day WIP started work on risk management for handling leveraged positions

* Backtester: WIP

* Backtester: started heavy documentation phase for handover

* Backtester: started heavy documentation phase for handover

* Backtester: further comments, also work on making chart solution modular to allow for usage outside backtester (e.g OHCLV data)

* Backtester: CHART LIBRARY

* Backtester: move backtester over to new chart library

* Backtester: removed old chart templates, template updates

* Chart: add advancedintervaldata, convert from stats -> chart

* Chart: gctscript hookup to generate chart from OHLCV data

* Chart: reworked template to load from generated data if no template path is set

* chart: template wip

* correclty generate backtester readme, readme generation for charts, chart data generation

* Removed old read file methods

* Removed chart library from backtest as its now standalone

* Remove reference to unfinish TA code. Removes value calculation from order signal. It belongs with portfolio signal

* regen

* Re-jiggles everything around to not have import cycle issues and makes it look like a normal application

* End of day commit creates a new function to setup a backtester from a settings struct. Doesn't work though lol

* Builds up more backtest work to allow to be run from the command line

* Regen RPC

* End of day mind mine field of RSI calculation5

* Finishes basic main.go application

* Minor updates while theorising

* Rearranging things like the size and data types. Adds portfolio setup like a normal human. Allows positions to be decimal based since this is for CRYPTOCURRENCIES :o

* Moves code around to related positions. Adds compatibility to ordermanager to handle order submission. Fails to do things

* End of day commit. Adding config based loading for indiviual strats. Attempting to allow for multiple cps per strategy as well as loading fees

* End of day commit. Expanding config definition and loading implementation. Attempting to setup backtester wide multi currency support in a strategy.

* Moves risk, attempts to revert multi currency, but also supports more in depth multi currency for later...... in the portfolio

* End of day commit for realsies. Updates the strat and sets the invalid backtester

* No more panics. Finishes config loading. Renames buyandhold to dollarcostaverage

* Extends strategy to include a reason why its performing an action. Adds 420blazeit.strat. Expands statistics output. Moves folders around some more. Reduces amount of processing when "DO NOTHING" is the direction

* Commit before home time. Looks to expand the order manager to cater to the backtester. Fleshes out risk manager to think about leverage and holdings in other currencies

* Some basic expanding of strategy definitions. Changes weird package naming.

* Expands size and risk validations. Expands config settings for the validation. Starts looking at loading from live data source

* Merge branch 'master' into backscratcher

* Work towards having backtester load data

* Adds support and tests for all data source loading except for LIVE

* Some basic additions looking to append to data streams instead of load all at once, for the purpose of live data analysis

* End of day commit where I broke functions

* Adds live backtesting

* Adds FANCY MATHS to correctly size orders before  slippage. Rearranges minmaxing in config and strats

* Prints out initial settings. Creates a lame slippage calculator. Ensures that order price/amounts respect OHLCV data. Adds customisable config variables that can influence a strategy

* Fixes minor issues with rendering. Fixes portfolio buying and selling now

* ALL OVER THE PLACE END OF DAY COMMIT! In order to expand stats, thing must be tracked appropriately, which they arent. Here we add the addition of a compliance.go to track orders specifically. This will allow for the holdings manager to keep track of base stats such as how much we hold versus whats in use along with profits Compliance holds snapshots of every tick and what orders were there across exchanges. Also added a random slippage calculator which will allow a user to set their own slippage rates

* Another fun end of day commit where nothing works. In order to have accurate stats, you need accurate positions, to have accurate positions you need to break things down to individual levels and store them. This is part of that process of ensuring that we can have multiple settings and everything processed appropriately.

* Finalises multi currency config and support at most levels with exception to data loading.
Simplifies some struct property definitions by removing redundancy
Allows tracking of entire portfolio snapshots after each interval to track the entire process
Lowercases use of exchange names

* Sets the different prices to track across time. Attempts to sort out compliance snapshots

* end of day commit. Moving compliance to the portfolio to manager and track all transactions at each interval.

* Moves compliance calculation to portfolio.go. Adds a nice little decorator on the compliance manager orders to keep track of slippage, cost basis, volume adjusted price and close price. Moves "positions" to "hodlings" to be more accurate. Ensures exchange value calculations are accurate. Begins looking at Statistics and hodlings

* Moves statistics to eventhandlers. Removes ticker work as not needed. Redefines hodler properties

* hodlings are actually part of the portfolio

* Renamed 420blazeit.strat file. Renamed hodlings to holdings. Moved Datahandler to data_types.go. Expanded holdings calculations, doesn't work, but we're getting somewhere. Renamed bad var names in backtest.go. Added new order side types to highlight lack of action reasons

* Adds tests for holdings to ensure that holding snapshot calculation is accurate for the length of a strategy. Removes portfolio.Funds because its now handled via the holdings snapshots. Adds helper functions to Holding snapshots to retrieve relevant holdings. Updates sizing calculation to properly handle sell events. Expands holdings definitions to allow for comparison. Expands risk calculations to include holding snapshots so as to analyse all positions simultaneously

* Changing the statistics results to consider all datas, with the ultimate goal to replace the current statistics package with this multi currency output

* Made "Why" more generic. Expands statistics output. Removes time tying to stats map. Moves order event to correct location. Removes some debug lines.

* Adds some raw funky drawdown statistics 🎉

* End of day commit. experimentation leaves little code changes

* An attempt at expanding statistics. Need to have ones dedicated to exchange, asset, pair. Early work for having global map to track all the asset things to minimise all the maps throughout the application

* 🎉 ADDS MULTI CURRENCY SUPPORT TO FOR THE BACKTESTER 🎉 Can either execute strategies by assessing multiple currencies individually, or as a group and make strategic decisions on what currency to signal in. Adds new strat files to demonstrate

* End of day shenanigans. Moving codes around, making more fun stats. Expanding DCA strat to check if DCA is better than the market longer term

* Adds sharpe ratio and total stats for final output if more than one currency is considered

* Adds sortino ratio and test for validation

* Adds information ratio

* Adds calmar ratio

* Adds CAGR

* Slims down the statistics file to only include my work. Updates everything to use interfaces rather than direct code references to make it easier to swap out codes. Begins looking at serialising statistics for reports

* More neatening. Removal of old FAKE tests. Can now output a report in JSON

* End of day commit. Creation of reporting. Uses tradingview charting library and some basic bootstrap CDN to render content nicely. Will be updating everything to have a special kline item to annotate chart results

* Minor formatting changes before all the reviews

* End of day commit. Expands reporting to have an enhanced candle. These candles contain metadata on whether an order has been placed and to mark charts appropriately. This will be expanded to have all the stats and make it pretty

* Extra code I forgot to commit!

* Fixes an issue where data cannot render above 1,100 candles by stopping it from rendering more than that..

* End of day commit. There is no inclusivity with candle requests and I cant figure it out right now.

* Fixes issue with missing data by adding events when data isnt present and classifying it. Adds new way for klines to verify data with a bit more clarity

* Completes report generation

* Improves cagr. removes butts. Replaces old kline function with new supercalc

* Adds readme templates and files across whole backtester. Renames 420rsi to more appropriate name. Moves interfaces to common

* Some extra documentation

* New header

* Adds some nice coverage to backtest.go. Updats readmes to use new backtester header template

* End of day crappy test commit

* Adds report coverage... Somewhat. Adds template path and output path to allow custom properties and easier testing. Fixes interface duplication

* Adds some lame tests.

* Fixes test

* Adds coverage to the exchange event handler

* Minor test changes

* Fixes slippage calculations based on buying and selling. Adds more tests to compliance and holdings

* Rejiggles risk assessment to properly consider leverage if it were ever to be implemented fully. Removes bot dependency and adds coverage to the risk package

* Expands coverage to sizing

* Rejiggles code to add coverage for the portfolio package and its compatriots.

* Adds additional testing to the backtester along with some data gathering tests

* Tried and failed attempt to expand testing for the database.

* Adds testing for kline, data, statistics

* into the 70%s of coverage! Adds tests for base, DCA, statistics

* Adds test coverage of strategies

* Adds test coerage to statistics. updates template generation to not require CurrencyStatistics to have EAP. Removes EAP from currencystatistics

* Adds coverage to currencystatistics.go BUT ITS NOT COMPLETE

* 86% coverage wow. Fixes 2 tests

* Fixes data races due to engine dependency craziness. Changes order manager to not have a global dependency

* Completes currencystatistics test coverage

* Some linting fixes

* Adds new documentation to the bakctester config. Updates how risk leverage/ratios work with a single map.

* Minor documentation changes. Its difficult to describe how it all works

* Redefines strats and strat tests. Adds some really light documentation

* Updates some basic documentation.

* Fixes lazy bugs

* Fixes bug in fill event processing. Fixes bug in statistics crashing. Fixes report generation. Fixes multi-currency processing to still process non-errored signals

* More documentation.

* Fixes ALL LINTING ISSUES

* Cuts off unnecessary limbs/interface functions. linting. Adding comments to all functions. Adding ability to use whalebomb to calculate slippage for live orders. Adds testing for it too. Simplifies adding events to statistics.

* Removes a weird overlap of holding features that made no sense and the writer of those functions should be ASHAMED. Adds additional documentation

* Fixes issue with data being outside ranges. Adds some extra validation to areas where people can mess around. Makes generating configs easier with consistent dates. Adds more documentation. Cleans up okex/okcoin implementation to some functions since people aren't understanding that they share a based okgroup and that anything that is the same between two functions only needs to be written once...................... Also fixes some bad gct script code

* Updated image and slight change to readme

* Removes unused code. Fixes up verbose and removes old comment

* Fixes issues with data validation for other data sources. Fixes bad reference in template

* Fixes missing data problem for last candle considered missing. Fixes issue where fill order crashes when sizing error occurs. Adds documentation

* Fixes issue with drawdown calculations. Fixes live data usage

* Adds some comments for good measure

* Default strat fix

* Fixes surprise linting issues

* gofmt

* New linting issue with every commit

* Fixes testing. Adds new config setting to set a custom gocryptotrader config path. Updates config tests to use dryrun. Results now include the nickname in the file for easier identification

* Fixes live testing bitstamp. Fixes some template issues. Adds comments.

* Updates max drawdown calculation to go peak vs trough. Fixes minor return issue. Removes unnecessary Data implementations. Removes weird verbose false. Fixes holdings calculations for boughtvalue. Removes Swingholder and just uses Swing. Fixes time calculation issue in kline

* End of day commit that breaks things. Fixes issue with documentation generation only going one space deep. Adds exchange name to warnings of missing candle data. Renames missing candle data function. Adds some testing to kline functions. Adds new ability to size modified orders to portfolio allowance. Addresses defer close and other small nits. Fixes slow loop

* End of day commit. There are too many mini changes to list. DateType to int. Default switch case. Returning earlier. Nil returns instead of ok. High low price in data, now used in max drop down. Missing data shown in the report.

* End of day commit moving things from stats to maths.

* Move the rest to math package and add testing

* Ammends slippage calculations for live. Adds sizing funds to order event. Improves CAGR calculation

* Mini fix commit for test

* End of day mini change for documentation

* Fixes in documentation and expanded error messages. Pretties up the report

* minor adjustments to sharpe ratio and other ratio calculations

* Fixes test by taking it out back. linting

* Fixes tests

* Fixes some tests, addresses some poor nits

* More test and lint fixes

* Fixes binance translation issue

* Further craziness into reducing the concurrent test issues

* lint

* Mini fix

* Geometric average added and tested. Adjusts application to support it. End of day experiementation with negative geometric mean. Fixes typo in currencystatistics package name

* Fixes geometric calculation. Adds sweet CMD logo

* fixes geometric mean 😆 can now disable logo output if you hate everything good in life

* lint

* Should fix test in appveyor by not being nil

* Fixes chance of getting no trades error. Maybe making nil events in the test will stop this poorly formed appveyor error

* Forgotten Y tail

* Check-ch-check-check-check-ch-check it out, minimising stutter is what its all about... Also provides more verbose error messages

* de-ooopsies the whoopsie

* Attempts to further address race issues when using global logs during start stop process

* Includes a copy of the logger itself when logging so that no log.Debug action can create a data race upon being changed globally

* Reduces bot usage further

* Removes sharpie from b-acktester

* comments, renames and bears, oh my!

* Fixes git merge issues/tests. Splits average calculation into their own functions. Clarifies math function and sell position comments. Removes taker fee from final report. Adds warning when maker and taker aren't appropriately set. Fixes config testing issue where the config was saved when running exchange_template tests. Adds new test to ensure the testconfig isn't changed unnecessarily

* More why to reason

* Remove test due to hash discrepancy.

* Updates maths to use errors. Updates tests to support it.

* Fixes error handling for some packages. Uses position value instead of position size. Fixes leverage ratio work. Removes extra binance windows

* Removes references to "multi currency" to shiny new verbiage "simultaneous processing"

* Fixes issue with extra data be appended and then declared missing

* Removes redundant code via code removal

* Does a larger transition to using error types. Addresses math related nits

* eat a mint while you lint

* Completes err definition sweep

* replaces over 80 instances of the same typo!

* Renames more properties with Maximum ratios. Adds examples to config readme. Updates config maker takers. Adds cool kline error

* Adds 'InclusiveEndDate' config property to API and Database datas. Adds testing for it. Updates readme for it

* splint

* Minor naming fix. Minor drawdown fix. Attempts to lower the bot usage when heaps of candles are requested.

* Large data set processing improvements

* Speeds up backtesting processing. Ensures rate limits are set

Processing of most events is done in a linear fashion. So functions that
relied on checking an events time for example, will now check the latest
before processing every interval. The functions will still work normally
in the event that someone wishes to use them out of order, but for
general backtesting, it greatly speeds up all processing.

Further, rather than comparing times all the time, I've introduced
offsets for comparisons of ints for events and with candle data tests

* Fixes build issue

* Adds committed funds stat. Adds config goal

Committed funds are calculated as the total amount of money currently in position
It allows for a strategist to get the maximum returns for the smallest funds

The goal function is to allow a strategist to set a goal description

* Fixes data race

* Adds unfinished config builder application

* End of day broken commit

I focussed on too many things at once and there are many things left to resolve

* Fixees panics

* Finishes config builder

* Fixes order manager start/stop. Improves config manager

* Fixes writefile reference

* Adds some extra readme

* Makes a more user friendly config builder. Fixes initial nil. Adds more order size reasons

* lint

* Adds warnings for when data is missing and ratios will be skewed

* bodMISSED bodmas

* Does not consider initial entry in performance calculations

Adds strategy description field
Adds cost basis to chart
Fixes time rendering on default configs

* Fixes bug in ratio calculations

* saveConfig := !(!false != !true) == true

* lint

* Fixes start end single day drawdowns. Expands cmd drawdown explanation

* Comment on rounding, updated report rounding

* Addresses readme link issues

* Actually fixes readme references

* Should truly solve readme links....

* Includes filename for report log

* Fixes panics, reduces csv trade candle size, no more science

* Removes more science

* test123

* Adds extra config validation

* Fixes the date validation

* Shows smaller fees

* Changes perfectly cromulent error message to start >= end

Co-authored-by: Andrew Jackson <andrew@disvelop.net>
2021-03-22 09:26:17 +11:00
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
Ryan O'Hara-Reid
4e828a8124 (Exchanges) Introduce validation method and small updates (#565)
* Remove pointer reference

* Fix portfolio withdraw tests

* Add nil protection in validator method to reduce prospective panics and for future outbound checking

* Updated tests

* ch order var to not ref package

* rm comparison

* Add order ID validation check

* Add exchange name validation check

* Add in test details

* fix tests

* fix linter issues

* linter issues strikes again

* linter rabbit hole

* Addr nitterinos

* Add validation variadic interface to define sets of functionality check POC

* didn't want to add an amount other than 0, didn't want to add address to exchange withdraw, didn't want to whitlist, can change if need be

* add coverage

* Add validation method options for exchange wrappers and abstracted validation into its own package

* Add validation code for structs in exchange template generation

* remove extra validation call as this is done in wrapper

* fix niterinos for examplerinos

* Add template to documentation tool and regenerated documentation

* Addr niticles

* Fix tests due to validation update

* Add more validation checks for modify/submit orders

* update tests

* fix more tests

* Add asset type to submit variable in tests and rpc call. Regen funcs.

* Add field to modify struct in tests

* applied field asset to cancel struct across project

* fix woopsy
2020-10-02 13:36:01 +10:00
Adrian Gallagher
d9bcf8246f Bump golangci-lint, Docker and Go CI versions (#564)
* Bump golangci-lint and Go CI versions

* Bump golangci-lint version

* Address nitterinos
2020-09-24 09:52:37 +10:00
Scott
16e35405a1 BUGFIX: PSQL Migration syntax fix (#550)
* Fixes asset typo and changes postgres migration to work

* Adds newline to appease
2020-09-10 10:51:49 +10:00
Andrew
39bbd8dfc9 (Feature) OHLCV data storage and retrieval (#522)
* WIP

* end of day WIP started migration of trade history

* added kline support to hitbtc huobi lbank

* added exchangehistory to all supported exchanges started work on coinbase 300 candles/request method

* end of day WIP

* removed unused ta and misc changes to flag ready for review

* yobit cleanup

* revert coinbase changES

* general code clean up and added zb support

* poloniex support added

* renamed method to FormatExchangeKlineInterval other misc fixes

* linter fixes

* linter fixes

* removed verbose

* fixed poloniex test coverage

* revert poloniex mock data

* regenerated poloniex mock data

* a very verbose clean up

* binance mock clean up

* removed unneeded t.Log()

* setting verbose to true to debug CI issue

* first pass changes addressed

* common.ErrNotYetImplemented implemented :D

* comments added

* WIP-addressed exchange requests and reverted previous GetExchangeHistory changes

* WIP-addressed exchange requests and reverted previous GetExchangeHistory changes

* increased test coverage added kraken support

* OKGroup support completed started work on address GetExchangeHistory feedback and migrating to own PR under https://github.com/xtda/gocryptotrader/tree/exchange_history

* convert zb ratelimits

* gofmt run on okcoin

* increased delay on rate limit

* gofmt package

* fixed panic with coinbene and bithumb if conversion fails

* very broken end of day WIP

* added support for GetHistoricCandlesEx to coinbase and binance

* gofmt package

* coinbase, btcmarkets, zb ex wrapper function added

* added all exchange support for ex regenerated mock data

* update bithumb to return wrapper method

* gofmt package

* end of day started work on changes

* models created for exchange/asset/currency/currencypair, new seed system created

* reworked test coverage added okgroup support general fixes/change requests addressed

* Added OneMonth

* limit checks on supportedexchanges

* reverted getexchangehistory

* started work on currency seeding and insertion

* reworked binance tesT

* added workaround for kraken panic

* :D extremely broken WIP

* renamed command to extended removed interval check on non-implemented commands

* added wrapperconfig back

* increased test coverage for FormatExchangeKlineInterval

* WIP

* increased test coverage for FormatExchangeKlineInterval bitfinex/gateio/huobi

* linter fixes

* zb kraken lbank coinbene btcmarkets support added

* removed verbose

* OK group support for other asset types added

* swapped margin to use spot endpoint

* index support added test coverage added for asset types

* added asset type to okcoin test

* gofmt

* add asset to extended method

* removed verbose

* Very broken WIP models need to be regenerated

* add support for coinbene swap increase test coverage

* removed verbose

* small clean up of okgroup wrapper functions

* verbose to troubleshoot CI issues

* removed verbose

* added error check reverted coinbasechanges

* attempting to fix broken model generation

* readme updated

* :D i broke so much

* model regeneration fixed & complete

* candle model filled out

* removed unused start/finish started work on decoupling api requests from kline package

* restructured coinbene, bithumb methods, added bitstamp support

* kraken time fix

* BTCMarkets restructure

* typo fix

* removed test for futures due to contact changing

* removed test for futures due to contact changing

* added start/end date to extended method over range

* WIP

* added sync option to candles

* converted to assettranslator

* removed verbose

* removed verbose

* removed invalid char

* reverted incorrectly removed return

* added import

* further template updates

* macos hates my keyboard :D

* misc canges

* started work on creating kline from databases eed

* x -> i

* removed verbose

* updated fixCasing to allocate var before checks

* sqlite3 supported work started

* removed time conversion

* further work on tets

* sort all outgoing kline candles

* fixCasing fix

* after/before checks added

* added parallel to test

* logic check on BTCmarkets

* removed unused param, used correct iterator

* converted HitBTC to use time.Time

* test update

* add iszero false check to candle times

* Seed exchange & OHCLV data for test usage

* updated resultlimit to 5000

* new line added

* added comment to exported const

* move date forward

* use configured ratelimit

* fixed pair for test

* panic fixed WIP on fixCasing

* fixCasing rework, started work on readme docs

* enable rate limiter for wrapper issues tool

* docs updated

* removed unused vars from tests

* removed err from return and formatted currency

* updated Yobit supported status

* Updated HitBTC to use onehour candles due to test exeuction times

* added further details to gctcli output

* added link to docs

* added link to tempalte

* disable FTX websocket in config_example

* fix poloneix

* regenerated poloniex mock data

* removed recording flag

* format on package

* moved exchange var outside of method scope

* reworked seeding into package

* verbose output improved

* removed verbose from candles

* Added comments to exported functions

* removed verbose output

* Reworking of tests

* end of day commit

* added SQLite migration for asset, test updates for exchange, added support for withdrawal for new exchange_name_id relation

* regenerated database models

* WIP

* test rework, sqlite migration updates for withdrawal

* Reworked error returns to stop duplications, format all output to UTC, changed gctscript OHLCV output to be unix timestmap, started work on seeding tool

* gofmt

* dbseed command for seeding exchanges added, removed seed from dbmigrate, LoadCSV method added for exchange

* go mod tidy

* added import candle from csv command to dbseed

* Removed reset & duplicate migrate command from helper, renamed struct to Item/Candle over Candle/Tick, added test coverage to dbseed, improved withdraw tests

* remove broken tests due to ORM generation of Fk, removed go unneeded goroutine for inserting records

* removed t.Cleanup usage because appveyor

* added test coverage to StoreInDatabase()

* removed unneeded data from config for test

* added new line

* Added down migration support to candle/asset removal, return original error and display rollback error

* removed unneeded err assignment, break out of loop on error

* add err check to method for test

* first pass changes

* WIP

* Updated migrations for both sqlite3 & postgres to create exchanges if any withdrawal_history records are found, removed migrate command

* removed argusage as usage information is provided by flags

* added inserted records return count and test coverage

* new line added

* Database: comment config details out to disable local postgresl testing by default

* added asset support

* Database: added error return when no exchanges are found, title exchange name across queries

* Fixed test data

* Database: removed migration bool from ConnectToDatabase(), removed empty line, insert asset on test

* Database: verbose linter :D

* Database/OHLCV: removed go module from dbseed command and reverted back to main module, converted interval to int64 to match other parts of code base, provided migrations to update database, poloniex fix to skip first candle

* dbseed: add completed message to output

* Database: added migration to add asset to uniq index for candle table

* Database: database -> exchange

* Database: add asset to upsert conflict

* Poloneix: fix for invalid interval

* regenerated poloniex mock data

* Database: added down migration for candle interval update

* OHCLV/Database: WIP

* OHLCV/Datastore: added new ValidateKline() method to check that asset, pair, interval are enabled/supported by exchange and updated tests

* revert configtest changes

* OHCLV/Kline: pointer assignment to ErrorKline & format pairs on check

* goimports

* migration updates

* Database/Candle: updated tests

* revert configtest changes

* ZB: updaed defaults to use uppercase pairs

* ZB: updaed defaults to use uppercase pairs

* revert pair formatting

* Switch over to .Cotains() method from pairManagement

* Added comment & ftx back 😆

* OHLCV/Datastore: (Candles): added not null to asset, (WithdrawalHistory): added not null to exchange_name_id), reworked KlineError return

* set verbose to false

* updated btc markets test

* Updated readme

* removed ability to have blank exchange name as indexing requires it

* remove old usedb and empty exchange check, return error on no data instead

* Updated kline test to match date range

* Renamed candles.exchange_id column to candles.xchange_name_id to match withdrawal table, return err on unwrap, zb fix revert

* regenerated sqlite3 models

* force UTC for sqlite.... because sqlite

* OHLCV/Datastore: upper case pairs on insert for consistency, remove unneeded rollback call on commit failure as it has no effect, move rollback outside of insertsqlite/insertpsql methods

* add error check for no candles

* nil length/cap is 0 in golang :D

* OHLCV/Datastore: updated wording on examples, removed duplicate testfile

* OHLCV/Datastore: updated README with links to dbseed

* dbtool -> dbseed
2020-09-03 17:13:53 +10:00
Adrian Gallagher
0d787bc259 Bump golangci-lint to v1.24.0, linter fixes and general code improvements (#478)
* Bump golangci-lint version, update Go version deps and generic code improvements

* Fix wesbocket resp nil check and zip closures

* Update pprof path
2020-04-09 13:07:32 +10:00
Scott
b686cf2e0e Feature: Websocket order handling (#446)
* Initial changes, removing exchange name as an arg and puts it in the pointer struct. Adds case to ws routines

* Adds CancelAllOrders func, adds GetByExchangeAndID. Adds modify handler in routines.go

* initial poor attempts to have bitmex work with new datahandler handlers. fixes ordersides

* bitmex Completes new order

* Better bitmex handling, but not complete. Begins a gargantuan task of unifying order data structs. Sometimes an order update will contain lot's of information, so its best to be able to update all fields of our orders, rather than just an arbitrary subset. As a result, everything will be broken for the foreseeable future :glitch_crab:

* Removes old order handler which did nothing. Updates order properties for everything everywhere - now consistent. Changes order status. Adds asset type and wallet address to all order types

* Adds order updater to update only relevant fields since the object is generic, we don't know what fields are passed from what exchanges. Adds "lastupdated" field to order.Detail. Expands order cancellation for engine orders.

* Ensures that new orders are added to the ordermanager's order store. Saaa many comments. Internalises orderStore get func. Adds internalOrderID to orderdetail and adds websocket support for it

* Fixes a cancelAllOrders oopsie doopsie

* Adds potential func to update orderdetails from an orderdetail struct. Unsure if will keep.

* Begins btcmarkets implementation. Expands order "stringToOrder" funcs to allow for some more flexible string coversions. Removes order.Submit via websocket as it would cause unlimited order place issues :D

* Finishes btc markets without testing

* Adds untested ws auth func to btse

* Finises btse, fixes btcmarkets bug

* Adds coinbasepro support

* Fixes a few more fields in coinbase pro and readds the extra subs

* Begins work on coinbene. Plus theyve added a new ws connection yeee

* Wasted a bunch of time adding support to an additional websocket that isn't needed ;_; Fixed a bug in coinbasepro. Fully kitted out coinbene support. Updates order types with all fields

* Removes extra websocket connection ;_;

* Finishes gemini. Fixes order side unknown

* Adds okgroup support. Moves byte reading to another function to allow for unit testing. Updates routines to use pointers. Updates date update handling for order details

* Finishes order data for okgroup websocket, but starts the STRANGE process of converting all other websocket endpoints to be a little less silly

* Cleans up okroup websocket implementation. Fixes bug in Gemini

* Adds poloniex support. Updates ws order handling

* new bitmex support. Adds some tests now that its all in its own func. Fixes poloniex bug

* Begins work on authenticated binance websocket

* Attempts to track user data via binance websocket

* Maybe finishes Binance websocket support

* Begins adding test coverage to orders.go. Updates names of script properties to match updated

* Begins an experiment with code coverage. Fixes more rebase issues

* Completes orders coverage. Botches a few other things though. Fixes more scripting stuff

* All tests in engine package pass

* Adds some loevely routine tests

* Moves ordermanager to test Bot ordermanager
Adds lovely routine tests to ensure things that get sent to be handled the data handler are handled by the data handler by handling them

* Replaces "wsHandleData" with "wsReadData" as that's what its going to do now.

* Splits all wsHandleData into wsReadData and wsHandleData to allow for easy testing via sending []byte json examples to test proper functionality. Breaks so many tests

* Fixes majority of test issues. But data races which are tough on the engine package

* "Fixes" test by removing shutdown test. It interferes with too many things. Requires some thought

* Tests all the binance websocket points

* Adds better bitfinex websocket support.

* Adds testing for bitfinex, bitstamp and btcmarkets. Fixes websocket bugs encountered

* Adds BTSE ws tests. Fixes bugs in ws

* Adds coinbase pro tests. Fixes any issues

* Coinbene tests

* Starts to handle coinut. Runs into a problem conceptually regarding websocket roundtrip and orders. Both events need to happen without impacting eachother/racing

* Addresses a data race issue regarding websocket and bot order management submission - order submission locks at an earlier point to prevent routines.go from creating an order before order submission creates it. Updates rpcserver to use order management bot to submit orders.

* Finishes the hectic coinut testing

* Adds tests for gateio

* Fixes rebase issues. Updates tests to work without being overloaded

* Begins testing of gemini. fixes up minor issues

* ginishes gemini tests and fixes

* Adds hitbtc tests. Fixes all the many issues with hitbtc websocket

* Adds remaining tests. Increases default test channel limit again

* Begins work towards huobi tests

* Finishes huobi tests

* Fixed all mythical rebase adventures

* Begins kraken transformation

* Finishes kraken. Fixes coinbene leverage now that its changed

* Begins okgroup testing

* Adds okgroup ws tests

* Does some poloniex

* Fixes basic curreny issue by extracting to func

* Begins redesign of poloniex websocket datahandling. Completes authenticated handling, now onto unauth

* Finishes poloniex revision

* Finishes ZB additions

* Fixes data races

* Fixes rebase issues. Fixes bad kraken logic

* Fixes after reviewing code

* lint everywhere

* Fixes lingering lints

* lint

* Adds test coverage to order detail and modify updating

* Fixes linting

* Fixes huge int, fixes date tests

* Adds GetByExchange, adds test for it. Protects fakepass echange. Renames DisplayQty to DisplayQuantity. Removes verbose. Adds some websocket properties.  Updates bitmex asset type in test

* Addresses timestamps, type abbreviations, verbosity. Expands binance kline switch cases. Updates some websocket capabilities.

* Adds coverage to the stringToOrderType/Status functions introduced in PR

* Minor fixes addressing some time, error text and use of StringDataCompareInsensitive

* Introduces shiny new system which checks if there is an awaiting ID, if found, processes via wrapper method, else, goes through wsHandleData method. Removes weird locking system from wrapper/websocket data race. Updates bitfinex to properly handle websocket order requests and notifications

* Moves fakePassingExchange to test_helper. Fixes some order side implementations for trades. Botches a new error type

* Adds new error type to track and handle order classification errors separately

* Fully fleshes out ClassificationError for all instances of status conversion. Even in order trades and some wrapper functions

* Introduces common.SimpleTimeFormat for "2006-01-02 15:04:05". Fixes binance and bitfinex issues with auth endpoint use, map casting. Expands more order.ClassificationError usage. Fixes some more generic websocket response errors

* Future proofs order updating by utilising asset types. Expands testing to accomodate. Adds shiny new time type. Expands wrapper websocket functionality definitions

* minty linty

* Broken end of day code addressing basic nits on comments, returns and currency conversion

* Adds testing to btcmarkets websocket. Also updates websocket orderbook to use update instead

* Fixes fun rebase fun fun so fun

* Addresses minor nits regarding changed interface and comments

* Creates new function `GetRequestFormattedPairAndAssetType` to retrieve a currency pair and asset type based on a string. It will iterate over enabled pairs and compare them to formatted pairs and then return that pair if found.

* Fixes test

* Adds a single line to the end of the file, because that would be really bad if it wasn't there

* Updates fakepassexchange to not use params, updates test params, uses fatal in some tests where its important, updates order manager to have a rwmutex, removes some returns, improves ws key test for binance, updates properties to reflect their actual values, adds some more websocket properties

* Addresses binance switch linting

* Updates leverage property to int64

* Fixes what was broken
2020-03-03 13:32:14 +11:00
Andrew
b26ec86d43 Withdraw additional functionality (validation/submission/tracking) (#409)
* reworked request struct and exchange response started work on validation system

* removed import cycle until work around

* Added intial withdraw support via CLI added

* Added Crypto command to gctcli

* moved var declartion to single line

* Test updates for binance and anx

* All exchange tests have been updated test coverage added to validate

* First pass at adding withdrawl select from database

* started adding basic lru cache system

* Added basic LRU cache including Add Get Remove Contains ContainsOrAdd Clear

* wording changes on comments

* removed exported var's in strut as they are not required

* Added README

* README updates

* corrected ID on commands

* rm line :D

* merged in origin/cache

* linter fixes (gofmt)

* Added basic cache lookup to events

* swapped to mutex over rwmutex updated comments

* unexported getNewest & getOldest

* unexported getNewest & getOldest

* Updated comments and cited references in source

* updated comments

* WIP

* Migrated exchange WithdrawFiat wrapper to new struct response

* Migrated exchange WithdrawFiat wrapper to new struct response

* started work on bank management

* Added exchange level banking details back with migration to banking package

* Removed broken tests for now

* Added validation to bank accounts

* removed duplicate bank details from withdraw struct

* Test coverage increased

* gofmt

* merged upstream/master with clean up

* First pass at adding command line linking to gctcli

* added validation for crypto address, added gctcli support to retreive previous withdrawal requests

* general cleanup

* general cleanup

* reordered imports

* Increased test coverage moved to database sublogger

* Pass incorrect currency no longer return error from c.CheckBankAccountConfig

* remove TestMain() for now as other tests in this package will need to be reworked

* Happy little race car

* Reverted to upstream tests

* Added test covarege for validation method, corrected response on cli protobuf

* query clean up and removal of duplicated code

* cleaned up queries into singlem ethod increased test coverage

* Migrated international fund withdraw to new exchange response and added cache size override

* Migrated international fund withdraw to new exchange response and added cache size override

* Extended gctcli commands

* lowered default cache to 25

* small code clean up

* added get by date method

* add returned error

* cli commands cleaing return error on nil results to fix out of bounds

* merged write & read helpers into one for test coverage and increased engine/withdraw test coverage

* gofmt

* Added test coverage for valid ID

* removed unused param

* converted to use timestamp package from protobuf

* gofmt

* use built in RFC3339 timestamp

* remove setting of CreatedAt & UpdatedAt and allow ORm to take care of it

* also use ptype on byid

* code flow improvements

* remove inverse conditional check and linters run

* removed test data

* removed comment

* removed comment

* also write failures to database for auditing

* converted to use default time for start & end

* Default to time.Now() minus 30 days

* Default to time.Now() minus 30 days

* small code clean up

* fixed missing semicolon on migrations, code clean up

* updated sqlite migrations

* Added additonal check for exchange level bank account if global is not found

* case sensativity fix for currency names

* use correct compare

* test coverage fixed

* removed space

* return pointer to banking.Account

* return pointer to banking.Account

* added else check back to validate()

* Added empty string as default to migration over NULL due to retrivial of data
2020-02-26 15:45:13 +11:00
Andrew
f515a2bcbd (QOL) Improve test setup for logger, improve test coverage for database (#447)
* Improved test setup for logger, improved test coverage for database

* removed some new lines

* add new line

* removed database config detailS

* removed lines

* code cleanup
2020-02-17 11:29:26 +11:00
Andrew
7fccc03164 (Logger) Rename package to log (#444)
* renamed package to log to stop side import requirement

* reverted comment changes

* reverted comment changes

* one more reverting wording back to logger

* wording changes on comments
2020-02-12 18:09:56 +11:00
Adrian Gallagher
b949388994 General engine improvements (#437)
* Add exchange manager to engine

* Several improvements for engine and friends

1) New file.Exists func
2) gRPC TLS cert expiration date check and regeneration
3) New donation var for use across the codebase
4) Use Go log package until the logger is initialised

* Add cert tests and create dir tree if it doesn't exist for file.Write

* Link up donation address to documentation tool plus minor adjustments

* Fix remaining donation addrs

* Move non-needed reload exchange funcs

* Revert accidental config_example.json changes 🕯️

* Use go logger for logging until the logger has initiliased, otherwise no output will be seen

* Link up portfolio delay val and other fixes

* Run go mod tidy after dependabot PR

* Address nitterinos
2020-02-06 12:32:01 +11:00
Andrew
f6fd94ea69 Engine: Scripting support (#383)
* WIP

* updated appveyor and increased deadline 5 seconds due to increased linters being added

* revert files to upstream/engine

* WIP

* WIP

* mod file changes

* added script manager

* Added manager/and cli interfaces to scripting

* Added script task handler

* WIP - Added timer/repeat support and fleshed out wrapper further

* autoload support added + WIP

* WIP commit

* added account balance info

* btc markets temp work around

* WIP - merged with upstream for new order package BTC Markets responses broken

* Cancel order wrapper WIP

*  order wrapper update

* Added test coverage for VM

* moved to map for VM List shutdown of all VM now handled added gctcli commands for list and stop of running scripts

* added override to load/execute for path

* fixed incorrect channel shutdown added further test coverage and restructured gctcli commands into sub commands

* increased test coverage for packages

* Added docs cleaned up tests and example scripts

* Test coverage increased for module/gct/exchange package

* windows fixes

* merged upstream/engine

* WIP

* logger fixes - removed pointer to bool check removed duplicate test check for logger

* remove unused mutex

* added inital upload support

* fix linter issues for go-fmt

* added zip support for uploading and added base for fund withdrawing

* changed error return types and also log errors, fix zip path issue

* improved error outputs and code flow

* pairs response fix added protobuf defs for stop all and list all

* added stop all running scripts general clean up and moved across to OrderManager

* linter fixes (gofmt)

* added list all command

* rewrote zip handler to be cleaner also fixed file overwrite on upload

* added query command reworked tests

* added further error checking to compileandrun corrected use of pointers for accountinfo

* bumped tengo version

* Removed named returns reworded log messages removed unused falseptr

* WIP

* Added virutal machine limit improved config options

* added model for script event added upload validation

* script_event table has been completed, tests for wrapper functions implemented

* README updates

* reverted changes opened new PR to move withdraw struct outs

* intial work on adding withdraw support after merger of withdraw package

* started work on examples

* Added crypto withdraw support

* fix switch case assignment and gofmt project

* Reworking Fiat withdraw request pending #402

* removed double pointer call

* added withdraw support for fiat  currencies

* added tests for withdraw methods increased readme

* removed local tengo require and also fix linter issues

* Added default log size const added basic test for invalid script execution

* First pass at moving wrapper to validator package to allow proper validation of uploaded scripts

* Added script details to README added config test added test for no file extension

* moved tests to const and fixed incorrect pathing

* added test coverage to withdraw package

* corrected file close handling

* point to included configtest.json

* extended validator support when a script is uploaded

* Bug fix on bool logic

* Added mutex

* Don't create autit events on test execution

* reverted common to master

* moved file rename to unix timestamp format

* converted logger enabled back to pointer as i need nilness check also moved scriptid to text over blob

* started work on autoload add/remove support

* First round of PR fixes (mostly commented exports)

* Moved GCTScript load to last, removed unneeded error from cleanup()

* Comment clairty for AuitEventID

* added autoload add/remove command to cli

* added tests for autoload

* Test updates for Exchanges

* linter fixes (gofmt)

* Removed double check of engine pointer

* remove possible nil pointer on GetSpecificTicker

* Fixed not closing file handler on write that causes archive removal to fail

* file handler Close clean ups

* corrected spelling on error return and return invalid name n autoload

* moved strings to cosnt moved bool pointer creation to convert package

* new zip extractor added

* Validation has been added to archive uploads

* removed shadow var on err

* added ok check to conversion

* converted condition check

* basic test for zip extract added

* new zip handler

* reverted back to old atomic loading system

* removed shadow err

* lets add a new line

* added space to error return

* command line toggle for script now works properly

* readme updated

* set configLoaded to true

* check for configLoaded condition

* added mutex to allow for multiple access on virtual machine increased test coverage disable script manager if scripting is disabled

* linked up to enable/disablesubsystem commands

* added start/stop example to readme

* reworked logic on test as check should be done on Load()

* updated to tengo v2

* linters

* lower time on ntp client to stop slippage

* remove all fails if any fail validtion from an archive

* remove vm from list if timer is invalid

* removed shadow on err

* remove config creation from NTPCheck test

* WIP testing DB changes

* add unique constraint

* WIP: created has many model

* linters run

* basic sqlite3 support added for new database format

* linters run

* Added test coverage for script repo

* removed unused print

* updated env vars for CI instances

* updated env vars for CI instances

* Updated test packages

* Test updates for postgresql

* removed invalid tests from postgres

* remove duplication of struct and improved code flow

* general cleanup

* wording changes on log output

* use databasemgr logger and add support for autoload without file extension

* corrected test naming

* return correct error

* return correct error again version 82

* store scriptdata on creation

* Hello

* Errorln -> Errorf

* Removed unused vars

* Read me updates

* testing without parallel

* comment on exported type

* added nil check against VM for test

* add debugging information

* gofmt

* remove verbose and data sent to channel

* Added debug information

* linter fixes (gofmt)

* remove unused CompileAndRun() call

* test sleep to see if issue is timing related

* semi-concurrent map fixes

* one day i will run gofmt or setup precommit hooks

* new line :D

* increased test coverage

* added correct sleep time

* Moved over to sync map

* linter fixes (gofmt)

* goimports

* moved VM related methods to vm.go

* new line at end of file

* trying increased timeout on golangci-lint for appveyor

* add debugging information

* removed timeout

* reworked timeout logic

* linter fixes (gofmt)

* increased test coverage

* increased test coverage

* one day i will run gofmt or setup precommit hooks

* removed unused exchange test

* increased golangci-lint timeout

* Added nil check on shutdown and test coverage for it lowered timeout back to 1:30

* reworked ID system

* removed script hash as it was unused

* added comments on exported methods and read me update

* reorder code

* removed to atomic.value for test execution flag

* increased test coverage

* move add further up execution

* point to correct script file
2020-01-23 13:54:04 +11:00
Andrew
92147cdc5f (Engine): Database system improvements (#358)
* Migrated to goose & sqlboiler

* create tests with sqlboiler

* code clean up

* Added gct -> sqlboiler config gen

* dropped pgx support

* dropped pgx support because who needs connection pools

* reenable sqlite audit tests

* first pass of migration changes

* stuff is broken :D

* sqlboiler :D

* end of date commit

* Added comments code clean up

* revert go module files back to upstream

* bug fix

* pushed go.mod update to use correc goose version

* renamed sqlite to sqlite3 for consistency across codebase and PR feedback changes

* makefile updates

* things are broken end of day commit

* added postgresql test

* use correct database name

* travis fixes for env vars

* travis fixes for env vars

* test fixes

* run migration on test setup

* test adding postgres support to appveyor

* Skip tests on appveyor due to issues with missing binaries

* oh yeah i have to support windows don't i

* bumped goose version up

* add postgres to osx

* fix travis config as osx does not support services move spin up to before_script

* added PGDATA path fix

* pass PG_DATA to pg_ctl

* added initdb to before install

* fixes to wording and bumps up goose version

* who needs ssl anyway

* moved ssl to correct section :D

* bumped goose version up

* unbreak travis

* unbreak travis

* fix if database is disabled in config

* move strings to consts

* converted more strings to const

* improvements to sqlboiler mmodel gen

* Added contrib\sqlboiler file

* sqlboiler windows contrib fixes

* bumped goose version up

* :D whoops

* further fixes to sql models

* further fixes to sql models

* database type fix for config gen

* README update

* go.mod clean up

* added config details for appveyor

* appveyor ordering fix

* force psql9.6

* appveyor config changes

* all the environmen vars

* model changes for psql

* model changes for psql

* sqlite model fixes

* attempt at osx fix

* added error check for migration

* typos and check against goose error instead of string :D

* updated sqlboiler commit id

* bump sqlboiler version again

* set decimal package to @0bb1631

* readme and makefile updates

* bump goose version update readme and add override flag to config gen

* README typo fix and lowered inserts in test down to 20 as we are only testing that inserts work running 200 was unnecessary

* added gctcli command for audit event

* Added debug output toggle to config added both postgres & sqlite support to gctcli command

* Wording changes on errors

* set sqlite to 1 connection to stop locke database issues

* Usage update for order

* README updates with config examples

* go.mod/sum tidy

* removed lines in import second

* removed lines in imports

* convert local time to utc for database and display output

* go mod clean up and error checking to time

* renamed all packages to sqlite3

* added windows command output for sql model gen

* time conversion fix

* time conversion on gctcli
2019-10-08 15:28:31 +11:00
Adrian Gallagher
132d2d03c2 Merge branch 'master' into engine 2019-09-24 17:05:58 +10:00
Adrian Gallagher
870fd6f4f3 Increase config test coverage 2019-09-13 16:53:41 +10:00
Andrew
0c76789b0d Database interface & auditing feature (#332)
* added audit manager

* Basic database DOA setup

* Added base config file

* added sqlite support and creation of schema

* added basic tests and config entry

* corrected issues of database is disabled

* fixed path for test

* WIP

* Added tests fixed config checking

* reverted files back to upstream

* reverted go.mod files

* no more test test test

* removed local testing details for psql

* hello

* added comments

* increased ping to 30 seconds

* renamed database table and added additional condition around test

* removed database test details

* goimport ran on all files

* WIP

* first attempt at migration

* fixes for migration system

* Migration system logger interface implemented

* fixes to print functions

* added write pooling pass

* gofmt :D

* formatted imports correctly

* removed old code

* added creation of migration

* gofmt

* :D Hello

*  🏎️

* maybe one day i will remember to revert go mod files

* checked err return condition correctly

* first changes for PR feedback

* code clean up

* protect Connected with RWmutex & event with mutex

* : D

* we can just pretend like it never happened

* MOved migrations back to source directory and added README

* readme formatting update

* Addd command line override for datadir

* use correct var when creating a migration and confirm folder is created

* Check if database version is newer than latest migration and also you know make migrations work.....

* uses filepath instead of manual path to use correct path seperator

* Add connection message and lower timeout

* Added support for sslmode for psql

* no longer force Close of database instead allow driver to maage

* Added closer func to test output

* sslmode added to example config
2019-08-20 16:35:06 +10:00