Commit Graph

599 Commits

Author SHA1 Message Date
Yordan Miladinov
417b2a77ef exchanges/binance/coinm: fix order submission (#819)
* exchanges/binance: proper arguments order when calling Binance.FuturesNewOrder

* exchanges/binance: adapt FuturesOrderPlaceData (+ unmarshaling) to latest coin/delivery futures API

* exchanges/binance: introduce futuresNewOrderRequest and use it to pass order parameters for coin margined futures

* exchanges/binance: test json unmarshaling of FuturesOrderPlaceData

* exchanges/binance: reorder fields as per docs, include missing fields (also in tests)

* exchanges/binance/coinm: use constants instead of hard coded strings (also fixes linting)

* exchanges/binance/coinm: pass futuresNewOrderRequest by reference

* exchanges/binance/coinm: expose FuturesNewOrderRequest

* exchanges/binance/coinm: do not explicitly assign default values fields of FuturesNewOrderRequest

* exchanges/binance/coinm: document FuturesNewOrderRequest

* exchanges/binance/coinm: expose all fields of FuturesNewOrderRequest

* exchanges/binance/coinm: expose fields of FuturesNewOrderRequest

* exchange/binance/coin: order submission: add support for priceProtect

Co-authored-by: Yordan Miladinov <jordanmiladinov@gmail.bg>
2021-11-10 10:24:30 +11:00
Luis Rascão
ca428f5203 binance: allow exposure of trade feed through data channel (#823) 2021-11-08 12:17:01 +11:00
Scott
6eaa2e4073 Backtester: USD tracking (#818)
* Initial concept for creating price tracking pairs

* Completes coverage, even with a slow test

* I dont know what point to hook this stuff up

* Bit of a broken way of handling tracking pairs

* Correctly calculates USD rates against all currencies

* Removes dependency on GCT config

* Failed currency statistics redesign

* initial Update chart to use highcharts

* Minor changes to stats

* Creats funding stats to handle the stat calculations. Needs more work

* tracks USD snapshots and BREAKS THINGS FURTHER

* Fixed!

* Adds ratio calculations and such, but its WRONG. do it at totals level dummy

* End of day basic lint

* Remaining lints

* USD totals statistics

* Minor panic fixes

* Printing of funding stats, but its bad

* Properly calculates overall benchmark, moves funding stat output

* Adds some template charge, removes duplicate fields

* New charts!

* Darkcharts. funding protection when disabled

* Now works with usd tracking/funding disabled!

* Attempting to only show working stats based on settings.

* Spruces up the goose/reporting

* Completes report HTML rendering

* lint and test fixes

* funding statistics testing

* slightly more test coverage

* Test coverage

* Initial documentation

* Fixes tests

* Database testing and rendering improvements and breakages

* report and cmd rendering, linting. fix comma output. rm gct cfg

* PR mode 🎉 Path field, config builder support,testing,linting,docs

* minor calculation improvement

* Secret lint that did not show up locally

* Disable USD tracking for example configs

* ShazNitNoScope

* Forgotten errors

* ""

* literally Logarithmically logically renders the date 👀

* Fixes typos, fixes parallel test, fixes chart gui and exporting
2021-11-08 12:10:15 +11:00
Luis Rascão
4531fdcb4a exchanges/websocket: Expose Trades/Fills feed through data channel (#814)
* Expose trade feed websocket exchange data through data channel

Most relevant to applications that import GCT as a lib, this allows
them to (through configuration, disabled by default) receive trade data
through the data channel similarly to the orderbook feed.

* exchanges: allow exposure of trade websocket feed through data channel

* Expose fill feed websocket abstracted exchange data through data channel

* exchanges: allow exposure of fill websocket feed through data channel
2021-10-28 10:25:15 +11:00
khcchiu
8617b50ff6 Exchanges: enrich order history with avg executed price, cost, and more (#792)
* Exchanges: enrich order history with avg executed price, cost, and more

* Fix division by zero in order detail enrichment

* Remove DateCompleted from Bithumb OrderData and fix OrderDate parsing

* Fixes on order detail fields and rename EnrichOrderDetail to CalculateCostsAndAmounts

* BTSE order history populate name and id

* Calculate average executed price for market order or when order amount is zero

* Minor fixes on infer order amounts, costs, and times

* Attach InferAmountsCostsAndTimes to Order.Detail

* Binance: fix order status

* Always use order.StringToOrderStatus() and ensure order has at least one of executed/remaining amount set
2021-10-26 11:22:30 +11:00
Ryan O'Hara-Reid
099ffa1a60 stream/websocket: Consolidate fields by using exchange config pointer (#809)
* stream: add exchange config pointer to setup WebsocketSetup struct to reduce and consolidate setting of variables.

* config: reduce stutter

* config: reduce minor stutter

* glorious: nits addr.

* Update exchanges/stream/websocket.go

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

* websocket: implement fix

* engine/helpers: fix test

* exchanges: fix after merge issues

* exchange_template: fix output

Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
2021-10-20 15:45:06 +11:00
Luis Rascão
a70224d123 exchanges/websocket: Allow configuration of orderbook publish period (#805)
* Allow configuration of orderbook publish period

For some applications that import GCT it's more interesting to be
immediately notified of an exchange orderbook update instead of
only getting notified every 10 seconds. This option allows that
to happen while keeping the previous default.

* exchanges: allow configuration of orderbook update period
2021-10-20 11:44:24 +11:00
Luis Rascão
a4d792f0c5 Kraken: Various futures bug fixes (#806)
* Kraken futures: fix requests signature calculation

* Kraken futures: fix error return of SendOrder

* Kraken futures: fix order id json field name

* Kraken Futures: ensure uppercase instrument names

* Kraken Futures: add support for immediate or cancel type orders
2021-10-20 11:34:33 +11:00
Ryan O'Hara-Reid
8fe4d73e89 kraken: Add check for correct order type in batch requests (#810)
* kraken: add check for correct order type in batch requests

* huboi: fix tests
2021-10-19 11:37:07 +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
Luis Rascão
0a91af0f2e bitmex: normalize account info currencies (#799)
* bitmex: normalize account info currencies

Bitmex has an interesting way of returning BTC balances, it returns them
as XBt and denominated in Satoshis instead. Normalize that still in the
bitmex wrapper by performing the conversion and returning the normal use
BTC currency.

* Change NW contract to NQ

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>
2021-10-13 11:05:16 +11:00
Ryan O'Hara-Reid
a5a960e9df FTX: Add FutureData / FillsData missing fields (#803)
* FTX: Add missing fields for FutureData type NOTE: Use f.GetFutures(context.Background()) to test.

* ftx: Add missing field for FillsData

* ftx: Add UnderlyingDescription field to Futures Data type
2021-10-12 11:37:02 +11:00
khcchiu
444307a990 binance: order history use request pair (#802) 2021-10-12 11:29:42 +11:00
Luis Rascão
334b3bf0cc ftx: fix websocket authentication of subaccounts (#801) 2021-10-11 11:39:09 +11:00
Luis Rascão
5208d2191e Huobi: symbol, var assignment and UpdateAccountInfo fixes (#793)
* huobi futures: GetSwapAccountInfo argument is optional

* huobi futures: fetch main account data as well

* huobi futures: shut linter up

Old warnings not introduced in this scope.
2021-10-07 14:43:06 +11:00
Yordan Miladinov
fe4221def0 exchanges/ftx: test ws -> ticker.Price conversion (#797)
* exchanges/ftx: add TestFTX_wsHandleData_Price

* exchange/ftx/test: proper types in casting errors
2021-10-07 14:38:40 +11:00
Luis Rascão
4caa1125bc gocritic: linter silence (#796) 2021-10-07 14:37:55 +11:00
Yordan Miladinov
4f0d5d175c exchanges/ftx: populate best bid/ask sizes when handling ticker ws events (#795) 2021-10-06 12:13:16 +11:00
Luis Rascão
01dea7e219 kraken futures: fix account info currency pairs (#791) 2021-10-01 14:24:02 +10:00
khcchiu
8b2c94f70e CoinbasePro: GetOrderHistory pair handling improvements (#789)
* Remove settled from Coinbase Pro order history status

* Get Coinbase Pro order history without restricting currency pair and include price

* Add empty and nil pairs scenario for TestGetOrderHistory

* Include fee and fee asset in Coinbase Pro history order
2021-09-30 15:33:56 +10:00
khcchiu
a959b6cce6 CoinbasePro: Remove settled from order history status (#788) 2021-09-29 14:16:40 +10:00
Scott
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>
2021-09-27 16:01:23 +10: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
Luis Rascão
1d7c656665 huobi: don't overwrite account balances when request spot asset (#785) 2021-09-21 14:01:22 +10:00
TaltaM
fd600972ba engine/order manager: Initial REST managed order updating (resolves #772) (#775)
* Initial REST managed order updating

* Apply gloriousCode's changes.go patch

* Update internal order ID handling

* Check error

* Replace string with string pointer

* Avoid nil pointers in upsert

* Update test for UpdateOrderFromDetail()

* Add tests for orders.go

* Remove unnecessary newline

* Address comments

* Add missing nil check

* Add tests for new functions in order_manager.go

* Remove empty line

* Change log level for updates from Info to Debug (keep added orders at Info)

* Initialize orders before running the timer

* [TEMP] Add verbosity for debugging

* Nil checking on exchangeManager in GetExchanges()

- exchangeManager.GetExchanges() and iExchangeManager.GetExchanges() return an error on nil
- bot.GetExchanges() wraps exchangeManager.GetExchanges() and returns an empty slice

* Revert b5afe1a46b

* Do not start the order manager runner thread

Instead, mark the order manager as running

* Remove redundant error.Is() and remove print wrapper on msg

* Add atomic blocker and waitgroup on processOrders()

* Disable unnecessary orderManager runner thread for rpcserver_test

* Remove redundant err from orderStore.getActiveOrders()

* [FIX] Populate requiresProcessing using UpsertResponse data instead of REST return data

.. because the data returned by the REST calls do not include the internal user ID's

* [TEST] Verify that processOrders() actually processes queried order data

* Remove leftover warning and add nil check on wg.Done()

* Apply suggestions from code review

Log category changes - as suggested

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

* Return when no exchanges available

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>
2021-09-15 09:28:31 +10:00
Luis Rascão
068b375867 ftx: honour subaccount setting when fetching balances (#780)
FTX won't allow us to fetch balances for all accounts when
using a subaccount API key.
2021-09-14 11:10:31 +10:00
Ryan O'Hara-Reid
7ab861fe4d kraken: fix GetTrades test (#782) 2021-09-13 09:29:14 +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
Yordan Miladinov
9e745d20a3 Account: Add account.Balance.Available() method (#777)
* add account.Balance.Available() method that returns the amount of an asset not locked/held

* account: comment Balance.Available()

* account: test Balance.Available()
2021-09-09 09:35:10 +10:00
Ryan O'Hara-Reid
66fbd43cf0 websocket: fix deadlock when enabling/disabling via gctrpc (#754)
* websocket: select case error if no receiver, add in functionality to reset to initial sync for books on a new websocket connection

* websocket: fix tests

* websocket: log error instead of losing it

* websocket: fix whoopsie

* exchanges: fix test

* websocket: force requirement of specific functionality

* exchanges: fix tests

* exchanges/websocket: move waitgroup add before scheduling across exchanges

* gateio: add feature subscribe

* bithumb/bittrex: include connection state reset, fix reconnection bug for Bithumb

* huobi: Add listen to shutdown to routine so it actually returns and stops being a naughty boy.

* huobi: add missing waitgroup add.

* exchanges: bleed comms channels

* binance: fix reconnection bug with buffer

* bithumb: fix reconnection bug with ws orderbook when websocket is diabled/enabled

* bithumb/bittrex: add bleeders for ws orderbook jobs

* linter: fix

* kraken: reduce code block from double assertion

* This bug ruined my day.

* glorious: error checking

* zb: add correct path for websocket connection

* exchange: Add verbosity when config conflicts and overwrites default values

* zb: add https to path

* exchanges: glorious nits

* stream: Add checkAndSetMonitoring to reduce potential routine bundling, increase timeout and check state in tests

* stream: remove check that is not needed.

* glorious: nits addr.

* lint: test
2021-09-03 17:21:23 +10:00
Scott
a1a667bab9 FTX: allow authenticated tests to run 2021-08-31 10:44:48 +10:00
Ryan O'Hara-Reid
4d1994afb6 bithumb: Add missing functionality (#770)
* bithumb: Add missing functionality

* glorious: nits
2021-08-31 09:57:04 +10:00
phieudu241
1e79384b25 Binance: Fix UKlineData func (#768) 2021-08-30 14:29:55 +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
Luis Rascão
c9ab0b1164 exchanges: Add UpdateTickers method and reserve UpdateTicker for single ticker symbol update requests (if supported) (#764)
* exchanges: add an UpdateTickers method to the main exchange interface

This method will fetch all currency pair tickers of a given asset type
and update them internally, does nothing for now.

* exchanges: refactor UpdateTicker on all exchanges

Keep the exact previous behaviour but implement the UpdateTickers
method and refactor UpdateTicker by using it where applicable.

* sync_manager: update all tickers when batching is enabled

* binance: UpdateTicker to fetch single ticker symbol

* ftx: UpdateTicker to fetch single ticker symbol
2021-08-27 12:31:34 +10:00
Adrian Gallagher
056a809d93 Bitstamp: Fix currency pair handling (#762)
* Fix Bitstamp pair handling

* Fix spelling

* Populate namerinos

* Address nitterinos

* Revert trade currency code, introduces races between engine / this and rely on OB test instead

* One liner
2021-08-26 11:40:14 +10:00
Yordan Miladinov
a15cbf6651 docs: Establish a standard for trade/order-update websocket events (#755)
* docs: initially commit WS_TRADE_UPDATES.md

* docs/WS_TRADE_UPDATES: shorter text

* docs: rename WS_TRADE_UPDATES to WS_ORDER_EVENTS as that is more descriptive of what it documents

* docs/ADD_NEW_EXCHANGE: reference the newly added WS_ORDER_EVENTS file

* WS_ORDER_EVENTS: common terminology

* WS_ORDER_EVENTS: turn the code segment into a markdown table

* WS_ORDER_EVENTS: AverageExecutedPrice is now not mandatory

* exchanges/README: link to WS_ORDER_EVENTS
2021-08-23 09:48:16 +10:00
Yordan Miladinov
3467914ab7 Binance/FTX: spot websocket fixes (#753)
* exchange/binance/websocket:

1. resolve order type by reading the dedicated executionReport field (X)

2. populate average price (computed as advised in docs: Z/z)

3. fee taken is now assigned to order.Detail.Fee (not to order.Detail.Cost)

4. proper order.Detail.Cost and order.Detail.CostAsset

* order.Detail: add a new field: FeeAsset

* exchange/binance/websocket: wsOrderUpdate: assign FeeAsset

* exchange/binance/websocket: wsOrderUpdate: use TransactionTime instead of EventTime (more precise) and populate order.Detail.TargetAmount

* exchange/binance/websocket: wsOrderUpdate: use full name for variables (isn't obvious otherwise), do not mix var and :=, order temporary variable by their order in order.Detail

* exchange/binance/websocket: order fields of WsOrderUpdateData by the documented/received-over-the-websocket order of fields

* exchange/binance/websocket: add explicitly "M" as WsOrderUpdateData.Ignored2, which would otherwise override small "m"

* exchange/binance/websocket: check for zero when computing averagePrice

* exchange/binance/test: update TestExecutionTypeToOrderStatus and TestWsOrderExecutionReport

* exchange/binance/websocket: wsOrderUpdate now reports cost thus far, not the total order cost as that cannot be predicted in the case of partially filled orders

* exchange/ftx/websocket: WsOrderDataStore now reports cost thus far, not the total order cost as that cannot be predicted in the case of partially filled orders

* exchange/binance/websocket: executionReport now does not set TargetAmount as it is not applicable

* exchanges: binance/websocket and ftx/websocket now properly set Date and LastUpdated time fields when reporting a trade

* exchange/binance/websocket: check if WsOrderUpdateData.CommissionAsset is populated when assigning feeAsset

* exchange/binance/test: fix TestWsOrderExecutionReport
2021-08-18 18:31:03 +10:00
TaltaM
4ba2c710b5 Bittrex: Enable ws orderbook sync recovery (resolves #746) (#747)
* [FIX] Enable ws orderbook sync recovery by:

- Testing if books have been cleared
- Assigning options when loading snapshot

* orderbooks: remove setlastupdate method and on select depth method that updates linked list, this reduced lock contention across code base and fixes buffer bug on applying buffered updates

* WS - Introduce signaling for the need to fetch the orderbook

* Address nits

* Update error messages to include exchange name

Co-authored-by: shazbert <oharareid.ryan@gmail.com>
2021-08-18 11:43:46 +10:00
Rocky Yang
c38757a689 Binance websocket: Order Detail Execution Report (#750)
* * Binance websocket: set commission of order Detail

* * Binance websocket: set commissionAsset of order.Detail

* * Binance websocket: change CostAsset to type currency.Code

* * Binance websocket: call NewCode after checking CommissionAsset is not empty. This guarantees that NULL CommissionAsset is mapped to an empty order.Detail.CostAsset. Otherwise, reflect.DeepEqual will fail on test. Update TestWsOrderExecutionReport json message to BTC commission.

* * Binance websocket: binance websocket "ExecutionReport" only provides "trade" status (partially filled), so check that executed amount == total amount before change status to filled
2021-08-17 14:33:54 +10:00
Luis Rascão
96669e29cf engine/exchange manager: Add support for custom exchanges (#749)
* engine: Setup exchange manager earlier

So it's available for applications before starting.

* engine: Add a custom exchange builder interface

Allows applications that import GCT as a lib to build new
custom exchanges without further modifications.
2021-08-17 14:03:05 +10:00
Ryan O'Hara-Reid
736c92a99b bithumb: Add websocket support (#745)
* bithumb: Add websocket support (WIP)

* bithumb: cont impl.

* bithumb: finish, issues with orderbook needs review

* linter issues

* bithumb: move to separate file

* bithumb: change to pointer for book

* bithumb: Add tests

* bithumb: Address nits

* websocket: Export subscription error and wrap returns

* bithumb: cleanup/ fix tests

* gctrpc/bithumb: fix misspelling

* bithumb: gofmt

* readme: update support table, regen doc

* tradesReadme: update

* readme: update template
2021-08-16 16:53:23 +10:00
Scott
126187b31b Bugfix: Syncer & websocket circular dependency (#743)
* Fixes cyclical dependency

* why not lint

* Addresses potential wait if websocket subsystem is disabled
2021-08-11 17:06:01 +10:00
Yordan Miladinov
c7c8cac21f exchanges/ftx: Order improvements: submission + websocket reports (#741)
* exchanges/ftx: add support for ReduceOnly, ImmediateOrCancel and PostOnly orders

* exchanges/ftx: adapt tests to ReduceOnly/ImmediateOrCancel/PostOnly boolean flags

* exchanges/ftx: wrong json key of WsFillsDataStore.FillsData was causing json.Unmarshal() to yield an empty struct

* exchanges/ftx: update WsFills to latest API

* exchanges/ftx: add TestFTX_wsHandleData_wsFills

* exchanges/ftx: WsOrders.FilledSize was never parsed properly because of a key error (was spelled `filedSize` -- with one L);  enrich data structure to support latest API fields

* exchanges/ftx: when order is closed, set status to closed, not canceled

* exchanges/ftx: compatibleOrderVars: compare floats for almost-equality

* order.Detail: add field: AverageExecutedPrice float64

* exchanges/ftx: FTX.wsHandleData() now populates all order.Detail fields properly on update/orders websocket message

* exchanges/ftx: implement TestFTX_wsHandleData_Details()

* exchanges/ftx: make golangci-lint happy

* exchanges/ftx: make golangci-lint happy

* exchanges/ftx/test: delete redundant commented code

* exchanges/ftx: move websocket tests from ftx_test.go to ftx_websocket_test.go

* exchanges/ftx: remove redundant line

* exchange/ftx: greatly simplify TestFTX_wsHandleData (thanks to @shazbert)

* exchanges/ftx: make golangci-lint/whitespace happy

* exchanges/ftx: requested review change: delete a redundant line

* exchanges/ftx/test: use predefined currency constants
2021-08-11 10:28:47 +10:00
Ryan O'Hara-Reid
232d6ebc1f rate limit: make context aware (#731)
* rate limits: Make context aware

* binance: rate limit allow for cancellation of reservation when deadline is exceeded

* request: add context.done() before initiating any bulk work.

* binance: update error return for rate limiting

* request: updated dealine check to remove after time.Now procedure as this will obfuscate a deadline which will be limited by the context check on every attempt, so no need to sleep with delay.
2021-08-10 12:08:27 +10:00
Ryan O'Hara-Reid
279b53827f requester: defer execution of request.Item generation in closure (#723)
* requester: defer execution of request.Item generation in closure.

* bithumb: fix issue

* coinut/itbit: fix linter issues

* binance: fix bug on recvWindow setting

* requester: standardize sendpayload + add readme update

* nonce: remove inc() function

* request: defer unlockiflocked

* binance: revert changes for open orders

* btcmarkets: defer auth generation functionality, rm context deadline as this will be created just before sending HTTP request.

* binance: move const to top

* exmo: remove debug output as its generated in the requester function

* ftx: defer auth functionality

* requester: move error to top

* bittrex: defer auth functionality

* bitmex: defer auth functionality and remove deadline as generation occurs after rate limiting.

* btse: defer auth functionality

* coinbasepro: defer auth functionality and removed context deadline as this is generated after rate limiting

* coinbene: defer auth functionality and remove context deadline as this is generated after rate limiting

* huobi: defer auth functionality and remove context deadline as this is generated after rate limiting

* huobi-futures: defer auth functionality and remove context deadline as this is generated after rate limiting

* kraken: defer auth functionality and remove context deadline as this is generated after rate limiting

* kraken: remove deadline protection for timestamp generation

* okgroup: defer auth functionality and remove context deadline as this is generated after rate limiting

* poloniex: defer auth functionality

* zb: defer auth functionality and remove context deadline as this is generated after rate limiting

* exchanges: clean up log output which are done and inspected in the requester package

* binance: fix path bug on every retry, rm timeout context as this is not needed

* coinbene: fix path bug on retry

* binance: consolidate functionality

* coinbene: fix linter issues

* poloniex: linter fix

* kraken: change add -> set

* bitstamp: fix path bug for retry

* BTSE: fix retry path bug

* coinbene: fix path bug whoopsie by me

* gateio: fix bug where on retry it does not reset reader

* localbitcoins: fix path bug on retry

* zb: change domain to land

* exchanges: make sure io.Reader is generated every request

* exchanges: move reader generation into function scope

* wrapper_issues: setup exchange manager

* engine: expand withdraw manager test

* engine: dont look for environment

* bitstamp: fix pathing bug (@thrasher-)

* engine/withdraw_manager: purge tests as this is covered in repository withdraw
2021-08-06 17:24:38 +10:00
Yordan Miladinov
2da239735f gctrpc/order manager: Add ModifyOrder endpoint (#724)
* gctcli: modifyorder stubs

* gctcli: add ModifyOrderRequest and ModifyOrderResponse in rpc.proto

* gctcli: regenerate rpc.pb.go after the addition of ModifyOrder structs

* gctrpc: add ModifyOrder() and regenerate dependent files

* gctcli: modifyorder command now uses newly generated ModifyOrder() RPC

* exchanges/order/orders.go: use time.Time.Equal() instead of ==

* gctrpc: update ModifyOrderRequest and ModifyResponse and regenerate gRPC

* gctcli/commands: rework modifyorder

* engine: implement RPCServer.ModifyOrder

* engine: commit an initial version OrderManager.Modify(), still does not update state of managed orders

* engine: OrderManager.Modify now updates the inner state of managed orders, but introduces race conditions, needs fixes

* engine/order_manager.go: comply with golangci-lint

* gctcli: fix getOrderCommand.ArgsUsage

* gctcli: fix getModifyOrderCommand args and ArgsUsage

* engine: OrderManager.Modify() now correctly updates price of modified order

* engine: RPCServer.ModifyOrder now uses checkParams() as advised

* exchanges: (1) IBotExchange.ModifyOrder now returns a Modify struct, (2) all exchanges are updated to comply with that change

* exchanges/order: Detail.UpdateOrderFromModify also updates the ID

* engine/order_manager: add store.modifyExisting() and use it in OrderManager.Modify to update (on success) the state of the modified order

* exchanges: Bitfinex.ModifyOrder() now returns the ID in case of an error

* engine: OrdetManager.Modify() now emits an order event

* exchanges/bithumb: proper order.payment_currency key

* engine/order_manager: populate more Modify fields as they are needed by (some) exchanges, add comments

* engine: test OrderManager.Modify()

* engine: test store.modifyExisting()

* engine: write a docstring for store.modifyExisting

* engine: OrderManager.Modify() now also sets Modify.Price and Modify.Amount in case of zero values

* engine: TestOrderManager_Modify() now verify the effects of price and/or amount set to 0

* engine: OrderManger.Modify() now uses the commsManager to let observers know of errors

* engine: TestOrderManager_Modify() uses t.Fatal()

* engine: TestOrderManager_Modify() and TestStore_modifyOrder() supply t.Error() with proper messages

* exchanges/order_manager_test: fix a golangci-lint complaint

* engine/order_manager: fix an error comparison bug and simplify

* gctcli/commands: check if either price or amount is set, otherwise we would waste an API call
2021-08-06 10:09:14 +10:00
Scott
547d123984 Fixes holding amounts got btse and gemini (#738) 2021-08-05 12:02:00 +10:00
Yordan Miladinov
d638f0b9fb exchanges/binance: Binance.UpdateAccountInfo() now correctly assigns Balance.Hold for spot (#736) 2021-08-05 12:01:14 +10:00