Compare commits

...

75 Commits

Author SHA1 Message Date
bailantaotao
b2eebb9fbe
Merge 5e3b0238d8 into 37106c35b7 2024-09-18 22:46:40 +08:00
c9s
37106c35b7
Merge pull request #1748 from c9s/c9s/add-pos-index
Some checks failed
Go / build (1.21, 6.2) (push) Has been cancelled
golang-lint / lint (push) Has been cancelled
IMPROVE: [db] add index on positions table
2024-09-18 17:06:34 +08:00
c9s
8265ada5a0
compile and update migration package 2024-09-18 13:30:56 +08:00
c9s
744ca57c71
migrations: add index on positions table 2024-09-18 13:30:20 +08:00
c9s
17d3097e06
add v1.60.3 release note
Some checks failed
Go / build (1.21, 6.2) (push) Has been cancelled
golang-lint / lint (push) Has been cancelled
2024-09-16 00:31:00 +08:00
c9s
a0c41f89f2
bump version to v1.60.3 2024-09-16 00:31:00 +08:00
c9s
35a6639530
update command doc files 2024-09-16 00:30:59 +08:00
c9s
26b1fd2ae7
xmaker: fix price initialization 2024-09-16 00:29:37 +08:00
c9s
80430fec46
Merge pull request #1744 from lanphan/activeorder
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
2024-09-14 23:19:10 +08:00
Lan Phan
1f8b2b3710 call b.EmitNew() when new order is added into activeorderbook 2024-09-14 18:26:36 +07:00
c9s
25a2203000
add v1.60.2 release note
Some checks failed
Go / build (1.21, 6.2) (push) Has been cancelled
golang-lint / lint (push) Has been cancelled
2024-09-12 17:51:57 +08:00
c9s
aca2c32442
bump version to v1.60.2 2024-09-12 17:51:57 +08:00
c9s
df915d6ee8
update command doc files 2024-09-12 17:51:57 +08:00
c9s
0d6b7b29d5
Merge pull request #1742 from c9s/c9s/fix-ws-close-err
FIX: types/stream: change errorf to warnf
2024-09-12 17:46:24 +08:00
c9s
2784ef4687
Merge pull request #1741 from c9s/c9s/upgrade-requestgen
FIX: upgrade github.com/c9s/requestgen to 1.4.3
2024-09-12 17:37:55 +08:00
c9s
ea8f3a5485
types/stream: change errorf to warnf 2024-09-12 17:35:13 +08:00
c9s
52f32e0ad0
upgrade github.com/c9s/requestgen to 1.4.3 2024-09-12 17:27:30 +08:00
c9s
50cdf617f2
Merge pull request #1740 from c9s/c9s/upgrade-requestgen
FIX: upgrade requestgen and re-generate max cancel order request files
2024-09-12 12:31:08 +08:00
c9s
de0d11b511
max: regenerate order cancel requests 2024-09-11 16:47:20 +08:00
c9s
789bb1e53e
upgrade github.com/c9s/requestgen to 1.4.2 2024-09-11 16:38:35 +08:00
kbearXD
a9b71adce9
Merge pull request #1739 from c9s/kbearXD/dca2/set-exchange-fee-rate
Some checks failed
Go / build (1.21, 6.2) (push) Has been cancelled
golang-lint / lint (push) Has been cancelled
FEATURE: [dca2] set exchange fee rate for round position
2024-09-11 16:15:13 +08:00
kbearXD
f83491af26 FEATURE: [dca2] set exchange fee rate for round position 2024-09-11 15:40:59 +08:00
bailantaotao
82d07a0098
Merge pull request #1738 from c9s/edwin/okx/add-polusdt
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
FEATURE: [okx] update symbols to latest
2024-09-10 17:23:42 +08:00
edwin
619cce53f6 pkg/exchange: update to latest 2024-09-10 17:11:58 +08:00
c9s
643ecde2e9
Merge pull request #1726 from c9s/dependabot/github_actions/morphy2k/revive-action-2.5.10
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
dep: bump morphy2k/revive-action from 2.5.9 to 2.5.10
2024-09-10 10:28:58 +08:00
c9s
d7ddc9c462
Merge pull request #1737 from c9s/c9s/xmaker/ioc-arb
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
FEATURE: [xmaker] implement tryArbitrage
2024-09-09 22:57:20 +08:00
c9s
bd19b63c7b
go: update sum file 2024-09-09 22:23:25 +08:00
c9s
83ed9b0811
go: upgrade go sqlite 2024-09-09 22:23:02 +08:00
c9s
34ef50d889
xmaker: refactor and clean up tryArbitrage 2024-09-09 22:03:06 +08:00
c9s
52925c5643
xmaker: calculate balance for arbitrage 2024-09-09 18:12:46 +08:00
c9s
b4f2748892
xmaker: fix sides 2024-09-09 18:03:03 +08:00
c9s
ceda1e06b9
xmaker: implement tryArbitrage 2024-09-09 17:49:53 +08:00
c9s
bc1715f8ad
Merge pull request #1736 from c9s/kbearXD/session/remove-log
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
MINOR: [session] remove environment nil validation log
2024-09-09 16:17:17 +08:00
c9s
f361b19564
Merge pull request #1734 from c9s/c9s/xmaker/ioc-arb
REFACTOR: [xmaker] refactor for supporting ioc arb [part1]
2024-09-09 16:05:11 +08:00
kbearXD
f44486447e MINOR: [session] remove environment nil validation log 2024-09-09 16:04:04 +08:00
kbearXD
a2eca66af5
Merge pull request #1735 from c9s/kbearXD/dca2/fix-memory-leak
FIX: configure environment
2024-09-09 15:50:24 +08:00
kbearXD
129e2c438e FIX: add debug log 2024-09-09 15:13:02 +08:00
c9s
90749f4873
xmaker: pull out s.UseDepthPrice dependency 2024-09-09 15:04:56 +08:00
c9s
77dfe213e5
xmaker: pull out getLayerPrice and add test against the method 2024-09-09 14:41:41 +08:00
c9s
960ea89d8c
testhelper: add more test helpers 2024-09-09 14:41:27 +08:00
c9s
f24a96c8c3
xmaker: refactor getInitialLayerQuantity for quantity multiplier 2024-09-07 14:19:07 +08:00
c9s
6ad16b7488
xmaker: add EnableArbitrage option and makerBook 2024-09-07 13:47:34 +08:00
c9s
e14f09a914
xmaker: add sourceDepthLevel option 2024-09-06 21:47:43 +08:00
c9s
3cc96ff6ad
Merge pull request #1724 from dropbigfish/main
Some checks failed
Go / build (1.21, 6.2) (push) Has been cancelled
golang-lint / lint (push) Has been cancelled
fix: fix slice init length
2024-09-06 18:06:21 +08:00
c9s
6ea996bec4
Merge pull request #1733 from c9s/c9s/fix-initialize-defaults-steps
FIX: [bbgo] fix the defaults / initialize steps
2024-09-06 17:54:13 +08:00
c9s
ef935f8ca0
Merge pull request #1732 from lanphan/telegram_doc
fix env name
2024-09-06 17:40:26 +08:00
c9s
a282654c02
bbgo: fix the defaults / initialize steps 2024-09-06 17:33:31 +08:00
Lan Phan
336dd7a108 fix env name 2024-09-05 22:51:43 +07:00
kbearXD
f2a443a499
Merge pull request #1728 from c9s/kbearXD/dca2/fix-memory-leak
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
FIX: [core] fix memory leak
2024-09-05 17:52:41 +08:00
kbearXD
63a58e1b12 FIX: fix memory leak 2024-09-05 17:05:58 +08:00
c9s
1b40118bba
Merge pull request #1731 from longhutianjie/main
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
bug: fix json tag
2024-09-05 13:57:31 +08:00
longhutianjie
c75a685cc0
bug: fix json tag 2024-09-04 17:58:27 +08:00
c9s
50262f2a84
Merge pull request #1730 from c9s/c9s/xmaker/market-trade-signal
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
FEATURE: [xmaker] add market trade signal
2024-09-04 16:27:42 +08:00
c9s
9fc3a1b44a
xmaker: rename to aggTradeVolume 2024-09-04 16:09:58 +08:00
c9s
656112de45
xmaker: call signalConfig.TradeVolumeWindowSignal.Bind 2024-09-04 16:07:28 +08:00
c9s
ba73eeaad1
xmaker: add TradeVolumeWindowSignal 2024-09-04 15:59:21 +08:00
c9s
2527c0c7b7
max: convert v3 DepositStateFailed into rejected 2024-09-04 15:00:37 +08:00
c9s
a2f8fe5f72
max: add v3 DepositStateFailed state 2024-09-04 14:59:58 +08:00
c9s
ed51eff242
max: drop unused function 2024-09-04 14:59:10 +08:00
c9s
f6865f664c
add v1.60.1 release note
Some checks are pending
Go / build (1.21, 6.2) (push) Waiting to run
golang-lint / lint (push) Waiting to run
2024-09-04 14:58:07 +08:00
c9s
24de49860f
bump version to v1.60.1 2024-09-04 14:58:07 +08:00
c9s
83dc981c92
update command doc files 2024-09-04 14:58:07 +08:00
c9s
ec68e3c5f6
Merge pull request #1727 from lanphan/ioc
FIX: update timeInForce for binance margin order
2024-09-04 14:38:40 +08:00
c9s
699164484b
Merge pull request #1729 from c9s/c9s/max/fix-v3-deposit-state-conversion
FIX: [max] fix v3 deposit state conversion
2024-09-04 11:41:22 +08:00
c9s
f27afac77b
max: use error log instead of warning log for convertion 2024-09-04 11:20:30 +08:00
c9s
d404b20bd1
deposit2transfer: fix comments 2024-09-04 11:19:43 +08:00
c9s
1b8d7bd805
max: fix v3 deposit state conversion 2024-09-04 11:17:56 +08:00
Lan Phan
ba913ce4de update timeInForce for binance margin order 2024-09-03 00:38:17 +07:00
dependabot[bot]
01f8b78008
dep: bump morphy2k/revive-action from 2.5.9 to 2.5.10
Bumps [morphy2k/revive-action](https://github.com/morphy2k/revive-action) from 2.5.9 to 2.5.10.
- [Release notes](https://github.com/morphy2k/revive-action/releases)
- [Commits](https://github.com/morphy2k/revive-action/compare/v2.5.9...v2.5.10)

---
updated-dependencies:
- dependency-name: morphy2k/revive-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-02 06:39:35 +00:00
dropbigfish
9d581adc04 fix: fix slice init length
Signed-off-by: dropbigfish <fillfish@foxmail.com>
2024-09-01 00:36:43 +08:00
edwin
5e3b0238d8 pkg/core: move convert manager to independent file 2024-08-23 17:30:30 +08:00
edwin
bc24e8dcaa pkg/core: add more tests for convert manager 2024-08-23 17:30:30 +08:00
edwin
4fefbaf0e7 pkg/core: add currency converter 2024-08-23 17:30:30 +08:00
edwin
b683550f44 rename converter.go to symbol_converter 2024-08-23 17:30:30 +08:00
edwin
26149103f0 pkg/core: support more function to symbol converter 2024-08-23 17:30:21 +08:00
78 changed files with 2440 additions and 993 deletions

View File

@ -90,7 +90,7 @@ jobs:
sed -i -e '/_requestgen.go/d' coverage_dnum.txt
- name: Revive Check
uses: morphy2k/revive-action@v2.5.9 # https://github.com/mgechev/revive/issues/956
uses: morphy2k/revive-action@v2.5.10 # https://github.com/mgechev/revive/issues/956
with:
reporter: github-pr-review
fail_on_error: true

View File

@ -58,4 +58,4 @@ bbgo [flags]
* [bbgo userdatastream](bbgo_userdatastream.md) - Listen to session events (orderUpdate, tradeUpdate, balanceUpdate, balanceSnapshot)
* [bbgo version](bbgo_version.md) - show version name
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -41,4 +41,4 @@ bbgo account [--session SESSION] [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -50,4 +50,4 @@ bbgo backtest [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -40,4 +40,4 @@ bbgo balances [--session SESSION] [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -39,4 +39,4 @@ bbgo build [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -49,4 +49,4 @@ bbgo cancel-order [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -41,4 +41,4 @@ bbgo deposits [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -9,16 +9,18 @@ bbgo execute-order --session SESSION --symbol SYMBOL --side SIDE --target-quanti
### Options
```
--deadline duration deadline of the order execution
-h, --help help for execute-order
--price-ticks int the number of price tick for the jump spread, default to 0
--session string the exchange session name for sync
--side string the trading side: buy or sell
--slice-quantity string slice quantity
--stop-price string stop price (default "0")
--symbol string the trading pair, like btcusdt
--target-quantity string target quantity
--update-interval duration order update time (default 10s)
--deadline duration deadline duration of the order execution, e.g. 1h
--delay-interval duration order delay time after filled (default 3s)
-h, --help help for execute-order
--order-update-rate-limit string order update rate limit, syntax: 1+1/1m (default "1s")
--price-ticks int the number of price tick for the jump spread, default to 0
--session string the exchange session name for sync
--side string the trading side: buy or sell
--slice-quantity string slice quantity
--stop-price string stop price (default "0")
--symbol string the trading pair, like btcusdt
--target-quantity string target quantity
--update-interval duration order update time (default 10s)
```
### Options inherited from parent commands
@ -48,4 +50,4 @@ bbgo execute-order --session SESSION --symbol SYMBOL --side SIDE --target-quanti
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -42,4 +42,4 @@ bbgo get-order --session SESSION --order-id ORDER_ID [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -45,4 +45,4 @@ bbgo hoptimize [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -42,4 +42,4 @@ bbgo kline [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -41,4 +41,4 @@ bbgo list-orders open|closed --session SESSION --symbol SYMBOL [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -38,4 +38,4 @@ margin related history
* [bbgo margin loans](bbgo_margin_loans.md) - query loans history
* [bbgo margin repays](bbgo_margin_repays.md) - query repay history
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -41,4 +41,4 @@ bbgo margin interests --session=SESSION_NAME --asset=ASSET [flags]
* [bbgo margin](bbgo_margin.md) - margin related history
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -41,4 +41,4 @@ bbgo margin loans --session=SESSION_NAME --asset=ASSET [flags]
* [bbgo margin](bbgo_margin.md) - margin related history
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -41,4 +41,4 @@ bbgo margin repays --session=SESSION_NAME --asset=ASSET [flags]
* [bbgo margin](bbgo_margin.md) - margin related history
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -40,4 +40,4 @@ bbgo market [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -44,4 +44,4 @@ bbgo optimize [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -42,4 +42,4 @@ bbgo orderbook --session=[exchange_name] --symbol=[pair_name] [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -40,4 +40,4 @@ bbgo orderupdate [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -49,4 +49,4 @@ bbgo pnl [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -51,4 +51,4 @@ bbgo run [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -46,4 +46,4 @@ bbgo submit-order --session SESSION --symbol SYMBOL --side SIDE --quantity QUANT
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -42,4 +42,4 @@ bbgo sync [--session=[exchange_name]] [--symbol=[pair_name]] [[--since=yyyy/mm/d
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -42,4 +42,4 @@ bbgo trades --session=[exchange_name] --symbol=[pair_name] [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -40,4 +40,4 @@ bbgo tradeupdate --session=[exchange_name] [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -42,4 +42,4 @@ bbgo transfer-history [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -40,4 +40,4 @@ bbgo userdatastream [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -39,4 +39,4 @@ bbgo version [flags]
* [bbgo](bbgo.md) - bbgo is a crypto trading bot
###### Auto generated by spf13/cobra on 21-Aug-2024
###### Auto generated by spf13/cobra on 16-Sep-2024

View File

@ -17,7 +17,7 @@ TELEGRAM_BOT_TOKEN=347374838:ABFTjfiweajfiawoejfiaojfeijoaef
```
For the telegram chat authentication (your bot needs to verify it's you), if you only need a fixed authentication token,
you can set `TELEGRAM_AUTH_TOKEN` in the `.env.local` file, e.g.,
you can set `TELEGRAM_BOT_AUTH_TOKEN` in the `.env.local` file, e.g.,
```sh
TELEGRAM_BOT_AUTH_TOKEN=itsme55667788

35
doc/release/v1.60.1.md Normal file
View File

@ -0,0 +1,35 @@
## Fixes
- fixed xmaker bugs
- updated helm chart for sync cronjob
- fixed max deposits api
[Full Changelog](https://github.com/c9s/bbgo/compare/v1.60.0...main)
- [#1727](https://github.com/c9s/bbgo/pull/1727): FIX: update timeInForce for binance margin order
- [#1729](https://github.com/c9s/bbgo/pull/1729): FIX: [max] fix v3 deposit state conversion
- [#1723](https://github.com/c9s/bbgo/pull/1723): FIX: [xmaker] avoid calculate margin from 0.0 signal
- [#1721](https://github.com/c9s/bbgo/pull/1721): FIX: [xmaker] fix aggregatePrice method
- [#1725](https://github.com/c9s/bbgo/pull/1725): IMPROVE: [xmaker] improve hedge margin account leverage calculation
- [#1722](https://github.com/c9s/bbgo/pull/1722): FEATURE: [xmaker] add signals
- [#1720](https://github.com/c9s/bbgo/pull/1720): FEATURE: [xmaker] margin credit improvement
- [#1718](https://github.com/c9s/bbgo/pull/1718): FEATURE: [xmaker] add more config metrics
- [#1719](https://github.com/c9s/bbgo/pull/1719): IMPROVE: [xmaker] fix bollinger band price calculation
- [#1709](https://github.com/c9s/bbgo/pull/1709): IMPROVE: [xmaker] improve profit stats ticker and integrate rate limiter
- [#1708](https://github.com/c9s/bbgo/pull/1708): FEATURE: [xmaker] integrate circuit breaker
- [#1712](https://github.com/c9s/bbgo/pull/1712): FEATURE: [xmaker] add profit fixer
- [#1710](https://github.com/c9s/bbgo/pull/1710): IMPROVE: [xmaker] improve stability
- [#1717](https://github.com/c9s/bbgo/pull/1717): REFACTOR: [xmaker] refactor hedge worker and quote worker
- [#1716](https://github.com/c9s/bbgo/pull/1716): FIX: [xmaker] profit object can be nil
- [#1707](https://github.com/c9s/bbgo/pull/1707): FIX: [xmaker] position metrics missing label
- [#1715](https://github.com/c9s/bbgo/pull/1715): UPGRADE: [go] upgrade packages that are too old
- [#1713](https://github.com/c9s/bbgo/pull/1713): FEATURE: [chart] add env vars section
- [#1711](https://github.com/c9s/bbgo/pull/1711): FEATURE: [binance] add new margin order side effect AUTO_BORROW_REPAY
- [#1705](https://github.com/c9s/bbgo/pull/1705): FIX: [k8s] fix sync.enabled option
- [#1704](https://github.com/c9s/bbgo/pull/1704): FEATURE: [k8s] add cronjob for sync
- [#1700](https://github.com/c9s/bbgo/pull/1700): Fix: [autobuy] fix error when bollinger settings is not set
- [#1703](https://github.com/c9s/bbgo/pull/1703): FEATURE: [core] add position metrics
- [#1702](https://github.com/c9s/bbgo/pull/1702): IMPROVE: improve balance related metrics
- [#1699](https://github.com/c9s/bbgo/pull/1699): REFACTOR: [twap] upgrade twap command and add optional order update rate limiter
- [#1701](https://github.com/c9s/bbgo/pull/1701): RELEASE: v1.60.0
- [#1714](https://github.com/c9s/bbgo/pull/1714): dep: bump actions/setup-node from 2 to 4

18
doc/release/v1.60.2.md Normal file
View File

@ -0,0 +1,18 @@
[Full Changelog](https://github.com/c9s/bbgo/compare/v1.60.1...main)
- [#1739](https://github.com/c9s/bbgo/pull/1739): FEATURE: [dca2] set exchange fee rate for round position
- [#1738](https://github.com/c9s/bbgo/pull/1738): FEATURE: [okx] update symbols to latest
- [#1737](https://github.com/c9s/bbgo/pull/1737): FEATURE: [xmaker] implement tryArbitrage
- [#1730](https://github.com/c9s/bbgo/pull/1730): FEATURE: [xmaker] add market trade signal
- [#1734](https://github.com/c9s/bbgo/pull/1734): REFACTOR: [xmaker] refactor for supporting ioc arb [part1]
- [#1736](https://github.com/c9s/bbgo/pull/1736): MINOR: [session] remove environment nil validation log
- [#1742](https://github.com/c9s/bbgo/pull/1742): FIX: types/stream: change errorf to warnf
- [#1741](https://github.com/c9s/bbgo/pull/1741): FIX: upgrade github.com/c9s/requestgen to 1.4.3
- [#1740](https://github.com/c9s/bbgo/pull/1740): FIX: upgrade requestgen and re-generate max cancel order request files
- [#1726](https://github.com/c9s/bbgo/pull/1726): dep: bump morphy2k/revive-action from 2.5.9 to 2.5.10
- [#1735](https://github.com/c9s/bbgo/pull/1735): FIX: configure environment
- [#1724](https://github.com/c9s/bbgo/pull/1724): FIX: fix slice init length
- [#1733](https://github.com/c9s/bbgo/pull/1733): FIX: [bbgo] fix the defaults / initialize steps
- [#1732](https://github.com/c9s/bbgo/pull/1732): FIX: fix env name
- [#1728](https://github.com/c9s/bbgo/pull/1728): FIX: [core] fix memory leak
- [#1731](https://github.com/c9s/bbgo/pull/1731): FIX: fix json tag

4
doc/release/v1.60.3.md Normal file
View File

@ -0,0 +1,4 @@
[Full Changelog](https://github.com/c9s/bbgo/compare/v1.60.2...main)
- FIX: fix xmaker default price
- [#1744](https://github.com/c9s/bbgo/pull/1744): call b.EmitNew() when new order is added into activeorderbook

8
go.mod
View File

@ -11,7 +11,7 @@ require (
github.com/Masterminds/squirrel v1.5.3
github.com/adshao/go-binance/v2 v2.6.0
github.com/c-bata/goptuna v0.8.1
github.com/c9s/requestgen v1.3.6
github.com/c9s/requestgen v1.4.3
github.com/c9s/rockhopper/v2 v2.0.4
github.com/cenkalti/backoff/v4 v4.2.0
github.com/cheggaaa/pb/v3 v3.0.8
@ -119,7 +119,7 @@ require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/mattn/go-sqlite3 v1.14.23 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
@ -153,12 +153,12 @@ require (
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 // indirect
golang.org/x/image v0.5.0 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/mod v0.20.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/term v0.23.0 // indirect
golang.org/x/text v0.17.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
golang.org/x/tools v0.24.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect

16
go.sum
View File

@ -86,8 +86,8 @@ github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP
github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/c-bata/goptuna v0.8.1 h1:25+n1MLv0yvCsD56xv4nqIus3oLHL9GuPAZDLIqmX1U=
github.com/c-bata/goptuna v0.8.1/go.mod h1:knmS8+Iyq5PPy1YUeIEq0pMFR4Y6x7z/CySc9HlZTCY=
github.com/c9s/requestgen v1.3.6 h1:ul7dZ2uwGYjNBjreooRfSY10WTXvQmQSjZsHebz6QfE=
github.com/c9s/requestgen v1.3.6/go.mod h1:QwkZudcv84kJ8g9+E0RDTj+13btFXbTvv2aI+zbuLbc=
github.com/c9s/requestgen v1.4.3 h1:0QZ27RVBLb9QuBKfiSBTOB5zSUuasrJm2p6/GZZHZZw=
github.com/c9s/requestgen v1.4.3/go.mod h1:3gk1M2ihvNU2wWl7WLUc09myp7XpHMP33Dx96+Vr8A0=
github.com/c9s/rockhopper/v2 v2.0.4 h1:1cQEzU7rzCSz09B2RYdyPWwBW9gZ/DoFqD1b2xLLmAk=
github.com/c9s/rockhopper/v2 v2.0.4/go.mod h1:x0XuYI2Su3kS/74UYu/3Cqc9m5Dtzqh7j7JZarczfss=
github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4=
@ -472,8 +472,8 @@ github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lL
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mattn/go-sqlite3 v1.14.23 h1:gbShiuAP1W5j9UOksQ06aiiqPMxYecovVGwmTxWtuw0=
github.com/mattn/go-sqlite3 v1.14.23/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
@ -759,8 +759,8 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@ -951,8 +951,8 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -0,0 +1,10 @@
-- +up
-- +begin
CREATE INDEX positions_traded_at ON positions (traded_at, profit);
-- +end
-- +down
-- +begin
DROP INDEX positions_traded_at ON positions;
-- +end

View File

@ -0,0 +1,10 @@
-- +up
-- +begin
CREATE INDEX positions_traded_at ON positions (traded_at, profit);
-- +end
-- +down
-- +begin
DROP INDEX positions_traded_at;
-- +end

View File

@ -359,6 +359,7 @@ func (b *ActiveOrderBook) Add(orders ...types.Order) {
}
b.add(order)
b.EmitNew(order)
}
}

View File

@ -5,6 +5,8 @@ import "github.com/c9s/bbgo/pkg/types"
const MaxNumOfKLines = 5_000
const MaxNumOfKLinesTruncate = 100
const CapacityOfKLineWindowLimit = 5_000
// MarketDataStore receives and maintain the public market data of a single symbol
//go:generate callbackgen -type MarketDataStore
type MarketDataStore struct {
@ -57,10 +59,20 @@ func (store *MarketDataStore) AddKLine(k types.KLine) {
}
window.Add(k)
if len(*window) > MaxNumOfKLines {
*window = (*window)[MaxNumOfKLinesTruncate-1:]
}
truncateKLineWindowIfNeeded(window)
store.EmitKLineClosed(k)
store.EmitKLineWindowUpdate(k.Interval, *window)
}
func truncateKLineWindowIfNeeded(window *types.KLineWindow) {
lenOfWindow := len(*window)
capOfWindow := cap(*window)
if lenOfWindow == capOfWindow && capOfWindow > CapacityOfKLineWindowLimit {
size := CapacityOfKLineWindowLimit / 2
start := lenOfWindow - size
copy(*window, (*window)[start:])
*window = (*window)[:size]
}
}

View File

@ -0,0 +1,45 @@
package bbgo
import (
"testing"
"github.com/c9s/bbgo/pkg/types"
"github.com/stretchr/testify/assert"
)
func TestMarketDataStore_AddKLineAndTruncateWindow(t *testing.T) {
store := NewMarketDataStore("BTCUSD")
interval := types.Interval1s
var maxCap int = 0
capFixed := false
var gid uint64 = 0
// insert 1.5 * CapacityOfKLineWindowLimit KLine into window
for ; gid < CapacityOfKLineWindowLimit+(CapacityOfKLineWindowLimit/2); gid++ {
store.AddKLine(types.KLine{
Interval: interval,
GID: gid,
})
// if the capacity is > CapacityOfKLineWindowLimit, the capacity should be fixed. We use this if expression to verify it then.
if !capFixed && cap(*store.KLineWindows[interval]) > CapacityOfKLineWindowLimit {
maxCap = cap(*store.KLineWindows[interval])
capFixed = true
}
}
window := store.KLineWindows[interval]
// make sure the capacity is fixed
assert.Equal(t, maxCap, cap(*window))
// after truncate, it will remain (CapacityOfKLineWindowLimit / 2) KLine in the window
// so the first GIC will be the maxCap - (CapacityOfKLineWindowLimit / 2)
truncatedGID := uint64(maxCap - (CapacityOfKLineWindowLimit / 2))
for _, kline := range *window {
assert.Equal(t, truncatedGID, kline.GID)
truncatedGID++
}
}

View File

@ -405,6 +405,8 @@ func (session *ExchangeSession) initSymbol(ctx context.Context, environ *Environ
return fmt.Errorf("market %s is not defined", symbol)
}
session.logger.Infof("environment config: %+v", environ.environmentConfig)
disableMarketDataStore := environ.environmentConfig != nil && environ.environmentConfig.DisableMarketDataStore
disableSessionTradeBuffer := environ.environmentConfig != nil && environ.environmentConfig.DisableSessionTradeBuffer
maxSessionTradeBufferSize := 0

View File

@ -16,8 +16,18 @@ import (
)
// Strategy method calls:
// -> Initialize() (optional method)
// -> Defaults() (optional method)
//
// setup default static values from constants
//
// -> Initialize() (optional method)
//
// initialize dynamic runtime objects
//
// -> Subscribe()
//
// register the subscriptions
//
// -> Validate() (optional method)
// -> Run() (optional method)
// -> Shutdown(shutdownCtx context.Context, wg *sync.WaitGroup)
@ -112,6 +122,12 @@ func (trader *Trader) DisableLogging() {
}
func (trader *Trader) Configure(userConfig *Config) error {
// config environment
if userConfig.Environment != nil && trader.environment != nil {
trader.environment.environmentConfig = userConfig.Environment
}
// config risk control
if userConfig.RiskControls != nil {
trader.SetRiskControls(userConfig.RiskControls)
}
@ -171,12 +187,6 @@ func (trader *Trader) SetRiskControls(riskControls *RiskControls) {
func (trader *Trader) RunSingleExchangeStrategy(
ctx context.Context, strategy SingleExchangeStrategy, session *ExchangeSession, orderExecutor OrderExecutor,
) error {
if v, ok := strategy.(StrategyValidator); ok {
if err := v.Validate(); err != nil {
return fmt.Errorf("failed to validate the config: %w", err)
}
}
if shutdown, ok := strategy.(StrategyShutdown); ok {
trader.gracefulShutdown.OnShutdown(shutdown.Shutdown)
}
@ -238,12 +248,6 @@ func (trader *Trader) injectFieldsAndSubscribe(ctx context.Context) error {
return err
}
if defaulter, ok := strategy.(StrategyDefaulter); ok {
if err := defaulter.Defaults(); err != nil {
panic(err)
}
}
if subscriber, ok := strategy.(ExchangeSessionSubscriber); ok {
subscriber.Subscribe(session)
} else {
@ -304,12 +308,6 @@ func (trader *Trader) injectFieldsAndSubscribe(ctx context.Context) error {
}
}
if initializer, ok := strategy.(StrategyInitializer); ok {
if err := initializer.Initialize(); err != nil {
return err
}
}
if subscriber, ok := strategy.(CrossExchangeSessionSubscriber); ok {
subscriber.CrossSubscribe(trader.environment.sessions)
} else {
@ -356,8 +354,23 @@ func (trader *Trader) Run(ctx context.Context) error {
return trader.environment.Connect(ctx)
}
// Initialize initializes the strategies, this method is called before the Run method.
// It sets the default values and validates the strategy configurations.
// And calls the Initialize method if the strategy implements the Initialize method.
func (trader *Trader) Initialize(ctx context.Context) error {
return trader.IterateStrategies(func(strategy StrategyID) error {
if defaulter, ok := strategy.(StrategyDefaulter); ok {
if err := defaulter.Defaults(); err != nil {
return err
}
}
if v, ok := strategy.(StrategyValidator); ok {
if err := v.Validate(); err != nil {
return fmt.Errorf("found invalid strategy config: %w", err)
}
}
if initializer, ok := strategy.(StrategyInitializer); ok {
return initializer.Initialize()
}

153
pkg/core/convert_manager.go Normal file
View File

@ -0,0 +1,153 @@
package core
import (
"github.com/c9s/bbgo/pkg/types"
"github.com/sirupsen/logrus"
)
type ConverterSetting struct {
SymbolConverter *SymbolConverter `json:"symbolConverter" yaml:"symbolConverter"`
CurrencyConverter *CurrencyConverter `json:"currencyConverter" yaml:"currencyConverter"`
}
func (s *ConverterSetting) getConverter() Converter {
if s.SymbolConverter != nil {
return s.SymbolConverter
}
if s.CurrencyConverter != nil {
return s.CurrencyConverter
}
return nil
}
func (s *ConverterSetting) InitializeConverter() (Converter, error) {
converter := s.getConverter()
if converter == nil {
return nil, nil
}
logrus.Infof("initializing converter %T ...", converter)
err := converter.Initialize()
return converter, err
}
// ConverterManager manages the converters for trade conversion
// It can be used to convert the trade symbol into the target symbol, or convert the price, volume into different units.
type ConverterManager struct {
ConverterSettings []ConverterSetting `json:"converters,omitempty" yaml:"converters,omitempty"`
converters []Converter
}
func (c *ConverterManager) Initialize() error {
for _, setting := range c.ConverterSettings {
converter, err := setting.InitializeConverter()
if err != nil {
return err
}
if converter != nil {
c.AddConverter(converter)
}
}
numConverters := len(c.converters)
logrus.Infof("%d converters loaded", numConverters)
return nil
}
func (c *ConverterManager) AddConverter(converter Converter) {
c.converters = append(c.converters, converter)
}
func (c *ConverterManager) ConvertOrder(order types.Order) types.Order {
if len(c.converters) == 0 {
return order
}
for _, converter := range c.converters {
convOrder, err := converter.ConvertOrder(order)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, order: %s", converter, order.String())
continue
}
order = convOrder
}
return order
}
func (c *ConverterManager) ConvertTrade(trade types.Trade) types.Trade {
if len(c.converters) == 0 {
return trade
}
for _, converter := range c.converters {
convTrade, err := converter.ConvertTrade(trade)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, trade: %s", converter, trade.String())
continue
}
trade = convTrade
}
return trade
}
func (c *ConverterManager) ConvertKLine(kline types.KLine) types.KLine {
if len(c.converters) == 0 {
return kline
}
for _, converter := range c.converters {
convKline, err := converter.ConvertKLine(kline)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, kline: %s", converter, kline.String())
continue
}
kline = convKline
}
return kline
}
func (c *ConverterManager) ConvertMarket(market types.Market) types.Market {
if len(c.converters) == 0 {
return market
}
for _, converter := range c.converters {
convMarket, err := converter.ConvertMarket(market)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, market: %+v", converter, market)
continue
}
market = convMarket
}
return market
}
func (c *ConverterManager) ConvertBalance(balance types.Balance) types.Balance {
if len(c.converters) == 0 {
return balance
}
for _, converter := range c.converters {
convBal, err := converter.ConvertBalance(balance)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, balance: %s", converter, balance.String())
continue
}
balance = convBal
}
return balance
}

View File

@ -0,0 +1,212 @@
package core
import (
"encoding/json"
"testing"
"github.com/c9s/bbgo/pkg/types"
"github.com/stretchr/testify/assert"
)
func TestInitializeConverter_ValidSymbolConverter(t *testing.T) {
setting := ConverterSetting{
SymbolConverter: &SymbolConverter{
FromSymbol: "MAXEXCHANGEUSDT",
ToSymbol: "MAXUSDT",
},
}
converter, err := setting.InitializeConverter()
assert.NoError(t, err)
assert.NotNil(t, converter)
}
func TestInitializeConverter_ValidCurrencyConverter(t *testing.T) {
setting := ConverterSetting{
CurrencyConverter: &CurrencyConverter{
FromCurrency: "MAXEXCHANGE",
ToCurrency: "MAX",
},
}
converter, err := setting.InitializeConverter()
assert.NoError(t, err)
assert.NotNil(t, converter)
}
func TestInitializeConverter_NoConverter(t *testing.T) {
setting := ConverterSetting{}
converter, err := setting.InitializeConverter()
assert.NoError(t, err)
assert.Nil(t, converter)
}
func TestInitialize_ValidConverters(t *testing.T) {
manager := ConverterManager{
ConverterSettings: []ConverterSetting{
{SymbolConverter: &SymbolConverter{
FromSymbol: "MAXEXCHANGEUSDT",
ToSymbol: "MAXUSDT",
}},
{CurrencyConverter: &CurrencyConverter{
FromCurrency: "MAXEXCHANGE",
ToCurrency: "MAX",
}},
},
}
err := manager.Initialize()
assert.NoError(t, err)
assert.Equal(t, 2, len(manager.converters))
}
func TestInitialize_NoConverters(t *testing.T) {
manager := ConverterManager{}
err := manager.Initialize()
assert.NoError(t, err)
assert.Equal(t, 0, len(manager.converters))
}
func TestConvertOrder_WithConverters(t *testing.T) {
jsonStr := `
{
"converters": [
{
"symbolConverter": {
"from": "MAXEXCHANGEUSDT",
"to": "MAXUSDT"
}
},
{
"currencyConverter": {
"from": "MAXEXCHANGE",
"to": "MAX"
}
}
]
}
`
manager := ConverterManager{}
err := json.Unmarshal([]byte(jsonStr), &manager)
assert.NoError(t, err)
order := types.Order{
SubmitOrder: types.SubmitOrder{
Symbol: "MAXEXCHANGEUSDT",
Market: types.Market{
Symbol: "MAXEXCHANGEUSDT",
QuoteCurrency: "USDT",
BaseCurrency: "MAXEXCHANGE",
},
},
}
err = manager.Initialize()
assert.NoError(t, err)
convertedOrder := manager.ConvertOrder(order)
assert.Equal(t, "MAXUSDT", convertedOrder.Symbol)
assert.Equal(t, "MAX", convertedOrder.Market.BaseCurrency)
assert.Equal(t, "USDT", convertedOrder.Market.QuoteCurrency)
assert.Equal(t, "MAXUSDT", convertedOrder.Market.Symbol)
}
func TestConvertOrder_NoConverters(t *testing.T) {
manager := ConverterManager{}
order := types.Order{}
err := manager.Initialize()
assert.NoError(t, err)
convertedOrder := manager.ConvertOrder(order)
assert.Equal(t, order, convertedOrder)
}
func TestConvertTrade_WithConverters(t *testing.T) {
manager := ConverterManager{}
converter := &CurrencyConverter{
FromCurrency: "MAXEXCHANGE",
ToCurrency: "MAX",
}
err := manager.Initialize()
assert.NoError(t, err)
manager.AddConverter(converter)
trade := types.Trade{}
convertedTrade := manager.ConvertTrade(trade)
assert.Equal(t, trade, convertedTrade)
}
func TestConvertTrade_NoConverters(t *testing.T) {
manager := ConverterManager{}
trade := types.Trade{}
err := manager.Initialize()
assert.NoError(t, err)
convertedTrade := manager.ConvertTrade(trade)
assert.Equal(t, trade, convertedTrade)
}
func TestConvertKLine_WithConverters(t *testing.T) {
manager := ConverterManager{}
converter := &CurrencyConverter{
FromCurrency: "MAXEXCHANGE",
ToCurrency: "MAX",
}
err := manager.Initialize()
assert.NoError(t, err)
manager.AddConverter(converter)
kline := types.KLine{}
convertedKline := manager.ConvertKLine(kline)
assert.Equal(t, kline, convertedKline)
}
func TestConvertKLine_NoConverters(t *testing.T) {
manager := ConverterManager{}
kline := types.KLine{}
err := manager.Initialize()
assert.NoError(t, err)
convertedKline := manager.ConvertKLine(kline)
assert.Equal(t, kline, convertedKline)
}
func TestConvertMarket_WithConverters(t *testing.T) {
manager := ConverterManager{}
converter := &CurrencyConverter{
FromCurrency: "MAXEXCHANGE",
ToCurrency: "MAX",
}
err := manager.Initialize()
assert.NoError(t, err)
manager.AddConverter(converter)
market := types.Market{}
convertedMarket := manager.ConvertMarket(market)
assert.Equal(t, market, convertedMarket)
}
func TestConvertMarket_NoConverters(t *testing.T) {
manager := ConverterManager{}
market := types.Market{}
err := manager.Initialize()
assert.NoError(t, err)
convertedMarket := manager.ConvertMarket(market)
assert.Equal(t, market, convertedMarket)
}
func TestConvertBalance_WithConverters(t *testing.T) {
manager := ConverterManager{}
converter := &CurrencyConverter{
FromCurrency: "MAXEXCHANGE",
ToCurrency: "MAX",
}
err := manager.Initialize()
assert.NoError(t, err)
manager.AddConverter(converter)
balance := types.Balance{}
convertedBalance := manager.ConvertBalance(balance)
assert.Equal(t, balance, convertedBalance)
}
func TestConvertBalance_NoConverters(t *testing.T) {
manager := ConverterManager{}
balance := types.Balance{}
err := manager.Initialize()
assert.NoError(t, err)
convertedBalance := manager.ConvertBalance(balance)
assert.Equal(t, balance, convertedBalance)
}

View File

@ -1,31 +0,0 @@
package core
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/c9s/bbgo/pkg/types"
)
func TestSymbolConverter(t *testing.T) {
converter := NewSymbolConverter("MAXEXCHANGEUSDT", "MAXUSDT")
trade, err := converter.ConvertTrade(types.Trade{
Symbol: "MAXEXCHANGEUSDT",
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXUSDT", trade.Symbol)
}
order, err := converter.ConvertOrder(types.Order{
SubmitOrder: types.SubmitOrder{
Symbol: "MAXEXCHANGEUSDT",
},
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXUSDT", order.Symbol)
}
}

View File

@ -0,0 +1,68 @@
package core
import (
"errors"
"github.com/c9s/bbgo/pkg/types"
)
type CurrencyConverter struct {
FromCurrency string `json:"from"`
ToCurrency string `json:"to"`
}
func NewCurrencyConverter(fromSymbol, toSymbol string) *CurrencyConverter {
return &CurrencyConverter{FromCurrency: fromSymbol, ToCurrency: toSymbol}
}
func (c *CurrencyConverter) Initialize() error {
if c.FromCurrency == "" {
return errors.New("FromCurrency can not be empty")
}
if c.ToCurrency == "" {
return errors.New("ToCurrency can not be empty")
}
return nil
}
func (c *CurrencyConverter) ConvertOrder(order types.Order) (types.Order, error) {
if order.SubmitOrder.Market.QuoteCurrency == c.FromCurrency {
order.SubmitOrder.Market.QuoteCurrency = c.ToCurrency
}
if order.SubmitOrder.Market.BaseCurrency == c.FromCurrency {
order.SubmitOrder.Market.BaseCurrency = c.ToCurrency
}
return order, nil
}
func (c *CurrencyConverter) ConvertTrade(trade types.Trade) (types.Trade, error) {
if trade.FeeCurrency == c.FromCurrency {
trade.FeeCurrency = c.ToCurrency
}
return trade, nil
}
func (c *CurrencyConverter) ConvertKLine(kline types.KLine) (types.KLine, error) {
return kline, nil
}
func (c *CurrencyConverter) ConvertMarket(mkt types.Market) (types.Market, error) {
if mkt.QuoteCurrency == c.FromCurrency {
mkt.QuoteCurrency = c.ToCurrency
}
if mkt.BaseCurrency == c.FromCurrency {
mkt.BaseCurrency = c.ToCurrency
}
return mkt, nil
}
func (c *CurrencyConverter) ConvertBalance(balance types.Balance) (types.Balance, error) {
if balance.Currency == c.FromCurrency {
balance.Currency = c.ToCurrency
}
return balance, nil
}

View File

@ -0,0 +1,124 @@
package core
import (
"github.com/c9s/bbgo/pkg/types"
"github.com/stretchr/testify/assert"
"testing"
)
// pkg/core/tradecollector_test.go
func TestInitialize_ValidCurrencies(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
err := converter.Initialize()
assert.NoError(t, err)
}
func TestInitialize_EmptyFromCurrency(t *testing.T) {
converter := NewCurrencyConverter("", "MAX")
err := converter.Initialize()
assert.Error(t, err)
assert.Equal(t, "FromCurrency can not be empty", err.Error())
}
func TestInitialize_EmptyToCurrency(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "")
err := converter.Initialize()
assert.Error(t, err)
assert.Equal(t, "ToCurrency can not be empty", err.Error())
}
func TestConvertOrder_ValidConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
order := types.Order{
SubmitOrder: types.SubmitOrder{
Market: types.Market{
QuoteCurrency: "MAXEXCHANGE",
BaseCurrency: "MAXEXCHANGE",
},
},
}
convertedOrder, err := converter.ConvertOrder(order)
assert.NoError(t, err)
assert.Equal(t, "MAX", convertedOrder.SubmitOrder.Market.QuoteCurrency)
assert.Equal(t, "MAX", convertedOrder.SubmitOrder.Market.BaseCurrency)
}
func TestConvertOrder_NoConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
order := types.Order{
SubmitOrder: types.SubmitOrder{
Market: types.Market{
QuoteCurrency: "JPY",
BaseCurrency: "JPY",
},
},
}
convertedOrder, err := converter.ConvertOrder(order)
assert.NoError(t, err)
assert.Equal(t, "JPY", convertedOrder.SubmitOrder.Market.QuoteCurrency)
assert.Equal(t, "JPY", convertedOrder.SubmitOrder.Market.BaseCurrency)
}
func TestConvertTrade_ValidConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
trade := types.Trade{
FeeCurrency: "MAXEXCHANGE",
}
convertedTrade, err := converter.ConvertTrade(trade)
assert.NoError(t, err)
assert.Equal(t, "MAX", convertedTrade.FeeCurrency)
}
func TestConvertTrade_NoConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
trade := types.Trade{
FeeCurrency: "JPY",
}
convertedTrade, err := converter.ConvertTrade(trade)
assert.NoError(t, err)
assert.Equal(t, "JPY", convertedTrade.FeeCurrency)
}
func TestConvertMarket_ValidConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
market := types.Market{
QuoteCurrency: "MAXEXCHANGE",
BaseCurrency: "MAXEXCHANGE",
}
convertedMarket, err := converter.ConvertMarket(market)
assert.NoError(t, err)
assert.Equal(t, "MAX", convertedMarket.QuoteCurrency)
assert.Equal(t, "MAX", convertedMarket.BaseCurrency)
}
func TestConvertMarket_NoConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
market := types.Market{
QuoteCurrency: "JPY",
BaseCurrency: "JPY",
}
convertedMarket, err := converter.ConvertMarket(market)
assert.NoError(t, err)
assert.Equal(t, "JPY", convertedMarket.QuoteCurrency)
assert.Equal(t, "JPY", convertedMarket.BaseCurrency)
}
func TestConvertBalance_ValidConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
balance := types.Balance{
Currency: "MAXEXCHANGE",
}
convertedBalance, err := converter.ConvertBalance(balance)
assert.NoError(t, err)
assert.Equal(t, "MAX", convertedBalance.Currency)
}
func TestConvertBalance_NoConversion(t *testing.T) {
converter := NewCurrencyConverter("MAXEXCHANGE", "MAX")
balance := types.Balance{
Currency: "JPY",
}
convertedBalance, err := converter.ConvertBalance(balance)
assert.NoError(t, err)
assert.Equal(t, "JPY", convertedBalance.Currency)
}

View File

@ -9,6 +9,9 @@ import (
type Converter interface {
OrderConverter
TradeConverter
KLineConverter
MarketConverter
BalanceConverter
Initialize() error
}
@ -22,12 +25,33 @@ type TradeConverter interface {
ConvertTrade(trade types.Trade) (types.Trade, error)
}
// KLineConverter converts the kline to another kline
type KLineConverter interface {
ConvertKLine(kline types.KLine) (types.KLine, error)
}
// MarketConverter converts the market to another market
type MarketConverter interface {
ConvertMarket(market types.Market) (types.Market, error)
}
// BalanceConverter converts the balance to another balance
type BalanceConverter interface {
ConvertBalance(balance types.Balance) (types.Balance, error)
}
type OrderConvertFunc func(order types.Order) (types.Order, error)
type TradeConvertFunc func(trade types.Trade) (types.Trade, error)
type KLineConvertFunc func(kline types.KLine) (types.KLine, error)
type MarketConvertFunc func(market types.Market) (types.Market, error)
type BalanceConvertFunc func(balance types.Balance) (types.Balance, error)
type DynamicConverter struct {
orderConverter OrderConvertFunc
tradeConverter TradeConvertFunc
orderConverter OrderConvertFunc
tradeConverter TradeConvertFunc
klineConverter KLineConvertFunc
marketConverter MarketConvertFunc
balanceConverter BalanceConvertFunc
}
func NewDynamicConverter(orderConverter OrderConvertFunc, tradeConverter TradeConvertFunc) *DynamicConverter {
@ -46,6 +70,18 @@ func (c *DynamicConverter) ConvertTrade(trade types.Trade) (types.Trade, error)
return c.tradeConverter(trade)
}
func (c *DynamicConverter) ConvertKLine(kline types.KLine) (types.KLine, error) {
return c.klineConverter(kline)
}
func (c *DynamicConverter) ConvertMarket(market types.Market) (types.Market, error) {
return c.marketConverter(market)
}
func (c *DynamicConverter) ConvertBalance(balance types.Balance) (types.Balance, error) {
return c.balanceConverter(balance)
}
// SymbolConverter converts the symbol to another symbol
type SymbolConverter struct {
FromSymbol string `json:"from"`
@ -73,6 +109,10 @@ func (c *SymbolConverter) ConvertOrder(order types.Order) (types.Order, error) {
order.Symbol = c.ToSymbol
}
if order.SubmitOrder.Market.Symbol == c.FromSymbol {
order.SubmitOrder.Market.Symbol = c.ToSymbol
}
return order, nil
}
@ -83,3 +123,22 @@ func (c *SymbolConverter) ConvertTrade(trade types.Trade) (types.Trade, error) {
return trade, nil
}
func (c *SymbolConverter) ConvertKLine(kline types.KLine) (types.KLine, error) {
if kline.Symbol == c.FromSymbol {
kline.Symbol = c.ToSymbol
}
return kline, nil
}
func (s *SymbolConverter) ConvertMarket(mkt types.Market) (types.Market, error) {
if mkt.Symbol == s.FromSymbol {
mkt.Symbol = s.ToSymbol
}
return mkt, nil
}
func (c *SymbolConverter) ConvertBalance(balance types.Balance) (types.Balance, error) {
return balance, nil
}

View File

@ -0,0 +1,60 @@
package core
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/c9s/bbgo/pkg/types"
)
func TestSymbolConverter(t *testing.T) {
converter := NewSymbolConverter("MAXEXCHANGEUSDT", "MAXUSDT")
trade, err := converter.ConvertTrade(types.Trade{
Symbol: "MAXEXCHANGEUSDT",
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXUSDT", trade.Symbol)
}
order, err := converter.ConvertOrder(types.Order{
SubmitOrder: types.SubmitOrder{
Symbol: "MAXEXCHANGEUSDT",
Market: types.Market{
Symbol: "MAXEXCHANGEUSDT",
},
},
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXUSDT", order.Symbol)
assert.Equal(t, "MAXUSDT", order.SubmitOrder.Symbol)
assert.Equal(t, "MAXUSDT", order.SubmitOrder.Market.Symbol)
}
kline, err := converter.ConvertKLine(types.KLine{
Symbol: "MAXEXCHANGEUSDT",
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXUSDT", kline.Symbol)
}
market, err := converter.ConvertMarket(types.Market{
Symbol: "MAXEXCHANGEUSDT",
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXUSDT", market.Symbol)
}
balance, err := converter.ConvertBalance(types.Balance{
Currency: "MAXEXCHANGE",
})
if assert.NoError(t, err) {
assert.Equal(t, "MAXEXCHANGE", balance.Currency)
}
}

View File

@ -12,94 +12,6 @@ import (
"github.com/c9s/bbgo/pkg/types"
)
type ConverterSetting struct {
SymbolConverter *SymbolConverter `json:"symbolConverter" yaml:"symbolConverter"`
}
func (s *ConverterSetting) getConverter() Converter {
if s.SymbolConverter != nil {
return s.SymbolConverter
}
return nil
}
func (s *ConverterSetting) InitializeConverter() (Converter, error) {
converter := s.getConverter()
if converter == nil {
return nil, nil
}
logrus.Infof("initializing converter %T ...", converter)
err := converter.Initialize()
return converter, err
}
// ConverterManager manages the converters for trade conversion
// It can be used to convert the trade symbol into the target symbol, or convert the price, volume into different units.
type ConverterManager struct {
ConverterSettings []ConverterSetting `json:"converters,omitempty" yaml:"converters,omitempty"`
converters []Converter
}
func (c *ConverterManager) Initialize() error {
for _, setting := range c.ConverterSettings {
converter, err := setting.InitializeConverter()
if err != nil {
return err
}
if converter != nil {
c.AddConverter(converter)
}
}
numConverters := len(c.converters)
logrus.Infof("%d converters loaded", numConverters)
return nil
}
func (c *ConverterManager) AddConverter(converter Converter) {
c.converters = append(c.converters, converter)
}
func (c *ConverterManager) ConvertOrder(order types.Order) types.Order {
if len(c.converters) == 0 {
return order
}
for _, converter := range c.converters {
convOrder, err := converter.ConvertOrder(order)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, order: %s", converter, order.String())
continue
}
order = convOrder
}
return order
}
func (c *ConverterManager) ConvertTrade(trade types.Trade) types.Trade {
if len(c.converters) == 0 {
return trade
}
for _, converter := range c.converters {
convTrade, err := converter.ConvertTrade(trade)
if err != nil {
logrus.WithError(err).Errorf("converter %+v error, trade: %s", converter, trade.String())
continue
}
trade = convTrade
}
return trade
}
//go:generate callbackgen -type TradeCollector
type TradeCollector struct {
Symbol string

View File

@ -1005,16 +1005,13 @@ func (e *Exchange) submitMarginOrder(ctx context.Context, order types.SubmitOrde
}
}
// could be IOC or FOK
switch order.Type {
case types.OrderTypeLimit, types.OrderTypeStopLimit:
req.TimeInForce(binance.TimeInForceTypeGTC)
case types.OrderTypeLimitMaker:
// do not set TimeInForce for LimitMaker
default:
if len(order.TimeInForce) > 0 {
// TODO: check the TimeInForce value
req.TimeInForce(binance.TimeInForceType(order.TimeInForce))
if len(order.TimeInForce) > 0 {
// TODO: check the TimeInForce value
req.TimeInForce(binance.TimeInForceType(order.TimeInForce))
} else {
switch order.Type {
case types.OrderTypeLimit, types.OrderTypeStopLimit:
req.TimeInForce(binance.TimeInForceTypeGTC)
}
}

View File

@ -247,29 +247,6 @@ func toGlobalTradeV3(t v3.Trade) ([]types.Trade, error) {
return trades, nil
}
func toGlobalTradeV2(t max.Trade) (*types.Trade, error) {
isMargin := t.WalletType == max.WalletTypeMargin
side := toGlobalSideType(t.Side)
return &types.Trade{
ID: t.ID,
OrderID: t.OrderID,
Price: t.Price,
Symbol: toGlobalSymbol(t.Market),
Exchange: types.ExchangeMax,
Quantity: t.Volume,
Side: side,
IsBuyer: t.IsBuyer(),
IsMaker: t.IsMaker(),
Fee: t.Fee,
FeeCurrency: toGlobalCurrency(t.FeeCurrency),
QuoteQuantity: t.Funds,
Time: types.Time(t.CreatedAt),
IsMargin: isMargin,
IsIsolated: false,
IsFutures: false,
}, nil
}
func toGlobalDepositStatus(a max.DepositState) types.DepositStatus {
switch a {
@ -284,11 +261,21 @@ func toGlobalDepositStatus(a max.DepositState) types.DepositStatus {
case max.DepositStateAccepted:
return types.DepositSuccess
case max.DepositStateFailed: // v3 state
return types.DepositRejected
case max.DepositStateProcessing: // v3 states
return types.DepositPending
case max.DepositStateDone: // v3 states
return types.DepositSuccess
}
// other states goes to this
// max.DepositStateSuspect, max.DepositStateSuspended
log.Warnf("unsupported deposit state %q from max exchange", a)
log.Errorf("unsupported deposit state %q from max exchange", a)
return types.DepositStatus(a)
}

View File

@ -116,6 +116,11 @@ const (
DepositStateSuspended DepositState = "suspended"
DepositStateAccepted DepositState = "accepted"
DepositStateChecking DepositState = "checking"
// v3 states
DepositStateProcessing DepositState = "processing"
DepositStateFailed DepositState = "failed"
DepositStateDone DepositState = "done"
)
type Deposit struct {

View File

@ -136,6 +136,12 @@ func (c *CancelOrderRequest) GetSlugsMap() (map[string]string, error) {
return slugs, nil
}
// GetPath returns the request path of the API
func (c *CancelOrderRequest) GetPath() string {
return "/api/v3/order"
}
// Do generates the request object and send the request object to the API endpoint
func (c *CancelOrderRequest) Do(ctx context.Context) (*max.Order, error) {
params, err := c.GetParameters()
@ -144,7 +150,9 @@ func (c *CancelOrderRequest) Do(ctx context.Context) (*max.Order, error) {
}
query := url.Values{}
apiURL := "/api/v3/order"
var apiURL string
apiURL = c.GetPath()
req, err := c.client.NewAuthenticatedRequest(ctx, "DELETE", apiURL, query, params)
if err != nil {
@ -157,8 +165,32 @@ func (c *CancelOrderRequest) Do(ctx context.Context) (*max.Order, error) {
}
var apiResponse max.Order
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return &apiResponse, nil
}

View File

@ -6,11 +6,10 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/c9s/bbgo/pkg/exchange/max/maxapi"
"net/url"
"reflect"
"regexp"
max "github.com/c9s/bbgo/pkg/exchange/max/maxapi"
)
func (c *CancelWalletOrderAllRequest) Side(side string) *CancelWalletOrderAllRequest {
@ -166,6 +165,12 @@ func (c *CancelWalletOrderAllRequest) GetSlugsMap() (map[string]string, error) {
return slugs, nil
}
// GetPath returns the request path of the API
func (c *CancelWalletOrderAllRequest) GetPath() string {
return "/api/v3/wallet/:walletType/orders"
}
// Do generates the request object and send the request object to the API endpoint
func (c *CancelWalletOrderAllRequest) Do(ctx context.Context) ([]OrderCancelResponse, error) {
params, err := c.GetParameters()
@ -174,7 +179,9 @@ func (c *CancelWalletOrderAllRequest) Do(ctx context.Context) ([]OrderCancelResp
}
query := url.Values{}
apiURL := "/api/v3/wallet/:walletType/orders"
var apiURL string
apiURL = c.GetPath()
slugs, err := c.GetSlugsMap()
if err != nil {
return nil, err
@ -193,8 +200,32 @@ func (c *CancelWalletOrderAllRequest) Do(ctx context.Context) ([]OrderCancelResp
}
var apiResponse []OrderCancelResponse
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return apiResponse, nil
}

View File

@ -236,6 +236,12 @@ func (c *CreateWalletOrderRequest) GetSlugsMap() (map[string]string, error) {
return slugs, nil
}
// GetPath returns the request path of the API
func (c *CreateWalletOrderRequest) GetPath() string {
return "/api/v3/wallet/:walletType/order"
}
// Do generates the request object and send the request object to the API endpoint
func (c *CreateWalletOrderRequest) Do(ctx context.Context) (*max.Order, error) {
params, err := c.GetParameters()
@ -244,7 +250,9 @@ func (c *CreateWalletOrderRequest) Do(ctx context.Context) (*max.Order, error) {
}
query := url.Values{}
apiURL := "/api/v3/wallet/:walletType/order"
var apiURL string
apiURL = c.GetPath()
slugs, err := c.GetSlugsMap()
if err != nil {
return nil, err
@ -263,8 +271,32 @@ func (c *CreateWalletOrderRequest) Do(ctx context.Context) (*max.Order, error) {
}
var apiResponse max.Order
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return &apiResponse, nil
}

View File

@ -109,13 +109,21 @@ func (g *GetMarginADRatioRequest) GetSlugsMap() (map[string]string, error) {
return slugs, nil
}
// GetPath returns the request path of the API
func (g *GetMarginADRatioRequest) GetPath() string {
return "/api/v3/wallet/m/ad_ratio"
}
// Do generates the request object and send the request object to the API endpoint
func (g *GetMarginADRatioRequest) Do(ctx context.Context) (*ADRatio, error) {
// no body params
var params interface{}
query := url.Values{}
apiURL := "/api/v3/wallet/m/ad_ratio"
var apiURL string
apiURL = g.GetPath()
req, err := g.client.NewAuthenticatedRequest(ctx, "GET", apiURL, query, params)
if err != nil {
@ -128,8 +136,32 @@ func (g *GetMarginADRatioRequest) Do(ctx context.Context) (*ADRatio, error) {
}
var apiResponse ADRatio
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return &apiResponse, nil
}

View File

@ -136,6 +136,12 @@ func (g *GetOrderRequest) GetSlugsMap() (map[string]string, error) {
return slugs, nil
}
// GetPath returns the request path of the API
func (g *GetOrderRequest) GetPath() string {
return "/api/v3/order"
}
// Do generates the request object and send the request object to the API endpoint
func (g *GetOrderRequest) Do(ctx context.Context) (*max.Order, error) {
// empty params for GET operation
@ -145,7 +151,9 @@ func (g *GetOrderRequest) Do(ctx context.Context) (*max.Order, error) {
return nil, err
}
apiURL := "/api/v3/order"
var apiURL string
apiURL = g.GetPath()
req, err := g.client.NewAuthenticatedRequest(ctx, "GET", apiURL, query, params)
if err != nil {
@ -158,8 +166,32 @@ func (g *GetOrderRequest) Do(ctx context.Context) (*max.Order, error) {
}
var apiResponse max.Order
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return &apiResponse, nil
}

View File

@ -135,6 +135,12 @@ func (g *GetOrderTradesRequest) GetSlugsMap() (map[string]string, error) {
return slugs, nil
}
// GetPath returns the request path of the API
func (g *GetOrderTradesRequest) GetPath() string {
return "/api/v3/order/trades"
}
// Do generates the request object and send the request object to the API endpoint
func (g *GetOrderTradesRequest) Do(ctx context.Context) ([]Trade, error) {
// empty params for GET operation
@ -144,7 +150,9 @@ func (g *GetOrderTradesRequest) Do(ctx context.Context) ([]Trade, error) {
return nil, err
}
apiURL := "/api/v3/order/trades"
var apiURL string
apiURL = g.GetPath()
req, err := g.client.NewAuthenticatedRequest(ctx, "GET", apiURL, query, params)
if err != nil {
@ -157,8 +165,32 @@ func (g *GetOrderTradesRequest) Do(ctx context.Context) ([]Trade, error) {
}
var apiResponse []Trade
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return apiResponse, nil
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
package mysql
import (
"context"
"github.com/c9s/rockhopper/v2"
)
func init() {
AddMigration("main", up_main_addPositionIndex, down_main_addPositionIndex)
}
func up_main_addPositionIndex(ctx context.Context, tx rockhopper.SQLExecutor) (err error) {
// This code is executed when the migration is applied.
_, err = tx.ExecContext(ctx, "CREATE INDEX positions_traded_at ON positions (traded_at, profit);")
if err != nil {
return err
}
return err
}
func down_main_addPositionIndex(ctx context.Context, tx rockhopper.SQLExecutor) (err error) {
// This code is executed when the migration is rolled back.
_, err = tx.ExecContext(ctx, "DROP INDEX positions_traded_at ON positions;")
if err != nil {
return err
}
return err
}

View File

@ -0,0 +1,29 @@
package sqlite3
import (
"context"
"github.com/c9s/rockhopper/v2"
)
func init() {
AddMigration("main", up_main_addPositionIndex, down_main_addPositionIndex)
}
func up_main_addPositionIndex(ctx context.Context, tx rockhopper.SQLExecutor) (err error) {
// This code is executed when the migration is applied.
_, err = tx.ExecContext(ctx, "CREATE INDEX positions_traded_at ON positions (traded_at, profit);")
if err != nil {
return err
}
return err
}
func down_main_addPositionIndex(ctx context.Context, tx rockhopper.SQLExecutor) (err error) {
// This code is executed when the migration is rolled back.
_, err = tx.ExecContext(ctx, "DROP INDEX positions_traded_at;")
if err != nil {
return err
}
return err
}

View File

@ -77,7 +77,7 @@ type Strategy struct {
// boll is the BOLLINGER indicator we used for predicting the price.
boll *indicator.BOLL
CancelProfitOrdersOnShutdown bool `json: "shutdownCancelProfitOrders"`
CancelProfitOrdersOnShutdown bool `json:"shutdownCancelProfitOrders"`
}
func (s *Strategy) ID() string {

View File

@ -27,6 +27,10 @@ func (s *Strategy) placeTakeProfitOrders(ctx context.Context) error {
}
roundPosition := types.NewPositionFromMarket(s.Market)
roundPosition.SetExchangeFeeRate(s.ExchangeSession.ExchangeName, types.ExchangeFee{
MakerFeeRate: s.ExchangeSession.MakerFeeRate,
TakerFeeRate: s.ExchangeSession.TakerFeeRate,
})
for _, trade := range trades {
s.logger.Infof("add trade into the position of this round %s", trade.String())

View File

@ -236,7 +236,7 @@ func (s *Strategy) scanDepositHistory(ctx context.Context, asset string, duratio
s.watchingDeposits[deposit.TransactionID] = deposit
}
} else {
// ignore all initial deposit history that are already success
// ignore all initial deposits that are already in success status
logger.Infof("ignored succeess deposit: %s %+v", deposit.TransactionID, deposit)
}

View File

@ -440,9 +440,9 @@ for t in 1 .. n:
return argmax(alpha[t,si] over si)
*/
func hmm(y_t []float64, x_t []float64, l int) float64 {
al := make([]float64, l)
an := make([]float64, l)
as := make([]float64, l)
al := make([]float64, 0, l)
an := make([]float64, 0, l)
as := make([]float64, 0, l)
long := 0.
neut := 0.
short := 0.
@ -453,9 +453,9 @@ func hmm(y_t []float64, x_t []float64, l int) float64 {
sin := make([]float64, 3)
sis := make([]float64, 3)
for i := -1; i <= 1; i++ {
sil = append(sil, x_t[n-1-1]*transitProbability(i, j))
sin = append(sin, x_t[n-1-1]*transitProbability(i, j))
sis = append(sis, x_t[n-1-1]*transitProbability(i, j))
sil = append(sil, 0, x_t[n-1-1]*transitProbability(i, j))
sin = append(sin, 0, x_t[n-1-1]*transitProbability(i, j))
sis = append(sis, 0, x_t[n-1-1]*transitProbability(i, j))
}
if j > 0 {
_, longArr := floats.MinMax(sil, 3)

View File

@ -0,0 +1,111 @@
package xmaker
import (
"context"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
var tradeVolumeWindowSignalMetrics = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "xmaker_trade_volume_window_signal",
Help: "",
}, []string{"symbol"})
func init() {
prometheus.MustRegister(tradeVolumeWindowSignalMetrics)
}
type TradeVolumeWindowSignal struct {
Threshold fixedpoint.Value `json:"threshold"`
Window types.Duration `json:"window"`
trades []types.Trade
symbol string
mu sync.Mutex
}
func (s *TradeVolumeWindowSignal) handleTrade(trade types.Trade) {
s.mu.Lock()
s.trades = append(s.trades, trade)
s.mu.Unlock()
}
func (s *TradeVolumeWindowSignal) Bind(ctx context.Context, session *bbgo.ExchangeSession, symbol string) error {
s.symbol = symbol
if s.Window == 0 {
s.Window = types.Duration(time.Minute)
}
if s.Threshold.IsZero() {
s.Threshold = fixedpoint.NewFromFloat(0.7)
}
session.MarketDataStream.OnMarketTrade(s.handleTrade)
return nil
}
func (s *TradeVolumeWindowSignal) filterTrades(now time.Time) []types.Trade {
startTime := now.Add(-time.Duration(s.Window))
startIdx := 0
s.mu.Lock()
defer s.mu.Unlock()
for idx, td := range s.trades {
// skip trades before the start time
if td.Time.Before(startTime) {
continue
}
startIdx = idx
break
}
trades := s.trades[startIdx:]
s.trades = trades
return trades
}
func (s *TradeVolumeWindowSignal) aggTradeVolume(trades []types.Trade) (buyVolume, sellVolume float64) {
for _, td := range trades {
if td.IsBuyer {
buyVolume += td.Quantity.Float64()
} else {
sellVolume += td.Quantity.Float64()
}
}
return buyVolume, sellVolume
}
func (s *TradeVolumeWindowSignal) CalculateSignal(_ context.Context) (float64, error) {
now := time.Now()
trades := s.filterTrades(now)
buyVolume, sellVolume := s.aggTradeVolume(trades)
totalVolume := buyVolume + sellVolume
threshold := s.Threshold.Float64()
buyRatio := buyVolume / totalVolume
sellRatio := sellVolume / totalVolume
sig := 0.0
if buyRatio > threshold {
sig = (buyRatio - threshold) / 2.0
} else if sellRatio > threshold {
sig = -(sellRatio - threshold) / 2.0
}
log.Infof("[TradeVolumeWindowSignal] %f buy/sell = %f/%f", sig, buyVolume, sellVolume)
tradeVolumeWindowSignalMetrics.WithLabelValues(s.symbol).Set(sig)
return sig, nil
}

View File

@ -0,0 +1,55 @@
package xmaker
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
. "github.com/c9s/bbgo/pkg/testing/testhelper"
)
var tradeId = 0
func Trade(symbol string, side types.SideType, price, quantity fixedpoint.Value, t time.Time) types.Trade {
tradeId++
return types.Trade{
ID: uint64(tradeId),
Symbol: symbol,
Side: side,
Price: price,
IsBuyer: side == types.SideTypeBuy,
Quantity: quantity,
Time: types.Time(t),
}
}
func TestMarketTradeWindowSignal(t *testing.T) {
now := time.Now()
symbol := "BTCUSDT"
sig := &TradeVolumeWindowSignal{
symbol: symbol,
Threshold: fixedpoint.NewFromFloat(0.65),
Window: types.Duration(time.Minute),
}
sig.trades = []types.Trade{
Trade(symbol, types.SideTypeBuy, Number(18000.0), Number(1.0), now.Add(-2*time.Minute)),
Trade(symbol, types.SideTypeSell, Number(18000.0), Number(0.5), now.Add(-2*time.Second)),
Trade(symbol, types.SideTypeBuy, Number(18000.0), Number(1.0), now.Add(-1*time.Second)),
}
ctx := context.Background()
sigNum, err := sig.CalculateSignal(ctx)
if assert.NoError(t, err) {
// buy ratio: 1/1.5 = 0.6666666666666666
// sell ratio: 0.5/1.5 = 0.3333333333333333
assert.InDelta(t, 0.0083333, sigNum, 0.0001)
}
assert.Len(t, sig.trades, 2)
}

View File

@ -65,6 +65,7 @@ type SignalConfig struct {
BollingerBandTrendSignal *BollingerBandTrendSignal `json:"bollingerBandTrend,omitempty"`
OrderBookBestPriceSignal *OrderBookBestPriceVolumeSignal `json:"orderBookBestPrice,omitempty"`
KLineShapeSignal *KLineShapeSignal `json:"klineShape,omitempty"`
TradeVolumeWindowSignal *TradeVolumeWindowSignal `json:"tradeVolumeWindow,omitempty"`
}
func init() {
@ -90,11 +91,12 @@ type Strategy struct {
SignalConfigList []SignalConfig `json:"signals"`
SignalMarginScale *bbgo.SlideRule `json:"signalMarginScale,omitempty"`
Margin fixedpoint.Value `json:"margin"`
BidMargin fixedpoint.Value `json:"bidMargin"`
AskMargin fixedpoint.Value `json:"askMargin"`
UseDepthPrice bool `json:"useDepthPrice"`
DepthQuantity fixedpoint.Value `json:"depthQuantity"`
Margin fixedpoint.Value `json:"margin"`
BidMargin fixedpoint.Value `json:"bidMargin"`
AskMargin fixedpoint.Value `json:"askMargin"`
UseDepthPrice bool `json:"useDepthPrice"`
DepthQuantity fixedpoint.Value `json:"depthQuantity"`
SourceDepthLevel types.Depth `json:"sourceDepthLevel"`
EnableBollBandMargin bool `json:"enableBollBandMargin"`
BollBandInterval types.Interval `json:"bollBandInterval"`
@ -125,6 +127,8 @@ type Strategy struct {
NotifyTrade bool `json:"notifyTrade"`
EnableArbitrage bool `json:"arbitrage"`
// RecoverTrade tries to find the missing trades via the REStful API
RecoverTrade bool `json:"recoverTrade"`
@ -158,8 +162,8 @@ type Strategy struct {
ProfitStats *ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
CoveredPosition fixedpoint.Value `json:"coveredPosition,omitempty" persistence:"covered_position"`
book *types.StreamOrderBook
activeMakerOrders *bbgo.ActiveOrderBook
sourceBook, makerBook *types.StreamOrderBook
activeMakerOrders *bbgo.ActiveOrderBook
hedgeErrorLimiter *rate.Limiter
hedgeErrorRateReservation *rate.Reservation
@ -198,14 +202,33 @@ func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {
panic(fmt.Errorf("source session %s is not defined", s.SourceExchange))
}
sourceSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{})
sourceSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{
// TODO: fix depth20 stream for binance
// Depth: s.SourceDepthLevel,
})
sourceSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
makerSession, ok := sessions[s.MakerExchange]
if !ok {
panic(fmt.Errorf("maker session %s is not defined", s.MakerExchange))
}
makerSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
if s.EnableArbitrage {
makerSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{
Depth: types.DepthLevelMedium,
})
}
for _, sig := range s.SignalConfigList {
if sig.TradeVolumeWindowSignal != nil {
sourceSession.Subscribe(types.MarketTradeChannel, s.Symbol, types.SubscribeOptions{})
} else if sig.BollingerBandTrendSignal != nil {
sourceSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: sig.BollingerBandTrendSignal.Interval})
}
}
}
func aggregatePrice(pvs types.PriceVolumeSlice, requiredQuantity fixedpoint.Value) (price fixedpoint.Value) {
@ -263,7 +286,7 @@ func (s *Strategy) getBollingerTrend(quote *Quote) int {
}
func (s *Strategy) applySignalMargin(ctx context.Context, quote *Quote) error {
signal, err := s.calculateSignal(ctx)
signal, err := s.aggregateSignal(ctx)
if err != nil {
return err
}
@ -359,65 +382,140 @@ func (s *Strategy) applyBollingerMargin(
return nil
}
func (s *Strategy) calculateSignal(ctx context.Context) (float64, error) {
func (s *Strategy) aggregateSignal(ctx context.Context) (float64, error) {
sum := 0.0
voters := 0.0
for _, signal := range s.SignalConfigList {
var sig float64
var err error
if signal.OrderBookBestPriceSignal != nil {
sig, err := signal.OrderBookBestPriceSignal.CalculateSignal(ctx)
if err != nil {
return 0, err
}
if sig == 0.0 {
continue
}
if signal.Weight > 0.0 {
sum += sig * signal.Weight
voters += signal.Weight
} else {
sum += sig
voters++
}
sig, err = signal.OrderBookBestPriceSignal.CalculateSignal(ctx)
} else if signal.BollingerBandTrendSignal != nil {
sig, err := signal.BollingerBandTrendSignal.CalculateSignal(ctx)
if err != nil {
return 0, err
}
if sig == 0.0 {
continue
}
if signal.Weight > 0.0 {
sum += sig * signal.Weight
voters += signal.Weight
} else {
sum += sig
voters++
}
sig, err = signal.BollingerBandTrendSignal.CalculateSignal(ctx)
} else if signal.TradeVolumeWindowSignal != nil {
sig, err = signal.TradeVolumeWindowSignal.CalculateSignal(ctx)
}
if err != nil {
return 0, err
} else if sig == 0.0 {
continue
}
if signal.Weight > 0.0 {
sum += sig * signal.Weight
voters += signal.Weight
} else {
sum += sig
voters++
}
}
if sum == 0.0 {
return 0.0, nil
}
return sum / voters, nil
}
func (s *Strategy) updateQuote(ctx context.Context) {
// getInitialLayerQuantity returns the initial quantity for the layer
// i is the layer index, starting from 0
func (s *Strategy) getInitialLayerQuantity(i int) (fixedpoint.Value, error) {
if s.QuantityScale != nil {
qf, err := s.QuantityScale.Scale(i + 1)
if err != nil {
return fixedpoint.Zero, fmt.Errorf("quantityScale error: %w", err)
}
log.Infof("%s scaling bid #%d quantity to %f", s.Symbol, i+1, qf)
// override the default quantity
return fixedpoint.NewFromFloat(qf), nil
}
q := s.Quantity
if s.QuantityMultiplier.Sign() > 0 && i > 0 {
q = fixedpoint.NewFromFloat(
q.Float64() * math.Pow(
s.QuantityMultiplier.Float64(), float64(i+1)))
}
// fallback to the fixed quantity
return q, nil
}
// getLayerPrice returns the price for the layer
// i is the layer index, starting from 0
// side is the side of the order
// sourceBook is the source order book
func (s *Strategy) getLayerPrice(
i int,
side types.SideType,
sourceBook *types.StreamOrderBook,
quote *Quote,
requiredDepth fixedpoint.Value,
) (price fixedpoint.Value) {
var margin, delta, pips fixedpoint.Value
switch side {
case types.SideTypeSell:
margin = quote.AskMargin
delta = margin
if quote.AskLayerPips.Sign() > 0 {
pips = quote.AskLayerPips
} else {
pips = fixedpoint.One
}
case types.SideTypeBuy:
margin = quote.BidMargin
delta = margin.Neg()
if quote.BidLayerPips.Sign() > 0 {
pips = quote.BidLayerPips.Neg()
} else {
pips = fixedpoint.One.Neg()
}
}
sideBook := sourceBook.SideBook(side)
if pv, ok := sideBook.First(); ok {
price = pv.Price
}
if requiredDepth.Sign() > 0 {
price = aggregatePrice(sideBook, requiredDepth)
price = price.Mul(fixedpoint.One.Add(delta))
if i > 0 {
price = price.Add(pips.Mul(s.makerMarket.TickSize))
}
} else {
price = price.Mul(fixedpoint.One.Add(delta))
if i > 0 {
price = price.Add(pips.Mul(s.makerMarket.TickSize))
}
}
return price
}
func (s *Strategy) updateQuote(ctx context.Context) error {
if err := s.activeMakerOrders.GracefulCancel(ctx, s.makerSession.Exchange); err != nil {
s.logger.Warnf("there are some %s orders not canceled, skipping placing maker orders", s.Symbol)
s.activeMakerOrders.Print()
return
return nil
}
if s.activeMakerOrders.NumOfOrders() > 0 {
return
s.logger.Warnf("unable to cancel all %s orders, skipping placing maker orders", s.Symbol)
return nil
}
signal, err := s.calculateSignal(ctx)
signal, err := s.aggregateSignal(ctx)
if err != nil {
return
return err
}
s.logger.Infof("aggregated signal: %f", signal)
@ -432,14 +530,25 @@ func (s *Strategy) updateQuote(ctx context.Context) {
bbgo.Notify("Strategy %s is halted, reason: %s", ID, reason)
}
return
return nil
}
}
bestBid, bestAsk, hasPrice := s.book.BestBidAndAsk()
bestBid, bestAsk, hasPrice := s.sourceBook.BestBidAndAsk()
if !hasPrice {
s.logger.Warnf("no valid price, skip quoting")
return
return fmt.Errorf("no valid book price")
}
bestBidPrice := bestBid.Price
bestAskPrice := bestAsk.Price
s.logger.Infof("%s book ticker: best ask / best bid = %v / %v", s.Symbol, bestAskPrice, bestBidPrice)
if bestBidPrice.Compare(bestAskPrice) > 0 {
return fmt.Errorf("best bid price %f is higher than best ask price %f, skip quoting",
bestBidPrice.Float64(),
bestAskPrice.Float64(),
)
}
// use mid-price for the last price
@ -447,26 +556,26 @@ func (s *Strategy) updateQuote(ctx context.Context) {
s.priceSolver.Update(s.Symbol, s.lastPrice)
bookLastUpdateTime := s.book.LastUpdateTime()
bookLastUpdateTime := s.sourceBook.LastUpdateTime()
if _, err := s.bidPriceHeartBeat.Update(bestBid); err != nil {
s.logger.WithError(err).Errorf("quote update error, %s price not updating, order book last update: %s ago",
s.Symbol,
time.Since(bookLastUpdateTime))
return
return err
}
if _, err := s.askPriceHeartBeat.Update(bestAsk); err != nil {
s.logger.WithError(err).Errorf("quote update error, %s price not updating, order book last update: %s ago",
s.Symbol,
time.Since(bookLastUpdateTime))
return
return err
}
sourceBook := s.book.CopyDepth(10)
sourceBook := s.sourceBook.CopyDepth(10)
if valid, err := sourceBook.IsValid(); !valid {
s.logger.WithError(err).Errorf("%s invalid copied order book, skip quoting: %v", s.Symbol, err)
return
return err
}
var disableMakerBid = false
@ -637,25 +746,11 @@ func (s *Strategy) updateQuote(ctx context.Context) {
if disableMakerAsk && disableMakerBid {
log.Warnf("%s bid/ask maker is disabled due to insufficient balances", s.Symbol)
return
}
bestBidPrice := bestBid.Price
bestAskPrice := bestAsk.Price
s.logger.Infof("%s book ticker: best ask / best bid = %v / %v", s.Symbol, bestAskPrice, bestBidPrice)
if bestBidPrice.Compare(bestAskPrice) > 0 {
log.Errorf("best bid price %f is higher than best ask price %f, skip quoting",
bestBidPrice.Float64(),
bestAskPrice.Float64(),
)
return
return nil
}
var submitOrders []types.SubmitOrder
var accumulativeBidQuantity, accumulativeAskQuantity fixedpoint.Value
var bidQuantity = s.Quantity
var askQuantity = s.Quantity
var quote = &Quote{
BestBidPrice: bestBidPrice,
@ -679,61 +774,40 @@ func (s *Strategy) updateQuote(ctx context.Context) {
bidExposureInUsd := fixedpoint.Zero
askExposureInUsd := fixedpoint.Zero
bidPrice := quote.BestBidPrice
askPrice := quote.BestAskPrice
if bidPrice.Compare(askPrice) > 0 {
log.Errorf("maker bid price %f is higher than maker ask price %f, skip quoting",
bidPrice.Float64(),
askPrice.Float64(),
)
return
}
bidMarginMetrics.With(s.metricsLabels).Set(quote.BidMargin.Float64())
askMarginMetrics.With(s.metricsLabels).Set(quote.AskMargin.Float64())
for i := 0; i < s.NumLayers; i++ {
// for maker bid orders
if !disableMakerBid {
if s.QuantityScale != nil {
qf, err := s.QuantityScale.Scale(i + 1)
if err != nil {
log.WithError(err).Errorf("quantityScale error")
return
}
if s.EnableArbitrage {
done, err := s.tryArbitrage(ctx, quote, makerBalances, hedgeBalances)
if err != nil {
s.logger.WithError(err).Errorf("unable to arbitrage")
} else if done {
return nil
}
}
log.Infof("%s scaling bid #%d quantity to %f", s.Symbol, i+1, qf)
// override the default bid quantity
bidQuantity = fixedpoint.NewFromFloat(qf)
if !disableMakerBid {
for i := 0; i < s.NumLayers; i++ {
bidQuantity, err := s.getInitialLayerQuantity(i)
if err != nil {
return err
}
// for maker bid orders
accumulativeBidQuantity = accumulativeBidQuantity.Add(bidQuantity)
requiredDepth := fixedpoint.Zero
if s.UseDepthPrice {
sideBook := sourceBook.SideBook(types.SideTypeBuy)
if s.DepthQuantity.Sign() > 0 {
if i == 0 {
bidPrice = aggregatePrice(sideBook, s.DepthQuantity)
bidPrice = bidPrice.Mul(fixedpoint.One.Sub(quote.BidMargin))
} else if i > 0 && quote.BidLayerPips.Sign() > 0 {
pips := quote.BidLayerPips.Mul(s.makerMarket.TickSize)
bidPrice = bidPrice.Sub(pips)
}
requiredDepth = s.DepthQuantity
} else {
bidPrice = aggregatePrice(sideBook, accumulativeBidQuantity)
bidPrice = bidPrice.Mul(fixedpoint.One.Sub(quote.BidMargin))
}
} else {
if i == 0 {
bidPrice = bidPrice.Mul(fixedpoint.One.Sub(quote.BidMargin))
} else if i > 0 && quote.BidLayerPips.Sign() > 0 {
pips := quote.BidLayerPips.Mul(s.makerMarket.TickSize)
bidPrice = bidPrice.Sub(pips)
requiredDepth = accumulativeBidQuantity
}
}
bidPrice := s.getLayerPrice(i, types.SideTypeBuy, s.sourceBook, quote, requiredDepth)
if i == 0 {
s.logger.Infof("maker best bid price %f", bidPrice.Float64())
makerBestBidPriceMetrics.With(s.metricsLabels).Set(bidPrice.Float64())
@ -759,49 +833,30 @@ func (s *Strategy) updateQuote(ctx context.Context) {
hedgeQuota.Rollback()
}
if s.QuantityMultiplier.Sign() > 0 {
bidQuantity = bidQuantity.Mul(s.QuantityMultiplier)
}
}
}
// for maker ask orders
if !disableMakerAsk {
if s.QuantityScale != nil {
qf, err := s.QuantityScale.Scale(i + 1)
if err != nil {
log.WithError(err).Errorf("quantityScale error")
return
}
log.Infof("%s scaling ask #%d quantity to %f", s.Symbol, i+1, qf)
// override the default bid quantity
askQuantity = fixedpoint.NewFromFloat(qf)
// for maker ask orders
if !disableMakerAsk {
for i := 0; i < s.NumLayers; i++ {
askQuantity, err := s.getInitialLayerQuantity(i)
if err != nil {
return err
}
accumulativeAskQuantity = accumulativeAskQuantity.Add(askQuantity)
requiredDepth := fixedpoint.Zero
if s.UseDepthPrice {
if s.DepthQuantity.Sign() > 0 {
if i == 0 {
askPrice = aggregatePrice(sourceBook.SideBook(types.SideTypeSell), s.DepthQuantity)
askPrice = askPrice.Mul(fixedpoint.One.Add(quote.AskMargin))
} else if i > 0 && quote.AskLayerPips.Sign() > 0 {
pips := quote.AskLayerPips.Mul(s.makerMarket.TickSize)
askPrice = askPrice.Add(pips)
}
requiredDepth = s.DepthQuantity
} else {
askPrice = aggregatePrice(sourceBook.SideBook(types.SideTypeSell), accumulativeAskQuantity)
askPrice = askPrice.Mul(fixedpoint.One.Add(quote.AskMargin))
}
} else {
if i == 0 {
askPrice = askPrice.Mul(fixedpoint.One.Add(quote.AskMargin))
} else if i > 0 && quote.AskLayerPips.Sign() > 0 {
pips := quote.AskLayerPips.Mul(s.makerMarket.TickSize)
askPrice = askPrice.Add(pips)
requiredDepth = accumulativeAskQuantity
}
}
askPrice := s.getLayerPrice(i, types.SideTypeSell, s.sourceBook, quote, requiredDepth)
if i == 0 {
s.logger.Infof("maker best ask price %f", askPrice.Float64())
makerBestAskPriceMetrics.With(s.metricsLabels).Set(askPrice.Float64())
@ -837,25 +892,20 @@ func (s *Strategy) updateQuote(ctx context.Context) {
if len(submitOrders) == 0 {
log.Warnf("no orders generated")
return
return nil
}
formattedOrders, err := s.makerSession.FormatOrders(submitOrders)
if err != nil {
return
}
orderCreateCallback := func(createdOrder types.Order) {
s.orderStore.Add(createdOrder)
s.activeMakerOrders.Add(createdOrder)
return err
}
defer s.tradeCollector.Process()
createdOrders, errIdx, err := bbgo.BatchPlaceOrder(ctx, s.makerSession.Exchange, orderCreateCallback, formattedOrders...)
createdOrders, errIdx, err := bbgo.BatchPlaceOrder(ctx, s.makerSession.Exchange, s.makerOrderCreateCallback, formattedOrders...)
if err != nil {
log.WithError(err).Errorf("unable to place maker orders: %+v", formattedOrders)
return
return err
}
openOrderBidExposureInUsdMetrics.With(s.metricsLabels).Set(bidExposureInUsd.Float64())
@ -863,6 +913,121 @@ func (s *Strategy) updateQuote(ctx context.Context) {
_ = errIdx
_ = createdOrders
return nil
}
func (s *Strategy) makerOrderCreateCallback(createdOrder types.Order) {
s.orderStore.Add(createdOrder)
s.activeMakerOrders.Add(createdOrder)
}
func aggregatePriceVolumeSliceWithPriceFilter(pvs types.PriceVolumeSlice, filterPrice fixedpoint.Value) types.PriceVolume {
var totalVolume = fixedpoint.Zero
var lastPrice = fixedpoint.Zero
for _, pv := range pvs {
if pv.Price.Compare(filterPrice) > 0 {
break
}
lastPrice = pv.Price
totalVolume = totalVolume.Add(pv.Volume)
}
return types.PriceVolume{
Price: lastPrice,
Volume: totalVolume,
}
}
// tryArbitrage tries to arbitrage between the source and maker exchange
func (s *Strategy) tryArbitrage(ctx context.Context, quote *Quote, makerBalances, hedgeBalances types.BalanceMap) (bool, error) {
marginBidPrice := quote.BestBidPrice.Mul(fixedpoint.One.Sub(quote.BidMargin))
marginAskPrice := quote.BestAskPrice.Mul(fixedpoint.One.Add(quote.AskMargin))
makerBid, makerAsk, ok := s.makerBook.BestBidAndAsk()
if !ok {
return false, nil
}
var iocOrders []types.SubmitOrder
if makerAsk.Price.Compare(marginBidPrice) <= 0 {
quoteBalance, hasQuote := makerBalances[s.makerMarket.QuoteCurrency]
if !hasQuote {
return false, nil
}
askPvs := s.makerBook.SideBook(types.SideTypeSell)
sumPv := aggregatePriceVolumeSliceWithPriceFilter(askPvs, marginBidPrice)
qty := fixedpoint.Min(quoteBalance.Available.Div(sumPv.Price), sumPv.Volume)
if sourceBase, ok := hedgeBalances[s.sourceMarket.BaseCurrency]; ok {
qty = fixedpoint.Min(qty, sourceBase.Available)
} else {
// insufficient hedge base balance for arbitrage
return false, nil
}
iocOrders = append(iocOrders, types.SubmitOrder{
Symbol: s.Symbol,
Type: types.OrderTypeLimit,
Side: types.SideTypeBuy,
Price: sumPv.Price,
Quantity: qty,
TimeInForce: types.TimeInForceIOC,
})
} else if makerBid.Price.Compare(marginAskPrice) >= 0 {
baseBalance, hasBase := makerBalances[s.makerMarket.BaseCurrency]
if !hasBase {
return false, nil
}
bidPvs := s.makerBook.SideBook(types.SideTypeBuy)
sumPv := aggregatePriceVolumeSliceWithPriceFilter(bidPvs, marginAskPrice)
qty := fixedpoint.Min(baseBalance.Available, sumPv.Volume)
if sourceQuote, ok := hedgeBalances[s.sourceMarket.QuoteCurrency]; ok {
qty = fixedpoint.Min(qty, quote.BestAskPrice.Div(sourceQuote.Available))
} else {
// insufficient hedge quote balance for arbitrage
return false, nil
}
// send ioc order for arbitrage
iocOrders = append(iocOrders, types.SubmitOrder{
Symbol: s.Symbol,
Type: types.OrderTypeLimit,
Side: types.SideTypeSell,
Price: sumPv.Price,
Quantity: qty,
TimeInForce: types.TimeInForceIOC,
})
}
if len(iocOrders) == 0 {
return false, nil
}
// send ioc order for arbitrage
formattedOrders, err := s.makerSession.FormatOrders(iocOrders)
if err != nil {
return false, err
}
defer s.tradeCollector.Process()
createdOrders, _, err := bbgo.BatchPlaceOrder(
ctx,
s.makerSession.Exchange,
s.makerOrderCreateCallback,
formattedOrders...)
if err != nil {
return len(createdOrders) > 0, err
}
s.logger.Infof("sent arbitrage IOC order: %+v", createdOrders)
return true, nil
}
func (s *Strategy) adjustHedgeQuantityWithAvailableBalance(
@ -907,7 +1072,7 @@ func (s *Strategy) Hedge(ctx context.Context, pos fixedpoint.Value) {
}
lastPrice := s.lastPrice
sourceBook := s.book.CopyDepth(1)
sourceBook := s.sourceBook.CopyDepth(1)
switch side {
case types.SideTypeBuy:
@ -1030,6 +1195,10 @@ func (s *Strategy) Defaults() error {
s.BollBandInterval = types.Interval1m
}
if s.SourceDepthLevel == "" {
s.SourceDepthLevel = types.DepthLevelMedium
}
if s.BollBandMarginFactor.IsZero() {
s.BollBandMarginFactor = fixedpoint.One
}
@ -1086,7 +1255,7 @@ func (s *Strategy) Defaults() error {
}
func (s *Strategy) Validate() error {
if s.Quantity.IsZero() || s.QuantityScale == nil {
if s.Quantity.IsZero() && s.QuantityScale == nil {
return errors.New("quantity or quantityScale can not be empty")
}
@ -1351,8 +1520,11 @@ func (s *Strategy) CrossRun(
s.ProfitStats.ProfitStats = profitStats
}
s.book = types.NewStreamBook(s.Symbol, s.sourceSession.ExchangeName)
s.book.BindStream(s.sourceSession.MarketDataStream)
s.makerBook = types.NewStreamBook(s.Symbol, s.makerSession.ExchangeName)
s.makerBook.BindStream(s.makerSession.MarketDataStream)
s.sourceBook = types.NewStreamBook(s.Symbol, s.sourceSession.ExchangeName)
s.sourceBook.BindStream(s.sourceSession.MarketDataStream)
if s.EnableSignalMargin {
scale, err := s.SignalMarginScale.Scale()
@ -1366,7 +1538,7 @@ func (s *Strategy) CrossRun(
for _, signalConfig := range s.SignalConfigList {
if signalConfig.OrderBookBestPriceSignal != nil {
signalConfig.OrderBookBestPriceSignal.book = s.book
signalConfig.OrderBookBestPriceSignal.book = s.sourceBook
if err := signalConfig.OrderBookBestPriceSignal.Bind(ctx, s.sourceSession, s.Symbol); err != nil {
return err
}
@ -1374,6 +1546,10 @@ func (s *Strategy) CrossRun(
if err := signalConfig.BollingerBandTrendSignal.Bind(ctx, s.sourceSession, s.Symbol); err != nil {
return err
}
} else if signalConfig.TradeVolumeWindowSignal != nil {
if err := signalConfig.TradeVolumeWindowSignal.Bind(ctx, s.sourceSession, s.Symbol); err != nil {
return err
}
}
}

View File

@ -2,28 +2,89 @@ package xmaker
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/stretchr/testify/assert"
. "github.com/c9s/bbgo/pkg/testing/testhelper"
)
func Test_aggregatePrice(t *testing.T) {
bids := types.PriceVolumeSlice{
{
Price: fixedpoint.NewFromFloat(1000.0),
Volume: fixedpoint.NewFromFloat(1.0),
},
{
Price: fixedpoint.NewFromFloat(1200.0),
Volume: fixedpoint.NewFromFloat(1.0),
},
{
Price: fixedpoint.NewFromFloat(1400.0),
Volume: fixedpoint.NewFromFloat(1.0),
},
func TestStrategy_getLayerPrice(t *testing.T) {
symbol := "BTCUSDT"
market := Market(symbol)
s := &Strategy{
UseDepthPrice: true,
DepthQuantity: Number(3.0),
makerMarket: market,
}
sourceBook := types.NewStreamBook(symbol, types.ExchangeBinance)
sourceBook.Load(types.SliceOrderBook{
Symbol: symbol,
Bids: PriceVolumeSlice(
Number(1300.0), Number(1.0),
Number(1200.0), Number(2.0),
Number(1100.0), Number(3.0),
),
Asks: PriceVolumeSlice(
Number(1301.0), Number(1.0),
Number(1400.0), Number(2.0),
Number(1500.0), Number(3.0),
),
Time: time.Time{},
LastUpdateId: 1,
})
quote := &Quote{
BestBidPrice: Number(1300.0),
BestAskPrice: Number(1301.0),
BidMargin: Number(0.001),
AskMargin: Number(0.001),
BidLayerPips: Number(100.0),
AskLayerPips: Number(100.0),
}
t.Run("depthPrice bid price at 0", func(t *testing.T) {
price := s.getLayerPrice(0, types.SideTypeBuy, sourceBook, quote, s.DepthQuantity)
// (1300 + 1200*2)/3 * (1 - 0.001)
assert.InDelta(t, 1232.10, price.Float64(), 0.01)
})
t.Run("depthPrice bid price at 1", func(t *testing.T) {
price := s.getLayerPrice(1, types.SideTypeBuy, sourceBook, quote, s.DepthQuantity)
// (1300 + 1200*2)/3 * (1 - 0.001) - 100 * 0.01
assert.InDelta(t, 1231.10, price.Float64(), 0.01)
})
t.Run("depthPrice ask price at 0", func(t *testing.T) {
price := s.getLayerPrice(0, types.SideTypeSell, sourceBook, quote, s.DepthQuantity)
// (1301 + 1400*2)/3 * (1 + 0.001)
assert.InDelta(t, 1368.367, price.Float64(), 0.01)
})
t.Run("depthPrice ask price at 1", func(t *testing.T) {
price := s.getLayerPrice(1, types.SideTypeSell, sourceBook, quote, s.DepthQuantity)
// (1301 + 1400*2)/3 * (1 + 0.001) + 100 * 0.01
assert.InDelta(t, 1369.367, price.Float64(), 0.01)
})
}
func Test_aggregatePrice(t *testing.T) {
bids := PriceVolumeSliceFromText(`
1000.0, 1.0
1200.0, 1.0
1400.0, 1.0
`)
aggregatedPrice1 := aggregatePrice(bids, fixedpoint.NewFromFloat(0.5))
assert.Equal(t, fixedpoint.NewFromFloat(1000.0), aggregatedPrice1)

View File

@ -0,0 +1,43 @@
package testhelper
import (
"fmt"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
var markets = map[string]types.Market{
"BTCUSDT": {
Symbol: "BTCUSDT",
PricePrecision: 2,
VolumePrecision: 8,
QuoteCurrency: "USDT",
BaseCurrency: "BTC",
MinNotional: fixedpoint.MustNewFromString("0.001"),
MinAmount: fixedpoint.MustNewFromString("10.0"),
MinQuantity: fixedpoint.MustNewFromString("0.001"),
TickSize: fixedpoint.MustNewFromString("0.01"),
},
"ETHUSDT": {
Symbol: "ETH",
PricePrecision: 2,
VolumePrecision: 8,
QuoteCurrency: "USDT",
BaseCurrency: "ETH",
MinNotional: fixedpoint.MustNewFromString("0.005"),
MinAmount: fixedpoint.MustNewFromString("10.0"),
MinQuantity: fixedpoint.MustNewFromString("0.001"),
TickSize: fixedpoint.MustNewFromString("0.01"),
},
}
func Market(symbol string) types.Market {
market, ok := markets[symbol]
if !ok {
panic(fmt.Errorf("%s market not found, valid markets: %+v", symbol, markets))
}
return market
}

View File

@ -0,0 +1,49 @@
package testhelper
import (
"fmt"
"strings"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
func PriceVolumeSliceFromText(str string) (slice types.PriceVolumeSlice) {
lines := strings.Split(str, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
cols := strings.SplitN(line, ",", 2)
if len(cols) < 2 {
panic(fmt.Errorf("column length should be 2, got %d", len(cols)))
}
price := fixedpoint.MustNewFromString(strings.TrimSpace(cols[0]))
volume := fixedpoint.MustNewFromString(strings.TrimSpace(cols[1]))
slice = append(slice, types.PriceVolume{
Price: price,
Volume: volume,
})
}
return slice
}
func PriceVolumeSlice(values ...fixedpoint.Value) (slice types.PriceVolumeSlice) {
if len(values)%2 != 0 {
panic("values should be paired")
}
for i := 0; i < len(values); i += 2 {
slice = append(slice, types.PriceVolume{
Price: values[i],
Volume: values[i+1],
})
}
return slice
}

View File

@ -2,8 +2,9 @@ package types
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"testing"
"github.com/stretchr/testify/assert"
)
func TestKLineWindow_Tail(t *testing.T) {

View File

@ -13,6 +13,13 @@ type PriceVolume struct {
Price, Volume fixedpoint.Value
}
func NewPriceVolume(p, v fixedpoint.Value) PriceVolume {
return PriceVolume{
Price: p,
Volume: v,
}
}
func (p PriceVolume) InQuote() fixedpoint.Value {
return p.Price.Mul(p.Volume)
}

View File

@ -249,7 +249,7 @@ func (s *StandardStream) Read(ctx context.Context, conn *websocket.Conn, cancel
default:
if err := conn.SetReadDeadline(time.Now().Add(readTimeout)); err != nil {
log.WithError(err).Errorf("set read deadline error: %s", err.Error())
log.WithError(err).Errorf("unable to set read deadline: %v", err)
}
mt, message, err := conn.ReadMessage()
@ -300,7 +300,7 @@ func (s *StandardStream) Read(ctx context.Context, conn *websocket.Conn, cancel
var e interface{}
e, err = s.parser(message)
if err != nil {
log.WithError(err).Errorf("websocket event parse error, message: %s", message)
log.WithError(err).Errorf("unable to parse the websocket message. err: %v, message: %s", err, message)
// emit raw message even if occurs error, because we want anything can be detected
s.EmitRawMessage(message)
continue
@ -352,7 +352,7 @@ func (s *StandardStream) ping(
}
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeTimeout)); err != nil {
log.WithError(err).Error("ping error", err)
log.WithError(err).Warnf("unable to write ws control message, ping error: %v", err)
s.Reconnect()
return
}
@ -439,7 +439,7 @@ func (s *StandardStream) reconnector(ctx context.Context) {
log.Warnf("re-connecting...")
if err := s.DialAndConnect(ctx); err != nil {
log.WithError(err).Errorf("re-connect error, try to reconnect later")
log.WithError(err).Warnf("re-connect error: %v, will reconnect again later...", err)
// re-emit the re-connect signal if error
s.Reconnect()

View File

@ -3,6 +3,6 @@
package version
const Version = "v1.60.0-3a2e4dfd2-dev"
const Version = "v1.60.3-26b1fd2ae-dev"
const VersionGitRef = "3a2e4dfd2"
const VersionGitRef = "26b1fd2ae"

View File

@ -3,6 +3,6 @@
package version
const Version = "v1.60.0-3a2e4dfd2"
const Version = "v1.60.3-26b1fd2ae"
const VersionGitRef = "3a2e4dfd2"
const VersionGitRef = "26b1fd2ae"