mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-13 23:16:45 +00:00
c2d876d8b08fb8290f8687912562af681546162a
30 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d64d56f77c |
build/ci: Update Go to v1.24, golangci-lint to v1.64.6 and fix issues (#1804)
* build/ci: Update Go to v1.24, golangci-lint to v1.64.5 and fix issues * Address shazbert's nitters * linter/config: Fix new linter issue and use versionSize const * Address gk's nitters and fix additional linter issue after rebase * Address glorious nits * staticcheck: Fix additional linter issues after upgrading to Go 1.24.1 and golangci-lint v1.64.6 Also addresses nits * Improve testing, assertify usage and use common.ErrParsingWSField * TestCreateNewStrategy: Replace must > should wording |
||
|
|
649f3df266 |
engine: Add overridable exchanges command line flag (#1630)
* engine: Add overridable exchanges command line flag * Improve tests * engine: Add additional SetupExchanges edge case test and prevent suppressed dry run warnings |
||
|
|
0c40f90ceb |
requester: purge max request jobs (#1379)
* requester: purge max request jobs * request: rm unused error --------- Co-authored-by: shazbert <ryan.oharareid@thrasher.io> |
||
|
|
88182ec414 |
Engine: Remove Default Forex Provider (#1395)
* Currency: Do not use a default forex provider exchangerate.host now requires an API key. Instead of finding a new Free (for now) default, this change simply disables the currency exchange when nothing is enabled. * SyncManager: Report ?.?? for an unknown forex amount In a situation where we thought forex was available but we got an error, this avoids showing 0.00 when there was actually an error. * Currency: Tests for no default forex * Currency: Use mock provider for tests * Currency: Add API key to exchangerate.host * Currency: Remove Exchangerate.host Exchangerate.host was bought by apilayer, the old API deprecated, and replaced with a proxy to the apilayer api. We already have currencylayer support, so ther's no reason to keep exh. Worth noting: New ERH keys actually work on currencylayer * Currencies: Add test coverage for currency layer * fixup! Currency: Tests for no default forex Remove duplicate assignment Fixes [review comment](https://github.com/thrasher-corp/gocryptotrader/pull/1395#discussion_r1395178513) * fixup! Currency: Add API key to exchangerate.host Remove unused ErrVar Fixes [review comment](https://github.com/thrasher-corp/gocryptotrader/pull/1395#discussion_r1396647418) * fixup! Currency: Tests for no default forex Fix spelling of override in test Fixes [review comment](https://github.com/thrasher-corp/gocryptotrader/pull/1395#discussion_r1396701476) * fixup! SyncManager: Report ?.?? for an unknown forex amount Fix display of non-positive currency conversions. Fixes [review comment](https://github.com/thrasher-corp/gocryptotrader/pull/1395/files#r1398527134) |
||
|
|
d23898e63a |
engine: Adds shutdown method to exchange manager and unload all exchanges when engine is stopped (#1112)
* engine: shutdown and unload exchange when engine is stopped * linter: fixes * engine/exchMan: add nil check * engine/exchanges: add shutdown method to exchanges, rm len check lock not needed, expanded code coverage, address some nits * exchMan: report all failed shutdowns across exchanges, implement timer and monitoring routines. * exchMan: improve shutdown sequence and aloc. * further improvement * exchman: log from warn to error * websockconnection: Suppress error return when closure is caused by library * linter: fix * fix racies * add note on why not parallel tests * glorious: nits * spelling kween * thrasher: nits * engine: change print of setting using reflection, I keep forgetting to implement this so program around forgetfulness * engine/exchange_management: remove wait group and just rely on intermediary lock * glorious: nits * Update common/common.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update main.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> --------- Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io> Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> |
||
|
|
68db4155bf |
alert: Add optimizations (#939)
* alert: Add optimizations * alert: add basic benchmarks * alert: fix linter issue * documentation: change to text/template as html/template escapes to protect against code injection. Add readme.md for alert. * README: Add package name * alert: link up with engine settings * request: isVerbose refactor * Update exchanges/alert/alert_test.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 * glorious: fun police * documentation: regen Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io> Co-authored-by: Scott <gloriousCode@users.noreply.github.com> |
||
|
|
f929b4d51e |
backtester: Futures handling & FTX Cash and Carry example strategy (#930)
* 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 * Adds some conceptual futures order details to track PNL * Initial design of future order processing in the backtester * Introduces futures concept for collateral and spot/futures config diffs * Fixes most tests * Simple designs for collateral funding pair concept * Expands interface use so much it hurts * Implements more collateral interfaces * Adds liquidation, adds strategy, struggles with Binance * Attempts at getting FTX to work * Adds calculatePNL as a wrapper function and adds an `IsFutures` asset check * Successfully loads backtester with collateral currency * Fails to really get much going for supporting futures * Merges master changes * Fleshes out how FTX processes collateral * Further FTX collateral workings * hooks up more ftx collateral and pnl calculations * more funcs to flesh out handling * Adds more links, just can't fit the pieces together :( * Greatly expands futures order processing * Fleshes out position tracker to also handle asset and exchange +testing * RM linkedOrderID. rn positioncontroller, unexport * Successfully tracks futures order positions * Fails to calculate PNL * Calculates pnl from orders accurately with exception to flipping orders * Calculates PNL from orders * Adds another controller layer to make it ez from orderstore * Backtester now compiles. Adds test coverage * labels things add scaling collateral test * Calculates pnl in line with fees * Mostly accurate PNL, with exception to appending with diff prices * Adds locks, adds rpc function * grpc implementations * Gracefully handles rpc function * beautiful tests! * rejiggles tests to polish * Finishes FTX testing, adds comments * Exposes collateral calculations to rpc * Adds commands and testing for rpcserver.go functions * Increase testing and fix up backtester code * Returns cool changes to original branch * end of day fixes * Fixing some tests * Fixing tests 🎉 * Fixes all the tests * Splits the backtester setup and running into different files * Merge, minor fixes * Messing with some strategy updates * Failed understanding at collateral usage * Begins the creation of cash and carry strategy * Adds underlying pair, adds filldependentevent for futures * Completes fill prerequsite event implementation. Can't short though * Some bug fixes * investigating funds * CAN NOW CREATE A SHORT ORDER * Minor change in short size * Fixes for unrealised PNL & collateral rendering * Fixes lint and tests * Adds some verbosity * Updates to pnl calc * Tracks pnl for short orders, minor update to strategy * Close and open event based on conditions * Adds pnl data for currency statistics * Working through PNL calculation automatically. Now panics * Adds tracking, is blocked from design * Work to flesh out closing a position * vain attempts at tracking zeroing out bugs * woww, super fun new subloggers 🎉 * Begins attempt at automatically handling contracts and collateral based on direction * Merge master + fixes * Investigating issues with pnl and holdings * Minor pnl fixes * Fixes future position sizing, needs contract sizing * Can render pnl results, focussing on funding statistics * tracking candles for futures, but why not btc * Improves funding statistics * Colours and stats * Fixes collateral and snapshot bugs * Completes test * Fixes totals bug * Fix double buy, expand stats, fixes usd totals, introduce interface * Begins report formatting and calculations * Appends pnl to receiving curr. Fixes map[time]. accurate USD * Improves report output rendering * PNL stats in report. New tests for futures * Fixes existing tests before adding new coverage * Test coverage * Completes portfolio coverage * Increase coverage exchange, portfolio. fix size bug. NEW CHART * WHAT IS GOING ON WITH PNL * Fixes PNL calculation. Adds ability to skip om futures tracking * minor commit before merge * Adds basic liquidation to backtester * Changes liquidation to order based * Liquidationnnnnn * Further fleshes out liquidations * Completes liquidations in a honorable manner. Adds AppendReasonf * Beginnings of spot futures gap chart. Needs to link currencies to render difference * Removes fake liquidation. Adds cool new chart * Fixes somet tests,allows for zero fee value v nil distinction,New tests * Some annoying test fixes that took too long * portfolio coverage * holding coverage, privatisation funding * Testwork * boring tests * engine coverage * More backtesting coverage * Funding, strategy, report test coverage * Completes coverage of report package * Documentation, fixes some assumptions on asset errors * Changes before master merge * Lint and Tests * defaults to non-coloured rendering * Chart rendering * Fixes surprise non-local-lints * Niterinos to the extremeos * Fixes merge problems * The linter splintered across the glinting plinths * Many nits addressed. Now sells spot position on final candle * Adds forgotten coverage * Adds ability to size futures contracts to match spot positions. * fixes order sell sizing * Adds tests to sizing. Fixes charting issue * clint splintered the linters with flint * Improves stats, stat rendering * minifix * Fixes tests and fee bug * Merge fixeroos * Microfixes * Updates orderPNL on first Correctly utilises fees. Adds committed funds * New base funcs. New order summary * Fun test updates * Fix logo colouring * Fixes niteroonies * Fix report * BAD COMMIT * Fixes funding issues.Updates default fee rates.Combines cashcarry case * doc regen * Now returns err * Fixes sizing bug issue introduced in PR * Fixes fun fee/total US value bug * Fix chart bug. Show log charts with disclaimer * sellside fee * fixes fee and slippage view * Fixed slippage price issue * Fixes calculation and removes rendering * Fixes stats and some rendering * Merge fix * Fixes merge issues * go mod tidy, lint updates * New linter attempt * Version bump in appveyor and makefile * Regex filename, config fixes, template h2 fixes * Removes bad stats. * neatens config builder. Moves filename generator * Fixes issue where linter wants to fix my spelling * Fixes pointers and starts |
||
|
|
ee9c35d5ee |
grpc: add shutdown call for external management (#957)
* grpc: add shutdown call for external management * go mod: tidy * glorious: suggestion * Update engine/engine.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update engine/rpcserver.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update main.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update engine/rpcserver.go Co-authored-by: Scott <gloriousCode@users.noreply.github.com> Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io> Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> Co-authored-by: Scott <gloriousCode@users.noreply.github.com> |
||
|
|
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> |
||
|
|
adf7659e95 |
backtester: shared exchange level funding, decimal implementation (#783)
* Better designed backtester funding concept * Fleshes out funding concepts further to allow two funding types * Adds types, finishes adding to portfolio and adds to exchange * Fixes a bug to reveal another * Fixes issues with purchasing * A partial conversion to using decimal.decimal for the backtester * Further decimal rollout. Can compile and output report * More cleanup * Fix rendering and initial funds issue. * Adds new concept for trading using the exchange level funding to see what happens * Fixes a bug in funding not being found * New strat config to test RSI and discover issues * Can run with pairs that contain 0 funding * Finally fixes the arrangement to share funds * Adds testing and funding transfer * end of day * More comments, more tests! * Improves item comparisons and completes testing * Initial attempt at new strategy which utilisies shared funding and transfers * end of day broken * Chronological output. Fixes output bug where multi currency. * End of day commit * Fixes bug where events were being overwritten in a simultaneous context * Begins transitioning from portfolio holdings to funding holdings. Am I doing the right thing * End of day run around * Likely fix for holding calculations * Improvement to template. Improvement to holdings * DARK MODE. Report upgrades. Even handling with funds. Fix output * Output funding to cmd * Add new trasnferred funds "side" * Fixing test run 1 * Test updates * Test updating * More test fixing * Fixes portfolio tests * More test fixes * Fixes remaining tests and lints * Fixes currencystatistics tests. Adds decimal math implementations * Fixes hilarious bug where there could only be on holding * Adds funding support for config. Minor fixes * Adds documentation * Finishes config builder support for funding * Logs inexact conversions, updates tests. adds config validation * The quest to understand a new funding bug begins. New strategy * Fixes bug where wrong funding was retrieved. Expands t2b2 strat * End of the day commit. Gotta revert the nulldecimal stuff * Fixes tests, adds extra funding transfer feature * Fixes initial total values, tries to add a grand total value * Rebase fixes, documentation updates, tests for strategy * Swaps the err statement for tests. Regenerates tests. Math warnings * Attempts to solve Live data problems. Fixes volume * Fixes live data missing * can trade at any interval. skip volume sizing. volume colours. * config regen. display fixes * test fixes, lint fixes * Anti-funky errors * docs * Rmbad * docs * docs update * Simplifies err handling. Updates readmes. Data type checks * docs. new field initial-base-funds. comment errs. config test coverage * minMaxing * testfix * Fixes fee calculation, re-bans minMax being equal * Crazy concepts to attempt to solve totals. Addresses nits * Adds in totals calculation for exchange level funding.Uses external API In future, this will be replaced by proper pricing supplied by the same exchange that is requested. This is an unknown price * rm dollar signs in cmd and report. rm bad error. fix chart decimal. padding * re-run docs post merge * Fixes oopsie for fee parsing Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> |
||
|
|
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> |
||
|
|
197ef2df21 |
Feature: Data history manager engine subsystem (#693)
* Adds lovely initial concept for historical data doer
* Adds ability to save tasks. Adds config. Adds startStop to engine
* Has a database microservice without use of globals! Further infrastructure design. Adds readme
* Commentary to help design
* Adds migrations for database
* readme and adds database models
* Some modelling that doesn't work end of day
* Completes datahistoryjob sql.Begins datahistoryjobresult
* Adds datahistoryjob functions to retreive job results. Adapts subsystem
* Adds process for upserting jobs and job results to the database
* Broken end of day weird sqlboiler crap
* Fixes issue with SQL generation.
* RPC generation and addition of basic upsert command
* Renames types
* Adds rpc functions
* quick commit before context swithc. Exchanges aren't being populated
* Begin the tests!
* complete sql tests. stop failed jobs. CLI command creation
* Defines rpc commands
* Fleshes out RPC implementation
* Expands testing
* Expands testing, removes double remove
* Adds coverage of data history subsystem, expands errors and nil checks
* Minor logic improvement
* streamlines datahistory test setup
* End of day minor linting
* Lint, convert simplify, rpc expansion, type expansion, readme expansion
* Documentation update
* Renames for consistency
* Completes RPC server commands
* Fixes tests
* Speeds up testing by reducing unnecessary actions. Adds maxjobspercycle config
* Comments for everything
* Adds missing result string. checks interval supported. default start end cli
* Fixes ID problem. Improves binance trade fetch. job ranges are processed
* adds dbservice coverage. adds rpcserver coverage
* docs regen, uses dbcon interface, reverts binance, fixes races, toggle manager
* Speed up tests, remove bad global usage, fix uuid check
* Adds verbose. Updates docs. Fixes postgres
* Minor changes to logging and start stop
* Fixes postgres db tests, fixes postgres column typo
* Fixes old string typo,removes constraint,error parsing for nonreaders
* prevents dhm running when table doesn't exist. Adds prereq documentation
* Adds parallel, rmlines, err fix, comment fix, minor param fixes
* doc regen, common time range check and test updating
* Fixes job validation issues. Updates candle range checker.
* Ensures test cannot fail due to time.Now() shenanigans
* Fixes oopsie, adds documentation and a warn
* Fixes another time test, adjusts copy
* Drastically speeds up data history manager tests via function overrides
* Fixes summary bug and better logs
* Fixes local time test, fixes websocket tests
* removes defaults and comment,updates error messages,sets cli command args
* Fixes FTX trade processing
* Fixes issue where jobs got stuck if data wasn't returned but retrieval was successful
* Improves test speed. Simplifies trade verification SQL. Adds command help
* Fixes the oopsies
* Fixes use of query within transaction. Fixes trade err
* oopsie, not needed
* Adds missing data status. Properly ends job even when data is missing
* errors are more verbose and so have more words to describe them
* Doc regen for new status
* tiny test tinkering
* str := string("Removes .String()").String()
* Merge fixups
* Fixes a data race discovered during github actions
* Allows websocket test to pass consistently
* Fixes merge issue preventing datahistorymanager from starting via config
* Niterinos cmd defaults and explanations
* fixes default oopsie
* Fixes lack of nil protection
* Additional oopsie
* More detailed error for validating job exchange
|
||
|
|
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 |
||
|
|
6ff453c364 |
Currency: Add new forex provider exchangerate.host (#682)
* Add new forex provider ExchangeRateHost.io * Fix linter paramTypeComine * Add templates and README files * Convert all times to UTC * Fix cosmetic issue and address nits * Add support for fx exchangerate.host engine override * Address nit plus use remove plural |
||
|
|
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 |
||
|
|
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> |
||
|
|
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
|
||
|
|
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 |
||
|
|
56e535001c |
Implement Request Retry and Backoff (#491)
Refactoring the timeout retries into a more general 'retry policy' with support for retrying on HTTP 429 (Too Many Requests) and other responses with a `Retry-After` header The delay between requests is controlled by a combination of a 'backoff' (currently only a simple linear backoff), and honouring the `Retry-After` value (longest delay wins) This makes the 'rate limiter' an optional argument as well, removing the use of `nil` when one isn't supplied Signed-off-by: David Ackroyd <daveo.ackroyd@gmail.com> |
||
|
|
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 |
||
|
|
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
|
||
|
|
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 |
||
|
|
63191ce3ec |
Engine QA (#381)
* 1) Update Dockerfile/docker-compose.yml 2) Remove inline strings for buy/sell/test pairs 3) Remove dangerous order submission values 4) Fix consistency with audit_events (all other spec files use CamelCase) 5) Update web websocket endpoint 6) Fix main param set (and induce dryrun mode on specific command line params) * Engine QA Link up exchange syncer to cmd params, disarm market selling bombs and fix OKEX endpoints * Fix linter issue after merge * Engine QA changes Template updates Wrapper code cleanup Disarmed order bombs Documentation updates * Daily engine QA Bitstamp improvements Spelling mistakes Add Coinbene exchange to support list Protect API authenticated calls for Coinbene/LBank * Engine QA changes Fix exchange_wrapper_coverage tool Add SupportsAsset to exchange interface Fix inline string usage and add BCH withdrawal support * Engine QA Fix Bitstamp types Inform user of errors when parsing time accross the codebase Change time parsing warnings to errors (as they are) Update markdown docs [with linter fixes] * Engine QA changes 1) Add test for dryrunParamInteraction 2) Disarm OKCoin/OKEX bombs if someone accidently sets canManipulateRealOrders to true and runs all package tests 3) Actually check exchange setup errors for BTSE and Coinbene, plus address this in the wrapper template 4) Hardcode missing/non-retrievable contributors and bump the contributors 5) Convert numbers/strings to meaningful types in Bitstamp and OKEX 6) If WS is supported for the exchange wrapper template, preset authWebsocketSupport var * Fix the shadow people * Link the SyncContinuously paramerino * Also show SyncContinuously in engine.PrintSettings * Address nitterinos and use correct filepath for logs * Bitstamp: Extract ALL THE APM * Fix additional nitterinos * Fix time parsing error for Bittrex |
||
|
|
242b02c382 |
(Engine) Bugfix: Unlocking an unlocked mutex PANIC + Increase dispatcher job capacity via commandline (#371)
* Removes lock unlock timer and instead sets unlocks between getting a nonce and sending a payload. Increases dispatch channel buffer to deal with len(enabledCurrencies) > ~100 * Adds additional comments to help explain the situation * Fixes bug that could unlock mutex too early * Fixes LIES where Gemini gets a nonce and then proceeds to declare it doesn't get a nonce causing an unrecoverable lock * Fun new concept! The creation of a tested timed mutex. Unlocking an unlocked mutex cannot occur and response can be checked to verify whether the mutex was unlocked from timeout or command. * Adds new cmd parameter "dispatchjobbuffer" * Expands comments and renames benchmark. Makes `Timer` property private * Happy little linters * Renames jobBuffer and all related instances to jobs limit * Tiny error message update * Grammatical fix and setting dispatch.Start to use defaults |
||
|
|
596be31b6a |
dispatcher: Use int32 for atomic operations to prevent crash on ARM 32bit systems (#370)
See https://github.com/golang/go/issues/599 |
||
|
|
db317a2447 |
Engine: Dispatch service (#346)
* Added dispatch service * Added orderbook streaming capabilities * Assigned correct orderbook.base exchange name * Fixed Requested niterinos Add in cli orderbook QA tool to gctcli Add exchange orderbook streaming * Add ticker streaming support through dispatch package * Added in some more info on error returns for orderbook.go * fix linter issues * Fix some issues * Update * Fix requested * move dispatch out of exchanges folder to its own independant folder * Fix requested * change orderbook string to tickers * Limit orderbooks to 50 and made dispatch system more stateless in operation * lower cases for update/retrieve/sub exchange name * Adds in asset validation and lower case conversion on cli * Remove comment * Moved timer to a higher scope so its not constantly initialised just reset per instance and removed returning unused channel on error * Rm unused release function in dispatch.go Reset timer and bleed buffered timer chan if needed in dispatch.go Added in ticker.Stop() and timer.Stop() functions for worker routine return in dispatch.go Index aggregated bid and ask functions for orderbook.go Added in dummy slice for wsorderbook_test.go * Moved drain to above Reset so potential race would not occur in dispatch.go Fix various linter issues dispatch.go * Fix some issues * change to start/stop service, added in service state change via cli, updated logger * fix requested * Add worker amount init spawning * fix linter issues * Fix more linter issues * More fixes * Fix race issue on releasing pipe channel on a close after shutting down dispatcher system * Moved all types to dispatch_types.go && remove panic * Moved types into serperate file && improve test coverage * RM unnecessary select case for draining channel && fixed error string * Added orderbook_types file and improved code coverage * gofmt file * reinstated select cases on drain because I am silly * Remove error for drop worker * Added more test cases * not checking error issue fix * remove func causing race in test, this has required protection via an exported function * set Gemini websocket orderbook exchange name |
||
|
|
0c76789b0d |
Database interface & auditing feature (#332)
* added audit manager * Basic database DOA setup * Added base config file * added sqlite support and creation of schema * added basic tests and config entry * corrected issues of database is disabled * fixed path for test * WIP * Added tests fixed config checking * reverted files back to upstream * reverted go.mod files * no more test test test * removed local testing details for psql * hello * added comments * increased ping to 30 seconds * renamed database table and added additional condition around test * removed database test details * goimport ran on all files * WIP * first attempt at migration * fixes for migration system * Migration system logger interface implemented * fixes to print functions * added write pooling pass * gofmt :D * formatted imports correctly * removed old code * added creation of migration * gofmt * :D Hello * ❌ 🏎️ * maybe one day i will remember to revert go mod files * checked err return condition correctly * first changes for PR feedback * code clean up * protect Connected with RWmutex & event with mutex * : D * we can just pretend like it never happened * MOved migrations back to source directory and added README * readme formatting update * Addd command line override for datadir * use correct var when creating a migration and confirm folder is created * Check if database version is newer than latest migration and also you know make migrations work..... * uses filepath instead of manual path to use correct path seperator * Add connection message and lower timeout * Added support for sslmode for psql * no longer force Close of database instead allow driver to maage * Added closer func to test output * sslmode added to example config |
||
|
|
1daaa66830 |
Engine changes
Add addr helpers (will be split off into own package) Engine status updates (log and data dir display) Use GetPairFormat for various exchanges instead of calling the config QA fixes Implement GCTRPC exchange deposit address handling |
||
|
|
bd8dc47c38 | daily progress build | ||
|
|
f5914e8c10 | Engine changes |