Commit Graph

48 Commits

Author SHA1 Message Date
Ryan O'Hara-Reid
b87a0791b0 asset: bitmask type optimisation (#922)
* asset: basic optim. bitmask

* glorious: nits

* currency: forgot parralel in testttttt

* ticker/orderbook: test fixes

* engine/rpcserver: fix and expand tests
2022-04-28 09:49:43 +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
022001fecf btcmarkets: update order submission (#908)
* btcm/order: update order submission

* btcmarkets: addr nits

* btcmarkets: reinstate new order test
2022-03-25 15:05:24 +11:00
Ryan O'Hara-Reid
09fa2f236a context: Add authenticated HTTP credentials (#892)
* gRPC: context overide

* exchanges: continue update

* exchange: Update context handling
*Add setter methods for API credentials
*Shift credentials functionality to its own file in exchanges package
*Add tests
*Refactor function DeployCredentialsToContext for library usage
*Add function to process credential metadata from API boundary to internal use context value.
*Add OTP rpc handling

* exchanges: reverts to old style in GetFeeByType, reverts some code I accidently deleted. Plus things and other. XD

* template: update

* exchanges: fix linter issues

* REMOVE THAT AWESOME NEW LINE!

* gct: fix some tests

* I cant spell :(

* exchanges/gctscript: fix more tests

* coinnut: fix tests

* Update exchanges/credentials.go

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

* Update exchanges/credentials.go

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

* Update exchanges/credentials.go

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

* Update exchanges/credentials.go

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

* Update exchanges/credentials.go

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

* glorious: nits

* exchanges/gctcli: stop applying empty credentials

* fix linters

* exchanges: add test

* rpceserver: actually check error for errors

* rpcserver: fix up tests

* Update exchanges/credentials.go

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

* exchanges/creds: move tests to corresponding files, add protection and segration for Credentials struct & ptr values

* exchanges/creds: allow subaccount to override default credentials via gRPC

* exchanges/credentials: don't return nil in GetCredentials

* creds: spelling

* exchanges: fix glorious NITS!

* credentials: Add in test and refactor IsEmpty method.

* credentials: change type positioning (glorious)

* exchange_template: Fix template changes

* DOCS: Refresh

* docs: fix spelling

* DOCS: fix alignment and add package

* DOCS: ALIGN!

Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io>
Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
2022-03-21 13:58:08 +11:00
Scott
86d3724507 Futures order position tracking & FTX scaled collateral calculation (#868)
* implements futures functions and GRPC functions on new branch

* lint and test fixes

* Fix uneven split pnl. Adds collateral weight test. docs. New clear func

* Test protection if someone has zero collateral

* Uses string instead of double for accuracy

* Fixes old code panic

* context, match, docs

* Addresses Shazniterinos, var names, expanded tests

* Returns subaccount name, provides USD values when offlinecalc

* Fixes oopsie

* Fixes cool bug which allowed made up subaccount results

* Subaccount override on FTX, subaccount results for collateral

* Strenghten collateral account info checks. Improve FTX test

* English is my first language

* Fixes oopsies

* Fixes for unrealised PNL & collateral rendering

* Fixes lint and tests

* Shaznit fixes

* Secret Shaznit

* Updates account information across wrappers to include more fields

* Updates online collateral calculations. Updates RPC data

* Accurately calculates collateral offline and online minus testing

* Tests and lint chocolate

* Simplifies accountinfo results

* Fixes shaznits

* Adds new func

* Increases collateral accuracy again again again x 200

* Increases accuracy of collateral rendering

* Fixes minor merge/test issues

* Linterino

* Fixes ws test. Improves collateral calculations and rendering

* Make it prettier

* Removes the lock I put on 👀

* Adds `additional_collateral_used` field, renders orig currency

* Fixes unrelated test

* Fix test

* Correctly calculate spot margin borrow collateral

* Address fun lint surprise

See https://github.com/golangci/golangci-lint/issues/741#issuecomment-1017014331

* Strange lint fixing x2

* Continued lint journey

* Nolint the nolint to not lint the lint

* Adds two new fields to response

* More linting issues arising

* fIX3s_c4s|NG

* Fixes command flags' incorrect numbering

* FairMarket = Won
2022-02-28 16:39:36 +11:00
Ryan O'Hara-Reid
11da520dc8 Currency: Add additional functionality, refactor and improvements (#881)
* currency: Add method to derive pair

* currency: Add method to lower entire charset but used the slice copy and returned that. This will change the original, just gotta see if this is an issue, but the slice usually goes out of scope anyway.

* currency/pairs: add filter method

* currency: add function to derive select currencies from currency pairs

* currency/engine: slight adjustments

* currency: fix linter issue also shift burden of proof to caller instead of repair, more performant.

* currency: more linter

* pairs: optimize; reduce allocs/op and B/op

* currency: Add in function 'NewPairsFromString' for testing purposes

* currency: don't suppress error

* currency: stop panic on empty currency code

* currency: Add helper method to match currencies between exchanges

* currency: fixed my bad spelling

* currency: Implement stable coin checks, refactored base code methods, optimized upper and lower case strings for currency code/pairs

* currency: add pairs method to derive stable coins from internal list.

* Currency: Cleanup, fix tests.

* engine/exchanges/currency: fix whoops

* Currency: force govet no copy on Item datatype

* Currency: fix naughty linter issues

* exchange: revert change

* currency/config: fix config upgrade mistake

* currency: re-implement currency sub-systems

* *RetrieveConfigCurrencyPairs removed
*CheckCurrencyConfigValues to only provide warnings, add additional support when, disable when support is lost or not available and set default values.
*Drop Cryptocurrencies from configuration as this is not needed.
*Drop REST Poll delay field as this was unused.
*Update default values for currencyFileUpdateDuration & foreignExchangeUpdateDuration.
*Allow Role to be marshalled for file type.
*Refactor RunUpdater to verify and check config values and set default running foreign exchange provider.

* currency: cleanup

* currency: change match -> equal for comparison which is more of a standard and little easier to find

* currency: address nits

* currency: fix whoops

* currency: Add some more pairs methods

* currency: linter issues

* currency: RM unused field

* currency: rm verbose

* currency: fix word

* currency: gocritic

* currency: fix another whoopsie

* example_config: default to show log system name

* Currency: Force all support packages to use Equal method for comparison as there is a small comparison bug when checking upper and lower casing, this has a more of a pronounced impact between exchanges and client instances of currency generation

* currency: fix log name

* ordermanager: fix potential panic

* currency: small optim.

* engine: display correct bool and force shutdown

* currency: add function and fix regression
* Change ConvertCurrency -> ConvertFiat to be more precise
* ADD GetForeignExchangeRate to get specific exchange rate for fiat pair
* Fix currency display and formatting regression and tied in with config.Currency fields

* engine: fix tests

* currency: return the amount when no conversion needs to take place

* currency: reduce method name

* currency: Address nits glorious nits

* currency: fix linter

* currency: addr nits

* currency: check underlying role in test

* gct: change to EMPTYCODE and EMPTYPAIR across codebase

* currency: fix nits

* currency: this fixes test race but this issue has not been resolved. Please see: https://trello.com/c/54eizOIo/143-currency-package-upgrades

* currency: Add temp dir for testing

* Update engine/engine.go

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>

* documentation: update and regen

* currency: Address niterinos

* currency: Add test case for config upgrade when falling over to exchange rate host as default from exchangeRates provider

* currency: addr nits

* currency: fix whoops

Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io>
Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>
2022-02-17 16:24:57 +11: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
Ryan O'Hara-Reid
da3402476e tool/exchange_wrapper_coverage: fix regression and implement reflection (#837)
* cmd/tools/exchange: fix regression and implement reflection so as this can dynamically scale to our interface

* exchanges: add comment and fix whoopsie

* exchanges: fix linter issues

* wrapper_cov_tool: add actual full interface method count to get a better perceived deployment

* exchanges/tool: addr glorious nits

* kraken: remove string in test

* exchange_template_tool: fix tmpl issue
2021-11-17 15:41:21 +11:00
Adrian Gallagher
0c00b7e1df exchanges/engine: Add multichain deposit/withdrawal support (#794)
* Add exchange multichain support

* Start tidying up

* Add multichain transfer support for Bitfinex and fix poloniex bug

* Add Coinbene multichain support

* Start adjusting the deposit address manager

* Fix deposit tests and further enhancements

* Cleanup

* Add bypass flag, expand tests plus error coverage for Huobi

Adjust helpers

* Address nitterinos

* BFX wd changes

* Address nitterinos

* Minor fixes rebasing on master

* Fix BFX acceptableMethods test

* Add some TO-DOs for 2 tests WRT races

* Fix acceptableMethods test round 2

* Address nitterinos
2021-10-15 15:55:38 +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
Ryan O'Hara-Reid
5dfbbf84de engine/exchanges: Add exchange currency state subsystem (#774)
* state: Add management system (init)

* linter: fix

* engine: gofmt

* gct: after merge fixup

* documentation: add

* rpc: implement services for testing

* gctcli: gofmt state_management.go

* documentation: reinstate lost information

* state: Add pair check to determine trading operation

* exchanges: add interface for specific state scoped subsystem functionality

* engine/order_man: reduce code footprint using new method

* RPC: implement pair trading request and change exported name to something specific to state

* engine: add tests

* engine: Add to withdraw manager

* documentation: reinstate soxipy in contrib. list

* engine: const fake name

* Glorious: NITERINOS

* merge: fix issues

* engine: csm incorporate service name into log output

* engine: fix linter issues

* gct: fix tests

* currencystate: remove management type

* rpc: fix tests

* backtester: fix tests

* Update engine/currency_state_manager.go

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

* Update engine/currency_state_manager.go

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

* Update exchanges/currencystate/currency_state.go

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

* Update exchanges/alert/alert.go

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

* Update exchanges/alert/alert.go

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

* glorious: nits

* config: integrate with config and remove flag delay adjustment

* gctcli: fix issues after name changes

* engine: gofmt manager file

* Update engine/rpcserver.go

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

* engine: Add enable/disable manager functions, add default popoulation for potential assets

* linter: fix

* engine/test: bump subsystem count

* Update engine/currency_state_manager.go

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

* Update exchanges/bithumb/bithumb.go

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

* glorious: nits addressed

* alert: fix commenting for its generalized purpose

* glorious: nits

* engine: use standard string in log output

* bitfinex: apply patch, thanks @thrasher-

* bitfinex: fix spelling

* engine/currencystate: Add logs/fix logs

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
2021-09-27 13:33:49 +10:00
Ryan O'Hara-Reid
d636049fb2 exchanges: Initial context propagation (#744)
* gct: phase one context awareness pass

* exchanges: context propagation pass

* common/requester: force context requirement

* gctcli/exchanges: linter fix

* rpcserver: fix test using dummy rpc server

* backtester: fix comments

* grpc: add correct cancel and timeout for commands

* rpcserver_test: add comment on dummy server

* common: deprecated SendHTTPGetRequest

* linter: fix

* linter: turn on no context check

* apichecker: fix context linter issue

* binance: use param context

* common: remove checks as this gets executed before main

* common: change mutex to RW as clients can be used by multiple go routines.

* common: remove init and JIT default client. Unexport global variables and add protection.

* common: Add comments

* bithumb: after dinner mints fix
2021-09-11 13:52:07 +10:00
Ryan O'Hara-Reid
a54c5107f4 engine: GetSubsystemsStatus fix (#773)
* engine: GetSubsystemsStatus fix

* engine: force map literal to stop doubling up on keys, expanded test coverage

* engine: Deploy default for migration requirement.

* glorious: nits addr

* glorious: suggestion

* tests: fix
2021-09-03 11:59:52 +10:00
Ryan O'Hara-Reid
8020e1ec6a linter: Enable error checking linter (#766)
* golangci: Enable err checking linter to expose unchecked errors.

* gct: handle errors across the board

* gct: handle errors NOTE: Found bug in FTX (WIP)

* linter: fix issues

* ftx/exchanges: fix bug where error was being returned when setting pair management variables to an already enabled state

* bitmex: fix bug where a dangly supported asset in config danglied up the place.

* linter: fix more linter issues

* linter: fix my terrible spelling.

* currency: fix test

* exchanges: fix tests

* logger: fix test

* exchanges: fix tests

* glorious: nits

* vm: revert rm variable and instigate test
2021-08-30 14:06:40 +10:00
Ryan O'Hara-Reid
4851e94eba Engine/ExchangeManager: Return error for method GetExchangeByName (#760)
* engine: Add error returns

* engine: after merge fixes

* engine: remove interface

* linter: fix shadow declarations

* engine: fix tests

* niterinos: fixed

* GLORIOUS NITS!
2021-08-26 13:09:14 +10:00
Ryan O'Hara-Reid
a2381310da GCT: general updates across codebase (#699)
* orderbook: export orderbook nodes for external strategy inspection

* orderbook: Add in methods for locking and unlocking multiple books at the same time e.g. book1.LockWith(book2); defer book1.UnlockWith(book2)

* include waiting functionality for depth change alert

* backtester: add word.

* log: include logger changes to impl with downstream integration

* engine: reduce params for loading exchange

* assort: rm verbose in tests, change wording in ob, expose sync.waitgroup for ext. sync options

* ticker: reduce map look ups and contention when using RW mutex when there are over 80% writes adds find last function to get the latest rate

* engine/syncmanager: add in waitgroup for step over for external package calls

* cleaup

* engine: linter fix

* currency/fx: include all references to fiat currencies to default

* orderbook: Add in fields to Unsafe type for strategies to detect potential out of sync book operations

* syncmanager: changed config variable to display correct time

* ordermanager: Add time when none provided

* currency/manager: update getasset param to get enabled assets for minor optimizations

* ftx: use get all wallet balances for a better accounts breakdown

* orderbook: unlock in reverse order

* bithumb: fixes bug on market buy and sell orders

* bithumb: fix bug for nonce is also time window sensitive

* bithumb: get orders add required parameter

* bithumb: Add asset type to account struct

* currency: improve log output when checking currency and it fails

* bithumb: Add error return on incomplete pair

* ticker:unexport all service related methods

* ticker/currency: fixes

* orderbook: fix comment

* engine: revert variable name in LoadExchange method

* sync_manager: fix panic when enabling disabling manager

* engine: fix naming convention of exported function and comments

* engine: update comment

* orderbook: fix comment for unsafe type
2021-07-29 14:42:28 +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
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
Ryan O'Hara-Reid
7b718700f7 orderbook: Implement initial linked list (#643)
* Exchanges: Initial implementation after rebase of depth (WIP)

* orderbook/buffer: convert and couple orderbook interaction functionality from buffer to orderbook linked list - Use single point reference for orderbook depth

* buffer/orderbook: conversion continued (WIP)

* exchange: buffer/linkedlist handover (WIP)

* Added some tests for yesterday

* linkedList: added more testing and trying to figure out broken things

* Started tying everything in

* continuous integration and testing

* orderbook: expanded tests

* go mod tidy

* Add in different synchornisation levels for protocols
Add in timer for the streaming system to reduce updates to datahandler
Add in more test code as I integrate more exchanges

* Depth: Add tests, add length check to call linked list updating, add in constructor.
Linked List: Improve tests, add in checks for zero liquidity on books.
Node: Added in cleaner POC, add in contructor.
Buffer: Fixed tests, checked benchmarks.

* orderbook: reinstate dispatch calls

* Addr glorious & madcozbad nits

* fix functionality and add tests

* Address linterinos

* remove label

* expanded comment

* fix races and and bitmex test

* reinstate go routine for alerting changes

* rm line :D

* fix more tests

* Addr glorious nits

* rm glorious field

* depth: defer unlock to stop deadlock

* orderbook: remove unused vars

* buffer: fix test to what it should be

* nits: madcosbad addr

* nits: glorious nits

* linkedlist: remove unused params

* orderbook: shift time call to outside of push to inline, add in case for update inster price for zero liquidity, nits

* orderbook: nits addressed

* engine: change stream -> websocket convention and remove unused function

* nits: glorious nits

* Websocket Buffer: Add verbosity switch

* linked list: Add comment

* linked list: fix spelling

* nits: glorious nits

* orderbook: Adds in test and explicit time type with constructor, fix nits

* linter

* spelling: removed the dere fence

* depth: Update alerting mechanism to a more battle tested state

* depth: spelling

* nits: glorious nits

* linked list: match cases

* buffer: fix linter issue

* golangci: increase timeout by 30 seconds

* nodes: update atomic checks

* spelling: fix

* node: add in commentary

* exchanges/syncer: add function to switch over to REST when websocket functionality is not available for a specific asset type

* linter: exchange linter issues

* syncer: Add in warning

* nits: glorious nits

* AssetWebsocketSupport: unexport map

* Nits: Adrr

* rm letter

* exchanges: Orderbook verification change for naming, deprecate checksum bypass as it has the potential to obfuscate errors that are at the tail end of the book, add in verification for websocket stream updates

* general: fix spelling remove breakpoint

* nits: fix more glorious nits until more are found

* orderbook: fix tests

* orderbook: fix wait tests and add in more checks

* nits: addr

* orderbook: remove dispatch reference

* linkedlist: consolidate bid/ask functions

* linked lisdt: remove words

* fix spelling
2021-04-23 15:16:01 +10:00
Scott
3c72a199f2 Feature: Faster start & stop times (#648)
* Updates starting and stopping routines to be a bit more parallel with less waiting required

* Removes stop, removes debugging output

* linting and test fixes

* Add extra kill switch for exiting on exchange loading delay

* Fixes fun math

* breaks loop instead of switch. Moves param warns higher

* Removes unceccary gos. passes in cfg to remove data race

* Removes os signal processing. Fixes bad master merge
2021-03-23 10:18:57 +11: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
Adam
504c2fad6d Feature: Implement funding rates, futures and coin margin (exchange API coverage) (#530)
* ALMOST THERE

* more api wips

* more api thingz

* testing n more api wipz

* more apiz

* more wips

* what is goin on

* more wips

* whip n testing

* testing

* testing

no keys

* remove log

* kraken is broken

ugh

* still broken

* fixing auth funcs + usdtm api docs

* wip

* api stuffs

* whip

* more wips

* whip

* more wip

* api wip n testing

* wip

* wip

* unsaved

* wip n testing

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* whip

* wrapper authenticated functions

* adding asset type and fixing dependencies

* wip

* binance auth wrapper start

* wrapper functionality

* wip

* wip

* wip

* wrapper cancel functions

* order submission for wrappers

* wip

* more error fixing and nits

* websocket beginning n error fix

* wip

* WOW

* glorious n shazzy nits

* useless nits

* wip

* fixing things

* merge stuffs

* crapveyor

* crapveyor rebuild

* probably broke more things than he fixed

* rm lns n other thangs

* hope

* please

* stop it

* done

* ofcourse

* rm vb

* fix lbank

* appveyor please

* float lev

* DONT ASK RYAN FOR HELP EVER

* wip

* wip

* endpoint upgrades continued

* path upgrade

* NeeeNeeeNeeeNeeeNING

* fix stuffs

* fixing time issue

* fixing broken funcs

* glorious nits

* shaz changes

* fixing errors for fundmon

* more error fixing for fundmon

* test running past 30s

* basic changes

* THX AGAIN SHAZBERT

* path system upgrade

* config upgrade

* unsaved stuffs

* broken wip config upgrade

* path system upgrade contd.

* path system upgrade contd

* path upgrade ready for review

* testing verbose removed

* linter stuffs

* appveyor stuffs

* appveyor stuff

* fixed?

* bugfix

* wip

* broken stuff

* fix test

* wierd hack fix

* appveyor pls stop

* error found

* more useless nits

* bitmex err

* broken wip

* broken wip path upgrade change to uint32

* changed url lookups to uint

* WOW

* ready4review

* config fixed HOPEFULLY

* config fix and glorious changes

* efficient way of getting orders and open orders

* binance wrapper logic fixing

* testing, adding tests and fixing lot of errrrrs

* merge master

* appveyor stuffs

* appveyor stuffs

* fmt

* test

* octalLiteral issue fix?

* octalLiteral fix?

* rm vb

* prnt ln to restart

* adding testz

* test fixzzz

* READY FOR REVIEW

* Actually ready now

* FORMATTING

* addressing shazzy n glorious nits

* crapveyor

* rm vb

* small change

* fixing err

* shazbert nits

* review changes

* requested changes

* more requested changes

* noo

* last nit fixes

* restart appveyor

* improving test cov

* Update .golangci.yml

* shazbert changes

* moving pair formatting

* format pair update wip

* path upgrade complete

* error fix

* appveyor linters

* more linters

* remove testexch

* more formatting changes

* changes

* shazbert changes

* checking older requested changes to ensure completion

* wip

* fixing broken code

* error fix

* all fixed

* additional changes

* more changes

* remove commented code

* ftx margin api

* appveyor fixes

* more appveyor issues + test addition

* more appveyor issues + test addition

* remove unnecessary

* testing

* testing, fixing okex api, error fix

* git merge fix

* go sum

* glorious changes and error fix

* rm vb

* more glorious changes and go mod tidy

* fixed now

* okex testing upgrade

* old config migration and batch fetching fix

* added test

* glorious requested changes WIP

* tested and fixed

* go fmted

* go fmt and test fix

* additional funcs and tests for fundingRates

* OKEX tested and fixed

* appveyor fixes

* ineff assign

* 1 glorious change

* error fix

* typo

* shazbert changes

* glorious code changes and path fixing huobi WIP

* adding assetType to accountinfo functions

* fixing panic

* panic fix and updating account info wrappers WIP

* updateaccountinfo updated

* testing WIP binance USDT n Coin Margined and Kraken Futures

* auth functions tested and fixed

* added test

* config reverted

* shazbert and glorious changes

* shazbert and glorious changes

* latest changes and portfolio update

* go fmt change:

* remove commented codes

* improved error checking

* index out of range fix

* rm ln

* critical nit

* glorious latest changes

* appveyor changes

* shazbert change

* easier readability

* latest glorious changes

* shadow dec

* assetstore updated

* last change

* another last change

* merge changes

* go mod tidy

* thrasher requested changes wip

* improving struct layouts

* appveyor go fmt

* remove unnecessary code

* shazbert changes

* small change

* oopsie

* tidy

* configtest reverted

* error fix

* oopsie

* for what

* test patch fix

* insecurities

* fixing tests

* fix config
2021-02-12 16:19:18 +11:00
Ryan O'Hara-Reid
f050c13daa remove rounding from scripting TA (#591) 2020-11-09 04:14:10 +00:00
Rauno Ots
1b65d97b65 Engine/GCTScript: Refactor script manager (#580)
* refactor script manager

* remove singleton GCTScriptConfig
* create constant for ".gct" extension
* move GctScriptManager into vm package
* reduce script manager global dependencies
* use manager struct to store runtime override values
* enable/disable scripting subsystem now doesn't store the setting in
config (aligned with other subsystems)
* setting max VMs via start option doesn't change config

* instantiate scriptmanager as part of creating a new Engine

    * script manager config is now set during instantiation
    * run script manager when enabled in conf or explicitly enabled
    * use the Started() method to check if script manager is running

* in tests set script manager as running

* script manager adjustments

* create manager before attempting overrides
* check for nil config when creating script manager

* fix script manager waitgroup counter increased too late

* move autoload() function to autoload.go
* add tests to script manager
2020-11-05 15:44:53 +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
Scott
12263997c0 Bugfix: Submit/Cancel order scripting errors + Ordermanager GetOrder & CancelOrder improvements (#584)
* Fixes Submit and Cancel order functions for scripting. Adds tests to ensure that wrapper functions actually execute as expected. Adds more coverage. Fixes a few other tests

* Fixes issues

* Simplifies tests

* Update cancel order to properly cancel an order. Adds example script. Adds sweet tests.

* Fixes bad test setup for cancelling orders

* Adds new order manager GetOrderInfo function to call the wrapper function and then store it in the order manager

* Addresses order concerns

* LOWERS THE CASE OF ALL EXCHANGE NAMES BECAUSE ORDER MANAGER NEVER CARED ABOUT CASING OR YOUR FAMILY

* Removes asset and currency requirement from cancelling orders via validation test

* Fixes old cancel order assumptions that had requirements for currency and asset

* Moves all the logs and events to the dedicated Cancel function instead of exclusively doing it in CancelAllOrders

* Adds more detail logging. Fixes lbank fee test

* Addresses comms manager issues

* Removes go routine for pushing events. Better to let them fail
2020-10-27 17:05:43 +11:00
Vazha
fab9d934fe Getting closed orders implementation, fixed Binance MARKET order creation, expanded SubmitOrder response (#572)
* GetClosedOrder implemented for Kraken and Binance, fixed Binance MARKET order creaton, added rate, fee and cost fileds on SubmitOrder responce

* return Trades on Binance SubmitOrder, new validation methods on Binance and kraken GetClosedOrderInfo

* removed the Binance extra method GetClosedOrder

* func description corrected

* removed price, fee and cost from SimulateOrder response, as we get all necessary info in response to calculate them on client side

* GetClosedOrder implementation moved to GetOrderInfo

* changed GetOrderInfo params

* removed Canceled order.Type used for Kraken

* update QueryOrder in gctscript

* add missed params to QueryOrder validator (gctscript)

* fixed testing issues

* GetClosedOrder implemented for Kraken and Binance, fixed Binance MARKET order creaton, added rate, fee and cost fileds on SubmitOrder responce

* return Trades on Binance SubmitOrder, new validation methods on Binance and kraken GetClosedOrderInfo

* removed the Binance extra method GetClosedOrder

* func description corrected

* removed price, fee and cost from SimulateOrder response, as we get all necessary info in response to calculate them on client side

* GetClosedOrder implementation moved to GetOrderInfo

* changed GetOrderInfo params

* removed Canceled order.Type used for Kraken

* update QueryOrder in gctscript

* add missed params to QueryOrder validator (gctscript)

* fixed testing issues

* pull previous changes

* linter issues fix

* updated query_order exmple in gctscript, fixed params check

* removed orderPair unnecessary conversion

Co-authored-by: Vazha Bezhanishvili <vazha.bezhanishvili@elegro.eu>
2020-10-22 11:54:24 +11:00
Ryan O'Hara-Reid
4ccb495baf Asset package update (#581)
* Rewrite new function and deploy where we can minimise the chance of setting an asset type that is different to supported list - sets validation to exact supported list

* change wording
2020-10-19 13:59:50 +11:00
Rauno Ots
8c86aac21d Config: fix don't create empty dir when resolving path (#575)
* Config: fix don't create empty dir when resolving path

* refactor migration of default config file

* gracefully handle src == target on Move
* create target directory on Move, if necessary

* unify resolution of default config location

* refactor the use of flagSet to be explicit
* remove package variable
* use empty config file path setting if not set in flags
* resolve default file location the same way when showing the target and
when loading default config file

* don't migrate if target file is the same as source

* rename configfile to configFile

* add migrateConfig tests
2020-10-15 13:24:43 +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
Rauno Ots
991dfed705 Engine: Refactor use of global Bot (#563)
* refactor use of global Bot

* make the dependency on having an existing running Engine more obvious
* use explicit dependency of engine in RPCServer
* reduce static dependencies in rpcserver
* improve helpers

* revert bad document update, add check for nil error in test

* add basic start stop test

* fix race condition in storage

* skip the test because of race conditions

* fix typo

* add empty line
2020-09-23 17:41:59 +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
Ryan O'Hara-Reid
14c72c9c6b Currency System Update (#448)
* initial update of currency system

* WIP progress

* Finish initial currency string error returns

* fix whoopsie testing for non https insecureinos

* Current WIP for getEnabledPairs check and error return

* WIP continued

* When getting enabled pairs throw error when item is not contained in available pairs list

* More updates -WIP

* Wip continued including potential interface

* Current WIP

* pairs manager pass

* drop asset string and just use the map key, plus return some errors and create more work for myself.

* clean and fixed a bug in currency.json, will not populate correctly without coinmarketcap api keys set.

* purge logger references after merge

* go mod tidy after merge

* Pointer change WIP

* fix some issues and added error returns to a few items (WIP)

* WIP

* Clean

* Fix some linter issues

* Fix more linter issues

* even more linters

* xtda nits

* revert pointer change and rm field

* Addr madcozbadd nits

* fix linter issues: shadow declarations

* Fix linter issues: gocritic huge things

* linter issue fix

* Addr nits

* flush go mod files

* after merge woops

* fix shadow dec

* Addr thrasher nits

* addr nits

* fix some issues

* more fixes

* RM println

* Addr glorious nits

* Add helper method for setting assets

* add missing format directive

* Addr nits

* Actually process new futures contracts -_- derp

* WIP for GRPC upgrade for pair management

* update config pairs

* finished disabling and enabling asset

* linked update of tradable pairs to cli

* fix oopsies

* defer writing to file on program termination for currency storage system

* update template

* don't add disabled asset items to initial sync

* Fix enable disabling a list of pairs and added in a slice error type so we can add whats allowable without throwing an error and return a report, also addressed some other nits

* WIP on getting a channel to unsub

* Wip track down unsubscribe bug and start creating streaming interface

* purge websocket orderbook object and centralised updating routine for orderbook

* general clean before interface implementation

* stage one connection interface WIP

* WIP

* repackage wshandler WIP

* find difference of subs and change signature of subscriber functions so we can batch subscriptions and unsubscription in exchanges that support it

* design change on mange subscription routine WIP

* integrated ZB with the new webosocket updates

* WIP - okex conversion

* integrate websocket upgrades for lakebtc, kraken, huobi, hitbtc, gateio, and WIP for coinbene

* integrate another range of exchanges for websocket update

* Added subscriber and unsubscriber methods to websocket functionality

* fixed tests WIP

* amalgamate cache setup with main websocket setup

* reinstate exported fields traffic alert and shutdownC to accommodate gemini and lakebtc implementations

* added in colon

* Updated websocket auth handling as they werent getting passed through. Added a setter method for websocket URL due to the Binance generated auth key/listenKey. Fixed bug which stopped reconnection.

* Fix subscribe candle bug
Fix time conversion in candle
Fix inititial candle history to datahandler
Include funding to orderbook handling
Include funding to trades
Reduce code duplication in sub and unsub functions
Added the ability to include funding currency websocket subscriptions
validated all channels and added more items todo list (Auth items)

* RM line

* bitstamp pass

* btcmarkets pass - still needs to implement unsubscriber functionality and pairs change test.

* Batch outgoing subscriptions and fix unsubscribe bug

* BTSE - bumped time to minute to reduce pinger calling by 75 calls per day. Fix authentication bug and add authentication pass into to-do. Batch outgoing subscription calls

* fix type field and batch outgoing subs and unsubs for coinbasepro

* Batch outgoing subs and unsubs

* Fixes bug when matching return from authentication

* Fix bug where params where being sent out of order due to map ,where depth items werent being subscribed too, where trying to subscribe to too many kline items caused error, where trying to get a nano secocond ID conflicted due to speed of generation.

* Add websocket capability for currency pair change by utilizing full channel subscription list in subscribe function.

* Add error handling

* Fix public: time conversions, subscription list, stopped pushing heartbeat to data handler, aggregated list of connections.

* hitBTC pass

* returned nil instead of error due to period null bids and asks updates coming through.

* Fix auth ping capture and reply. Added in interval handling for kline data. Added correct full trade data handling. Fix subscribe and unsubscribe.

* Fix when websocket auth conn and token generation fail we don't try and auth sub. Fix bug between auth and normal connection id generation and matching. Batch outgoing payloads to increase efficiency. Updated matching functions to utilise channels instead of waitgroups and go routines.

* RM debug output

* rm func to get shutdown channel

* Add unsubscriber functionality, added wsTicker type, removed return as this will impede data flow and cause reconnection when handling and processing data

* okgroup WIP

* *Added missing fields for websocket trades
*Fix bug processing kline interval
*Added fields for websocket ticker struct
*Fix auth bug
	-Updated request and response matching param to interface so we can custom signature match. Stops auth subscribing before a reply is issued.
	-Updated channel inclusion of pair fo auth subs as this was missing.
*Assortment of perfomance improvements

* poloniex pass

* send all trades to data handler, validated enabled and disable pairs

* initial clean

* centralised request matching mechanism

* websocket main improvements WIP

* WIP

* Websocket management via gctcli WIP

* GRPC expansion

* Updated GCTCLI with websocket url and proxy setting functionality which flushes connection

* Fix continuous spawning of routines bug on error with reconnection

* Addr linter issues

* fix subscription bug that I caused when I changed to a switch case

* fix linter issue

* fix woopsie

* End of day WIP

* Fix order submission REST, time conversion, order type conversion, orderID bugs

* fix gateio test and unsubscribe bug

* revert comment out code

* websocketAPI changed to to true in configtest.json

* fix race in gateio test

* End of day WIP for websocket tests.

* BugFix for binance when book isn't seeded. Updated websocket tests. Deprecated subscription manager. RM wrapper funcs.

* Added string title to exchange name as they are saved as lower case in type, reinstated verbose check in websocket.go

* Added verbosity check for setting websocket URL

* fix bug where the asset had a mind of its own

* purge dodgy coding

* Fix tests, drop blocking chan in websocket Dial function

* few more changes

* race condition fix for websocket tests.

* fix intermittent test failure due to underlying hash table storage

* Address madcuzbad nit

* RM superfluous printlines

* Add quick top example with paramater fields

* First pass Glorious nits

* As per madcozbad suggestion return error when enabled pair not found in full return map. Add test.

* addr madcozbadd nits

* as per glorious suggestion rm'd loadedJSON field

* adjusted ticker, added test and RM'd code that can never be executed

* Addr nits and add in crypto rand genration for ID's

* remove global channel declaration and rescoped as this was causing a lock

* as per glorious suggestion restructured return error for websocket

* addr glorious suggestions

* fix linter issues

* purge non-existent pair from testdata

* add side field to struct and parse

* addr glorious nits

* Add verbosity to error returns and logs and fix string parsing in GCTRPC

* fix speeling mistwake

* Adds websocket functionality check before flushing websocket connection

* Addr kraken panic and setting/flush websocket url stage one.

* added websocket url check before setting with tests

* Added in edge case test if by the time we call contains on available pairs it has been changed

* remove error return for func

* Continuation of tests

* continuation of tests

* Stop potential panic within pair creation function

* Implement changes to upstream

* rm sup comment

* fix bug when subscribing and unsubscribing. Also add in boolean to determine there are currencies that need to be flushed via set pairs via gctcli

* fix test

* Fix linter issues

* Fix tests

* turn websocket off in config example

* Fix issue where you cannot enable websocket when config is set to false, also added config websocket enable state saving

* Introduced err var for same error returns

* Add err var exchange base not found

* restructure function

* drop gctscript from generic response name

* drop managesub delay const as its not being used

* correctly implement websocket rate limiting for coinut

* remove quotations

* drop pair management check

* fix spelling

* return error in function to not update currency with unset role

* amalagamted enable/disable into set function and added in pairstore fetch function

* update error description

* rm function

* moved test function to sharedtestvals and move type to types.go

* append delimiter onto currency delimiter strings

* add test coverage

* rm functions as they are set as methods in base

* remove superfluous methods

* Fix issue that would occur when a subscription errored and not appending successful subs

* fix after rebase woopsie

* fix linter issues

* fix bug streamline code

* fix linter issues

* fix linter issues

* fix case where it should not change ID if set but append new

* fix whoopsie

* fix websocket tests

* fix readme, fix wrapper issues reporting template, go mod tidy

* add test coverage

* add test coverage and verified futures pariing

* add in futures bypass as its not currently supported on BTSE until API update and implementation

* removed downside/upside profit contract type as its no longer supported. Added in check in set config pairs to warn user of potential conflict and to manually remove or update.

* If asset enabled add pair and increase code coverage

* remove strings.title, set and fetch with strings.Lower but keep struct field exchangename unchanged. Streamline ticker and orderbook code.

* Add code coverage

* log error if setting default currency fails, add code coverage

* address glorious nits

* Addr xtda nits

* fix linter issues

* addr glorious nits

* xtda nits

* Addr glorious nits

* add subscription protection and removed a superfluous wait call

* fix test

* fix whoopsie

* addr xtda nits

* addr glorious nits

* Added asset types to subscriptions structs, also added in error handling for resubscription errors

* consolidated rpc returned type and added in sucessful strings

* dropped stream timing down to 100ms

* DOC changes

* proxy and url usage string additions

* WIP

* go mod tidy rides again

* Addr nits

* Addr nits, fix tests

* fix wording

* add in test case for currency matching

* Add byte length check on outbound websocket payload subscriptions

* addr thrasher nits

* Addr madcozbadd nits

* addr linter issues

* Addr glorious nits by amalgamating function into one mega amazing function.

* fix futures account subscription bug

* addr glorious nits and reinstated wg.Wait() checks

* changed string to currency delimiter string and setconnected by function
2020-07-24 13:18:09 +10:00
Andrew
4a736fb335 (Exchange) Add GetHistoricCandles() & GetHistoricCandlesEx() support to exchanges (#479)
* implemented binance and bitfinex GetHistoricCandles wrapper methods)

* coinbene supported added

* after and before clean up

* gateio wrapper completed

* merged upstream/master

* Added bsaic KlineIntervalSupported() method

* Converted binance fixed test

* WIP

* new KlineConvertToExchangeStandardString method added

* end of day WIP

* 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

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

* Added OneMonth

* limit checks on supportedexchanges

* reverted getexchangehistory

* reworked binance tesT

* added workaround for kraken panic

* 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

* 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

* readme updated

* 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

* added start/end date to extended method over range

* converted to assettranslator

* removed verbose

* removed invalid char

* reverted incorrectly removed return

* added import

* further template updates

* macos hates my keyboard :D

* misc canges

* x -> i

* removed verbose

* updated fixCasing to allocate var before checks

* removed time conversion

* 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

* add iszero false check to candle times

* updated resultlimit to 5000

* new line added

* added comment to exported const

* 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 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
2020-07-08 10:51:54 +10:00
Adam
c2c200cd1b (Exchange) Add FTX exchange support with implementation tutorial (#495)
* initial

* wip

* brokenwip

* broken wipzzzz

* more functions

brokenwip

NO API KEYS

* broken wip

* WIP

* wip

* WIP

work in progress

* WIP

* WIP

* wip

* more wip

* wip

* ws wip

* broken wip

* adding new functions for websocket to work

* trying to fix websocket issues

* websocket bug fix wip

* broken websocket implementation

* WS unauth functions + brokenWS auth func

* authentication problems

* authentication problems fixed

* data handling for websocket

* websocket completed

* remove verbose

* minor error fix changes and testing

* reorganising variable declarations and minor errors fixed

* enabled exchanges updated

* enabled exchanges fixed

* remove keys

* glorious nits

* xdta n shazzy nitzzz

* shazzy n thrasher nitz

* nitz wip

* broken wip

* apichecker donee n make code better

* apichecker donee n make code better

* OB update

* wip

* wip

* all nitz done

* merge conflicts

* go mod tidy

* merge conflicts

* PLEASE merge conflicts

* new funcs added n binanceapi check update

NO APIKEYS

* basic tests

* linter fixs

* linter fixs

* remove verbose

* test errors fixed

* remove comented code

* minor changes

* some tests fixed

no apikeys

* documentation work

* documentation

* wip

* ryan nitz

* nits addressed

* unnecessary conversion

* no fail

* remove verbose

* type field checking

* broken

* websocket nits fixed

* some thangs

* remove verbose

* fix function

* linter issues

* test error fixed

* nits

* bumperino fixed

* very small change

* nits

* errors fixing

* errors fixing retry

* linters

* thrasher glorious nits

* more changes

* changes

* 2 more changes to be addressed

* 2 more changes to be addressed

* issues addressed

* whip

* changes

* missed change

* changes

* currency issues

* changes

* unsaved

* int64

* HUGE

* HUGE

* NO NITS PLS

* no more

* YES

* :

* changes

* PLEASE

* n another one

* thanks guys

* ill believe in god if this ever ends

* :D
2020-07-02 10:38:50 +10:00
Adrian Gallagher
9f775ca952 Indicators: Add support for correlation coefficient (#519)
* Add support for correlation coefficient code

* Bump ta depends

* Bump gct-ta depends version
2020-06-23 17:49:08 +10:00
Adrian Gallagher
8afee0b4b2 Miscellaneous bug fixes (#513)
* Various bug fixes

* Deadlink, cleanup plus bug fixes

* Various Kraken fixes

* Add convert func for decimal unix timestamps

* Convert all test times to UTC

* Kraken: Make assets a pointer to prevent excessive copying

* Docker slash fix

* Address nits plus bump ITBit last checked pairs timestamp

* Set pairs to enabled pairs when getting active orders

* Use asset translator for UpdateAccountInfo and more checks for the exchange template tool

* Address MadCozBadd's nits

* Make exchange var 2 chars

* Make program more user friendly

* Project wide comment checks and exchName check

* Fix Huobi indexing bug and use correct pair formatting

* Address nits + readme change
2020-06-03 12:48:36 +10:00
Ryan O'Hara-Reid
0adf39de35 Update to GCT script library (#496)
* * Adds script link to GCT logger package
* Adds ability to save data as csv via script

* addr nits

* go mod tidy

* add glorious suggestion

* rm unused function

* fix linter issues

* clean up some issues

* Add in configuration fields to object for reflection to the csv file

* RM line :D

* address nits

* update to check for target already being set and add more test coverage

* force usage of .csv file extention && append date to client filename as to not overwrite file if collision occurs

* fix whoopsie

* linter issues

* purge getter methods

* Added glorious suggestion

* go mod tidy after merge

* niterinos
2020-05-14 11:05:46 +10:00
Andrew
70615279bd (GCTScript) Add technical analysis support via script bindings (#467)
* added mfi and example

* renamed to moving average

* converted to array return type and added obv and mfi

* started work on test coverage

* test coverage added for rsi & mfi

* test coverage added for all indicators removed go mod replace moved to append helper method

* moved all indicators to new appendTo and increased test coverage

* added additional test and bumped go-talib to latest commi

* go.mod update

* linter fixes

* go mod clean up

* small fixes

* reverted changes from previous attempt to rework as data is still incorrect now passing full OHLCV data back to script binding

* testing new structure of passing full ohlcv data

* started linking ohlcv to gctscript

* OHCLV link up completed reworking passing back to indicators started

* OHCLV link up completed reworking passing back to indicators started

* added test coverage for tofloat

* linter fixes (gofmt)

* removed unused value

* improved test coverage

* added correct detection for 1w added ParseInterval test coverage moved OHCLV string to const

* removed unused value

* first round of changes addressed

* all indicators have been split with packages named after each indicator and a new calculate() method added

* linters

* fixed tests

* added check to check ta is running in validator for uploading

* Added test data for OHLCV testing new indicator interface for wrapper

* typed const to float64

* reworked validator data to generate previous timestamps

* rewored macd to return slice of array

* adding bbands linking and example

* why didn't this pick it up before :D

* bumped up total number of modules for test

* moved parseIndicator to exchange added comments

* test coverage added for ParseMAType & ParseIndicatorSelector

* gofmt

* WIP changes

* updated tests for bbands  & obv bumped to latest go-talib

* move multiple use strong to const

* reverted rpc.pb.go to master

* added 4w option

* removed selector from obv as unneeded

* improved test coverage and reworked all indicator methods on how they pass errors back

* order incoming OHCLV data

* revert go.mod

* removed verbose toggles

* added spot asset type

* removed 4w as its unused/uncommon

* renamed

* reworked further tests

* converted all examples to use coinbasepro for consistency

* updated all date ranges to 2019 + 6 months

* backported binance OHLCV wrapper from #479

* removed o

* rounded numbers

* chnage requests addressed and attempt to fix MACD... today has been really unproctive code wise :D

* Migrated to gct-ta library

* Corrected test import

* wording changes on test

* removed TA lib from go.mod

* PR changes addressed

Removed parallel running from tests due to slight possibility in very extreme cases TestExecution might not be set to the expected value and will cause lower test coverage

* removed pkg folder

* bumped gct-ta version

* gct-ta version bump
2020-04-24 15:36:49 +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
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
Ryan O'Hara-Reid
a32d16e1f5 Expose auth validator functionality for wrapper (#416)
* expose auth validator functionality for wrapper

* Add REST validation after keys set, package account types for future syncing

* Add transient error checking for initial creddemtial validation

* fix command types

* Addressed nits from glorious person

* Amalgamate body within error when not between 2xx status, added btcmarket specific auth error check

* nit fix for glorious person

* Format fix

* removed unused code

* check transient first then validate if its an exchange specific authentication error, all others will be disregarded

* Addressed glorious nits

* Addressed glorious nits

* Moved account processing to updateaccountinfo func and added in fetch account info

* Add GRPC Account streaming (NOTE: could not complete until sync item added)

* RM exchange check

* Address xtda nits

* RM comment code

* Fix linter issues

* used most recent protoc version

* lbank linter issues fixed

* Addressed nits and changed len check to range in for loops

* Fixed timeout issue

* thrasher nits addressed

* add string holdings
2020-01-31 12:09:24 +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