Compare commits

..

130 Commits

Author SHA1 Message Date
Matthias
958a4565db Merge pull request #7313 from freqtrade/new_release
New release 2022.8
2022-08-30 23:01:19 +02:00
Matthias
2403a03fcb Version bump 2022.8 2022-08-29 06:28:53 +02:00
Matthias
a01402fa46 Merge branch 'stable' into develop 2022-08-29 06:28:21 +02:00
th0rntwig
8b0cfe1236 Reduce image sizes in freqai doc (#7304) 2022-08-28 23:27:12 +02:00
Robert Caulk
39a739eadb Merge pull request #7296 from th0rntwig/dbscan
Improve MinPts calculation in DBSCAN, add outlier protection, and add data_kitchen tests
2022-08-28 14:37:47 +02:00
robcaulk
a44a235b56 isort imports in tests/freqai 2022-08-28 13:47:01 +02:00
robcaulk
6634229cc1 appease the flake8 gods 2022-08-28 13:21:29 +02:00
robcaulk
fcb5d1cb5a remove debugging flag 2022-08-28 13:01:39 +02:00
robcaulk
dd628eb525 add tests for outlier detection and removal functions 2022-08-28 12:56:39 +02:00
robcaulk
1e41c773a0 fix outlier protection 2022-08-28 12:11:29 +02:00
robcaulk
22b42e91f3 add new parameter to freqai doc 2022-08-28 11:53:24 +02:00
Matthias
b9f35cadb3 add /stopentry alias for /stopbuy 2022-08-28 11:37:22 +02:00
Matthias
59a723aec8 Add /health to rest client
discovered in #7299
2022-08-27 15:12:04 +02:00
th0rntwig
71f7d68783 Fixed mypy error 2022-08-27 12:44:55 +02:00
Matthias
6686489c06 Merge pull request #7258 from freqtrade/feat/hyp_optinal_indicator
Add flag to move hyperopt populate_indicators to epoch
2022-08-27 09:21:16 +02:00
Matthias
c3e74e6e8d Improve doc wording 2022-08-27 08:55:29 +02:00
Matthias
2b70c3d0c0 support price callback for partial exits in bt
This will align results to how live works.
closes #7292
2022-08-27 08:50:09 +02:00
Matthias
9204f01312 Don't lock pairs on partial exit 2022-08-27 07:23:02 +02:00
elintornquist
86c5ac44e4 Add outlier percentage check 2022-08-26 23:05:07 +02:00
Matthias
2ef4534fee Fix ccxt / longrun tests 2022-08-26 20:44:36 +02:00
Matthias
efe4fd3e24 Add libgomp1 to dockerfile 2022-08-26 20:21:19 +02:00
Matthias
01126c43f7 Fix liquidation price tier calculation
closes #7294
2022-08-26 20:14:24 +02:00
Matthias
753d1b2aad Update leverage tier terminology to be clear and aligned with ccxt 2022-08-26 19:34:51 +02:00
elintornquist
b2d664c63c Change MinPts calculation 2022-08-26 18:57:27 +02:00
Matthias
53d46a0385 align max_entry_position_adjustment behavior of backtesting to live
closes #7293
2022-08-25 20:36:17 +02:00
Matthias
1fd223c815 Update --prepend help string
closes #7290
2022-08-25 17:03:41 +02:00
Matthias
f2a356a80c Fix some imports 2022-08-25 07:08:58 +02:00
Matthias
6636f17e0f Simplify usage of amount_to_contract precision 2022-08-25 07:08:22 +02:00
Matthias
9e48e6a40b Update docs about precision limits in backtesting 2022-08-25 06:50:10 +02:00
Matthias
205ab26e92 Remove TODO in test 2022-08-25 06:50:10 +02:00
Matthias
70df037690 Improve test precision 2022-08-25 06:50:10 +02:00
Matthias
32faad9333 Fix backtest calculation problem with DCA
closes #7287
2022-08-24 20:36:08 +02:00
Matthias
a6d78a8615 initialize Since parameter properly
closes #7285
2022-08-23 06:43:04 +02:00
Matthias
fe7108ae75 Convert amount to contracts before comparing for close
closes #7279
2022-08-23 06:37:38 +02:00
Matthias
78b161e14c add contract_size to database 2022-08-23 06:37:38 +02:00
Matthias
6036018f35 Extract contracts_to_amount and amount_to_contracts to standalone functions 2022-08-23 06:37:38 +02:00
Matthias
1b0f37a93c Fix documentation typo 2022-08-23 06:37:38 +02:00
Matthias
5f38a574ce Add okx broker id 2022-08-23 06:37:38 +02:00
th0rntwig
5ce1c69803 Improve DBSCAN epsilon identification (#7269)
* Improve DBSCAN epsilon identification
2022-08-22 19:57:20 +02:00
Matthias
60ba921f56 Merge pull request #7282 from freqtrade/mem-leak-fix
Plug mem leak, add training timer
2022-08-22 19:36:52 +02:00
robcaulk
96d8882f1e Plug mem leak, add training timer 2022-08-22 13:30:30 +02:00
Matthias
f55d5ffd8c Don't fail when --strategy-path is not a valid directory.
closes #7264
2022-08-22 09:20:14 +00:00
Matthias
914b6247e4 Merge pull request #7278 from freqtrade/dependabot/pip/develop/ccxt-1.92.52
Bump ccxt from 1.92.20 to 1.92.52
2022-08-22 08:41:52 +02:00
Matthias
da87e9cbb3 Merge pull request #7275 from freqtrade/dependabot/pip/develop/types-requests-2.28.9
Bump types-requests from 2.28.8 to 2.28.9
2022-08-22 08:41:34 +02:00
Matthias
484b147a89 Merge pull request #7277 from freqtrade/dependabot/pip/develop/time-machine-2.8.1
Bump time-machine from 2.7.1 to 2.8.1
2022-08-22 07:13:05 +02:00
Matthias
015be770c3 ccxt now defaults to base volume for all markets 2022-08-22 06:42:14 +02:00
Matthias
93d2f7fc85 types-requests bump pre-commit 2022-08-22 06:37:26 +02:00
Matthias
7844157a90 Merge pull request #7276 from freqtrade/dependabot/pip/develop/jsonschema-4.14.0
Bump jsonschema from 4.9.1 to 4.14.0
2022-08-22 06:31:29 +02:00
Matthias
6e046884af Merge pull request #7273 from freqtrade/dependabot/pip/develop/fastapi-0.79.1
Bump fastapi from 0.79.0 to 0.79.1
2022-08-22 06:25:35 +02:00
Matthias
a784f63e9a Merge pull request #7274 from freqtrade/dependabot/pip/develop/mkdocs-material-8.4.1
Bump mkdocs-material from 8.4.0 to 8.4.1
2022-08-22 06:24:22 +02:00
dependabot[bot]
ff9ed1abad Bump ccxt from 1.92.20 to 1.92.52
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.92.20 to 1.92.52.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/exchanges.cfg)
- [Commits](https://github.com/ccxt/ccxt/compare/1.92.20...1.92.52)

---
updated-dependencies:
- dependency-name: ccxt
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 03:02:25 +00:00
dependabot[bot]
354d3c0cda Bump time-machine from 2.7.1 to 2.8.1
Bumps [time-machine](https://github.com/adamchainz/time-machine) from 2.7.1 to 2.8.1.
- [Release notes](https://github.com/adamchainz/time-machine/releases)
- [Changelog](https://github.com/adamchainz/time-machine/blob/main/HISTORY.rst)
- [Commits](https://github.com/adamchainz/time-machine/compare/2.7.1...2.8.1)

---
updated-dependencies:
- dependency-name: time-machine
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 03:02:10 +00:00
dependabot[bot]
eeb177110e Bump jsonschema from 4.9.1 to 4.14.0
Bumps [jsonschema](https://github.com/python-jsonschema/jsonschema) from 4.9.1 to 4.14.0.
- [Release notes](https://github.com/python-jsonschema/jsonschema/releases)
- [Changelog](https://github.com/python-jsonschema/jsonschema/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/python-jsonschema/jsonschema/compare/v4.9.1...v4.14.0)

---
updated-dependencies:
- dependency-name: jsonschema
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 03:02:03 +00:00
dependabot[bot]
70848a258d Bump types-requests from 2.28.8 to 2.28.9
Bumps [types-requests](https://github.com/python/typeshed) from 2.28.8 to 2.28.9.
- [Release notes](https://github.com/python/typeshed/releases)
- [Commits](https://github.com/python/typeshed/commits)

---
updated-dependencies:
- dependency-name: types-requests
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 03:01:59 +00:00
dependabot[bot]
3958e53aaa Bump mkdocs-material from 8.4.0 to 8.4.1
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 8.4.0 to 8.4.1.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/8.4.0...8.4.1)

---
updated-dependencies:
- dependency-name: mkdocs-material
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 03:01:55 +00:00
dependabot[bot]
dfa7d1fc27 Bump fastapi from 0.79.0 to 0.79.1
Bumps [fastapi](https://github.com/tiangolo/fastapi) from 0.79.0 to 0.79.1.
- [Release notes](https://github.com/tiangolo/fastapi/releases)
- [Commits](https://github.com/tiangolo/fastapi/compare/0.79.0...0.79.1)

---
updated-dependencies:
- dependency-name: fastapi
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 03:01:51 +00:00
Matthias
2dc34779d5 Fix line length 2022-08-21 18:07:41 +02:00
Matthias
f6d832c6d9 Add get_option to expose ft_has via method 2022-08-21 17:51:46 +02:00
Matthias
87a3115073 Add get_open_trade_count() to simplify getting open trade count. 2022-08-21 17:08:27 +02:00
Matthias
085f81ec9e Fix header indent on stake-size-management 2022-08-21 08:24:14 +02:00
Matthias
0ec38e0cfd Fix typo in docs 2022-08-21 08:23:07 +02:00
Matthias
cdd4745693 Merge pull request #7263 from freqtrade/okx_cache_tiers
Okx cache tiers
2022-08-20 15:18:13 +02:00
Matthias
1fb2e9558f Disable caching of leverage tiers in ccxt compat methods 2022-08-20 14:39:11 +02:00
Matthias
5b3f031590 Use hyperopt safe amount precision method 2022-08-20 14:13:15 +02:00
Matthias
4511634f3a improve test coverage 2022-08-20 14:03:47 +02:00
Matthias
738e95b875 Add tests for leverage tiers caching 2022-08-20 13:54:54 +02:00
Matthias
b6e8b9df35 Use cached leverage tiers 2022-08-20 13:01:58 +02:00
Matthias
52ec0d1046 Update binance Leverage tiers 2022-08-20 11:53:15 +02:00
Matthias
7563050f17 Realign tests to precision backtesting 2022-08-20 11:47:15 +02:00
Matthias
0da0600836 Have backtesting respect tradable size
closes #7161
2022-08-20 11:41:11 +02:00
Matthias
54ddc1a4c2 Add --tradingmode alias 2022-08-20 11:24:20 +02:00
Matthias
aa3da092a0 Dont' use classProperty - that's not supported on 3.8 2022-08-20 10:55:52 +02:00
Matthias
63efb3ff3e Merge pull request #7245 from th0rntwig/improve-doc
Restructure and improve doc, add fig
2022-08-20 09:48:50 +02:00
Matthias
665cf4431d Add explicit test cov. for .range behavior 2022-08-20 08:41:31 +02:00
Matthias
01d45ed12e Merge pull request #7257 from freqtrade/feat/list-pair-time
Get min/max data in list-data command
2022-08-20 08:16:52 +02:00
Matthias
7b8b73e651 Merge pull request #7243 from lolongcovas/newbranch_test
Improve PCA and pairwise distance calcs
2022-08-20 08:13:40 +02:00
elintornquist
692c6bf1fd Added and updated figs and fig descriptions 2022-08-19 22:23:26 +02:00
robcaulk
88d6a7fbff additional edits 2022-08-19 22:23:26 +02:00
elintornquist
9c6b745f06 Restructure and improve doc, add fiq 2022-08-19 22:23:26 +02:00
Matthias
b9d48c3278 use numbers in HyperoptState properly ... 2022-08-19 15:40:06 +02:00
Matthias
1389c8f5b6 Update documentation with show-timerange option 2022-08-19 15:34:10 +02:00
Matthias
733f716819 Update documentation 2022-08-19 15:22:43 +02:00
Matthias
bc359675a2 Add --analyze-per-epoch - moving populate_analysis to the epoch process 2022-08-19 15:19:43 +02:00
Matthias
09f8904545 Extract analysis to separate method 2022-08-19 15:12:55 +02:00
Matthias
08ef5ad2d8 Add HyperoptState enum and container class 2022-08-19 15:11:43 +02:00
Matthias
1c6f966579 Hyperopt: simplify parameter "can_optimize" handling 2022-08-19 15:03:03 +02:00
Matthias
b7553d20d4 Get min/max data in list-data command 2022-08-19 13:45:55 +02:00
longyu
521381ebf0 undo example strategy newline 2022-08-19 12:40:03 +02:00
longyu
790534e0f8 Merge branch 'newbranch_test' of github.com:lolongcovas/freqtrade into newbranch_test 2022-08-19 12:39:19 +02:00
longyu
cfa5b3f12c add new line 2022-08-19 12:39:08 +02:00
longyu
277245c69d remove line 2022-08-19 12:39:00 +02:00
longyu
1fada53ddd remove newline 2022-08-18 19:40:00 +02:00
longyu
f70b0bab80 remove line 2022-08-17 23:49:20 +02:00
longyu
9c38c27eed ignore sample itself distance for avg_mean_dist computation 2022-08-17 15:09:57 +02:00
longyu
72c34291e3 newline 2022-08-17 15:09:10 +02:00
Matthias
987bbb8e12 Merge pull request #7176 from Jetsukda/patch-1
Edit Typo Custom-stake-amount
2022-08-05 06:23:00 +02:00
OGSK
c3d06257be Edit index of custom_stake_amount 2022-08-05 09:36:26 +07:00
OGSK
8bf056ca39 Edit Typo Custom-stake-amount
Edit Custom-stake-amount to `custom_stake_amount`
2022-08-05 00:28:28 +07:00
Matthias
046ae18411 Merge pull request #7144 from freqtrade/new_release
New release 2022.7
2022-07-30 16:06:37 +02:00
Matthias
28b4773083 Version bump 2022.7 2022-07-30 09:21:29 +02:00
Matthias
d4e8ab1cac Merge branch 'stable' into new_release 2022-07-30 09:21:05 +02:00
Matthias
2db5cc177d Merge pull request #7029 from freqtrade/new_release
New release 2022.6
2022-07-03 19:42:24 +02:00
Matthias
c1d4078518 Version bump to 2022.6 2022-07-03 15:04:38 +02:00
Matthias
d25ec6d0b8 Merge branch 'stable' into new_release 2022-07-03 15:04:16 +02:00
Matthias
c57db0a330 Version bump 2022.5.1 2022-06-01 06:34:28 +02:00
Matthias
f5087a82dc Merge branch 'stable' into new_release 2022-06-01 06:33:42 +02:00
Matthias
eed0d67005 Merge pull request #6893 from freqtrade/new_release
New release 2022.5
2022-05-28 13:46:24 +02:00
Matthias
a1d54f5ae0 Version bump 2022.5 2022-05-28 09:49:58 +02:00
Matthias
a4a7c6536d Merge branch 'stable' into new_release 2022-05-28 09:49:46 +02:00
Matthias
340a97d1df Merge pull request #6811 from DJCrashdummy/patch-1
corrected minor "typo" in formatting
2022-05-10 19:16:40 +02:00
DJCrashdummy
fab197edf2 corrected minor "typo" in formatting 2022-05-10 10:33:04 +00:00
Matthias
851c5dad30 Version bump 2022.4.2 2022-05-03 20:37:29 +02:00
Matthias
5b76ae452f Fix fee handling for futures trades 2022-05-03 20:35:30 +02:00
Matthias
2c750fdb09 Reduce no stake amount verbosity
closes #6768
2022-05-03 20:35:22 +02:00
Matthias
e7f5252074 Version bump 2022.4.1 2022-05-01 16:49:11 +02:00
Matthias
dfbd1c34c4 Merge pull request #6755 from freqtrade/new_release
New release 2022.4
2022-05-01 14:51:39 +02:00
Matthias
7615c4e904 Version bump 2022.4 2022-05-01 11:19:32 +02:00
Matthias
e9b78bf3ae Merge branch 'stable' into new_release 2022-05-01 11:19:17 +02:00
Matthias
2e397a88e1 Merge pull request #6592 from freqtrade/new_release
New release 2022.3
2022-03-27 15:51:58 +02:00
Matthias
fe6c62e144 Version bump 2022.3 2022-03-27 15:27:16 +02:00
Matthias
f0db721f05 Merge branch 'stable' into new_release 2022-03-27 15:09:06 +02:00
Matthias
4d8d30ea39 Version bump to 2022.2.2 2022-03-21 06:34:33 +01:00
Matthias
e90e3cead0 Map usdt fiat to correct coingecko fiat 2022-03-21 06:34:20 +01:00
Matthias
a568548192 Merge pull request #6464 from freqtrade/new_release
New release 2022.2.1
2022-02-26 08:57:42 +01:00
Matthias
f9d10a7fad Version bump 2022.2.1 2022-02-26 08:35:50 +01:00
Matthias
cbc2b00ee6 Merge branch 'stable' into new_release 2022-02-26 08:35:31 +01:00
Matthias
8f7b857ae9 Merge pull request #6459 from freqtrade/new_release
New release 2022.2
2022-02-25 15:14:27 +01:00
Matthias
e88b022cd4 Version bump 2022.2 2022-02-25 12:07:09 +01:00
Matthias
bfb738f69f Merge branch 'stable' into new_release 2022-02-25 12:06:11 +01:00
Matthias
00dd8e76ee Merge pull request #6416 from froggleston/patch-2
Update windows_installation.md
2022-02-25 11:44:40 +01:00
71 changed files with 2514 additions and 1278 deletions

View File

@@ -15,7 +15,7 @@ repos:
additional_dependencies:
- types-cachetools==5.2.1
- types-filelock==3.2.7
- types-requests==2.28.8
- types-requests==2.28.9
- types-tabulate==0.8.11
- types-python-dateutil==2.8.19
# stages: [push]

View File

@@ -11,7 +11,7 @@ ENV FT_APP_ENV="docker"
# Prepare environment
RUN mkdir /freqtrade \
&& apt-get update \
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev \
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev libgomp1 \
&& apt-get clean \
&& useradd -u 1000 -G sudo -U -m -s /bin/bash ftuser \
&& chown ftuser:ftuser /freqtrade \

View File

@@ -130,7 +130,7 @@ Telegram is not mandatory. However, this is a great way to control your bot. Mor
- `/start`: Starts the trader.
- `/stop`: Stops the trader.
- `/stopbuy`: Stop entering new trades.
- `/stopentry`: Stop entering new trades.
- `/status <trade_id>|[table]`: Lists all or specific open trades.
- `/profit [<n>]`: Lists cumulative profit from all finished trades, over the last n days.
- `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`).

BIN
docs/assets/freqai_DI.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 KiB

BIN
docs/assets/freqai_algo.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 995 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

View File

@@ -561,6 +561,14 @@ BTC trades at 22.000\$ today (0.001 BTC is related to this) - but the backtestin
Today's minimum would be `0.001 * 22_000` - or 22\$.
However the limit could also be 50$ - based on `0.001 * 50_000` in some historic setting.
#### Trading precision limits
Most exchanges pose precision limits on both price and amounts, so you cannot buy 1.0020401 of a pair, or at a price of 1.24567123123.
Instead, these prices and amounts will be rounded or truncated (based on the exchange definition) to the defined trading precision.
The above values may for example be rounded to an amount of 1.002, and a price of 1.24567.
These precision values are based on current exchange limits (as described in the [above section](#trading-limits-in-backtesting)), as historic precision limits are not available.
## Improved backtest accuracy
One big limitation of backtesting is it's inability to know how prices moved intra-candle (was high before close, or viceversa?).

View File

@@ -70,7 +70,7 @@ This loop will be repeated again and again until the bot is stopped.
* Determine stake size by calling the `custom_stake_amount()` callback.
* Check position adjustments for open trades if enabled and call `adjust_trade_position()` to determine if an additional order is requested.
* Call `custom_stoploss()` and `custom_exit()` to find custom exit points.
* For exits based on exit-signal and custom-exit: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
* For exits based on exit-signal, custom-exit and partial exits: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
* Generate backtest report output
!!! Note

View File

@@ -63,7 +63,7 @@ optional arguments:
`jsongz`).
--trading-mode {spot,margin,futures}
Select Trading mode
--prepend Allow data prepending.
--prepend Allow data prepending. (Data-appending is disabled)
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
@@ -186,7 +186,7 @@ Freqtrade currently supports 3 data-formats for both OHLCV and trades data:
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
To persist this change, you should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
``` jsonc
// ...
@@ -374,6 +374,7 @@ usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--data-format-ohlcv {json,jsongz,hdf5}]
[-p PAIRS [PAIRS ...]]
[--trading-mode {spot,margin,futures}]
[--show-timerange]
optional arguments:
-h, --help show this help message and exit
@@ -387,6 +388,8 @@ optional arguments:
separated.
--trading-mode {spot,margin,futures}
Select Trading mode
--show-timerange Show timerange available for available data. (May take
a while to calculate).
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).

View File

@@ -77,9 +77,9 @@ Freqtrade will not provide incomplete candles to strategies. Using incomplete ca
You can use "current" market data by using the [dataprovider](strategy-customization.md#orderbookpair-maximum)'s orderbook or ticker methods - which however cannot be used during backtesting.
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
### Is there a setting to only Exit the trades being held and not perform any new Entries?
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forceexit all` (sell all open trades).
You can use the `/stopentry` command in Telegram to prevent future trade entry, followed by `/forceexit all` (sell all open trades).
### I want to run multiple bots on the same machine

File diff suppressed because it is too large Load Diff

View File

@@ -40,7 +40,8 @@ pip install -r requirements-hyperopt.txt
```
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH]
[--recursive-strategy-search] [-i TIMEFRAME]
[--recursive-strategy-search] [--freqaimodel NAME]
[--freqaimodel-path PATH] [-i TIMEFRAME]
[--timerange TIMERANGE]
[--data-format-ohlcv {json,jsongz,hdf5}]
[--max-open-trades INT]
@@ -53,7 +54,7 @@ usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--print-all] [--no-color] [--print-json] [-j JOBS]
[--random-state INT] [--min-trades INT]
[--hyperopt-loss NAME] [--disable-param-export]
[--ignore-missing-spaces]
[--ignore-missing-spaces] [--analyze-per-epoch]
optional arguments:
-h, --help show this help message and exit
@@ -129,6 +130,7 @@ optional arguments:
--ignore-missing-spaces, --ignore-unparameterized-spaces
Suppress errors for any requested Hyperopt spaces that
do not contain any parameters.
--analyze-per-epoch Run populate_indicators once per epoch.
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
@@ -154,6 +156,10 @@ Strategy arguments:
--recursive-strategy-search
Recursively search for a strategy in the strategies
folder.
--freqaimodel NAME Specify a custom freqaimodels.
--freqaimodel-path PATH
Specify additional lookup path for freqaimodels.
```
### Hyperopt checklist
@@ -185,7 +191,7 @@ Rarely you may also need to create a [nested class](advanced-hyperopt.md#overrid
### Hyperopt execution logic
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators.
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators, unless `--analyze-per-epoch` is specified.
Hyperopt will then spawn into different processes (number of processors, or `-j <n>`), and run backtesting over and over again, changing the parameters that are part of the `--spaces` defined.
@@ -426,9 +432,10 @@ While this strategy is most likely too simple to provide consistent profit, it s
`range` property may also be used with `DecimalParameter` and `CategoricalParameter`. `RealParameter` does not provide this property due to infinite search space.
??? Hint "Performance tip"
By doing the calculation of all possible indicators in `populate_indicators()`, the calculation of the indicator happens only once for every parameter.
While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values).
You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space.
During normal hyperopting, indicators are calculated once and supplied to each epoch, linearly increasing RAM usage as a factor of increasing cores. As this also has performance implications, hyperopt provides `--analyze-per-epoch` which will move the execution of `populate_indicators()` to the epoch process, calculating a single value per parameter per epoch instead of using the `.range` functionality. In this case, `.range` functionality will only return the actually used value. This will reduce RAM usage, but increase CPU usage. However, your hyperopting run will be less likely to fail due to Out Of Memory (OOM) issues.
In either case, you should try to use space ranges as small as possible this will improve CPU/RAM usage in both scenarios.
## Optimizing protections
@@ -879,6 +886,7 @@ To combat these, you have multiple options:
* Avoid using `--timeframe-detail` (this loads a lot of additional data into memory).
* Reduce the number of parallel processes (`-j <n>`).
* Increase the memory of your machine.
* Use `--analyze-per-epoch` if you're using a lot of parameters with `.range` functionality.
## The objective has been evaluated at this point before.

View File

@@ -1,6 +1,6 @@
markdown==3.3.7
mkdocs==1.3.1
mkdocs-material==8.4.0
mkdocs-material==8.4.1
mdx_truly_sane_lists==1.3
pymdown-extensions==9.5
jinja2==3.1.2

View File

@@ -163,6 +163,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
| `strategy <strategy>` | Get specific Strategy content. **Alpha**
| `available_pairs` | List available backtest data. **Alpha**
| `version` | Show version.
| `sysinfo` | Show informations about the system load.
| `health` | Show bot health (last bot loop).
!!! Warning "Alpha status"
Endpoints labeled with *Alpha status* above may change at any time without notice.
@@ -227,6 +229,11 @@ forceexit
Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
health
Provides a quick health check of the running bot.
locks
Return current locks
@@ -312,12 +319,13 @@ version
whitelist
Show the current whitelist.
```
### OpenAPI interface
To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration.
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs - but it'll depend on your settings.
### Advanced API usage using JWT tokens

View File

@@ -75,7 +75,7 @@ class AwesomeStrategy(IStrategy):
```
### Stake size management
## Stake size management
Called before entering a trade, makes it possible to manage your position size when placing a new trade.
@@ -423,7 +423,7 @@ class AwesomeStrategy(IStrategy):
!!! Warning "Backtesting"
Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range.
Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle.
`custom_exit_price()` is only called for sells of type exit_signal and Custom exit. All other exit-types will use regular backtesting prices.
`custom_exit_price()` is only called for sells of type exit_signal, Custom exit and partial exits. All other exit-types will use regular backtesting prices.
## Custom order timeout rules
@@ -654,7 +654,7 @@ Position adjustments will always be applied in the direction of the trade, so a
Stoploss is still calculated from the initial opening price, not averaged price.
Regular stoploss rules still apply (cannot move down).
While `/stopbuy` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
While `/stopentry` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
!!! Warning "Backtesting"
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so run-time performance will be affected.

View File

@@ -149,7 +149,7 @@ You can create your own keyboard in `config.json`:
!!! Note "Supported Commands"
Only the following commands are allowed. Command arguments are not supported!
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopbuy`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopentry`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
## Telegram commands
@@ -161,7 +161,7 @@ official commands. You can ask at any moment for help with `/help`.
|----------|-------------|
| `/start` | Starts the trader
| `/stop` | Stops the trader
| `/stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
| `/stopbuy | /stopentry` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
| `/reload_config` | Reloads the configuration file
| `/show_config` | Shows part of the current configuration with relevant settings to operation
| `/logs [limit]` | Show last log messages.

View File

@@ -1,5 +1,5 @@
""" Freqtrade bot """
__version__ = '2022.8.dev'
__version__ = '2022.8'
if 'dev' in __version__:
try:

View File

@@ -34,7 +34,7 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
"print_colorized", "print_json", "hyperopt_jobs",
"hyperopt_random_state", "hyperopt_min_trades",
"hyperopt_loss", "disableparamexport",
"hyperopt_ignore_missing_space"]
"hyperopt_ignore_missing_space", "analyze_per_epoch"]
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
@@ -69,7 +69,7 @@ ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "exchange", "tradin
ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"]
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode"]
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode", "show_timerange"]
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "new_pairs_days", "include_inactive",
"timerange", "download_trades", "exchange", "timeframes",

View File

@@ -255,6 +255,13 @@ AVAILABLE_CLI_OPTIONS = {
nargs='+',
default='default',
),
"analyze_per_epoch": Arg(
'--analyze-per-epoch',
help='Run populate_indicators once per epoch.',
action='store_true',
default=False,
),
"print_all": Arg(
'--print-all',
help='Print all results, not only the best ones.',
@@ -367,7 +374,7 @@ AVAILABLE_CLI_OPTIONS = {
metavar='BASE_CURRENCY',
),
"trading_mode": Arg(
'--trading-mode',
'--trading-mode', '--tradingmode',
help='Select Trading mode',
choices=constants.TRADING_MODES,
),
@@ -434,6 +441,11 @@ AVAILABLE_CLI_OPTIONS = {
help='Storage format for downloaded trades data. (default: `jsongz`).',
choices=constants.AVAILABLE_DATAHANDLERS,
),
"show_timerange": Arg(
'--show-timerange',
help='Show timerange available for available data. (May take a while to calculate).',
action='store_true',
),
"exchange": Arg(
'--exchange',
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
@@ -450,7 +462,7 @@ AVAILABLE_CLI_OPTIONS = {
),
"prepend_data": Arg(
'--prepend',
help='Allow data prepending.',
help='Allow data prepending. (Data-appending is disabled)',
action='store_true',
),
"erase": Arg(

View File

@@ -5,13 +5,13 @@ from datetime import datetime, timedelta
from typing import Any, Dict, List
from freqtrade.configuration import TimeRange, setup_utils_configuration
from freqtrade.constants import DATETIME_PRINT_FORMAT
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format
from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data,
refresh_backtest_trades_data)
from freqtrade.enums import CandleType, RunMode, TradingMode
from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes
from freqtrade.exchange.exchange import market_is_active
from freqtrade.exchange import market_is_active, timeframe_to_minutes
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist
from freqtrade.resolvers import ExchangeResolver
@@ -80,7 +80,7 @@ def start_download_data(args: Dict[str, Any]) -> None:
data_format_trades=config['dataformat_trades'],
)
else:
if not exchange._ft_has.get('ohlcv_has_history', True):
if not exchange.get_option('ohlcv_has_history', True):
raise OperationalException(
f"Historic klines not available for {exchange.name}. "
"Please use `--dl-trades` instead for this exchange "
@@ -177,17 +177,31 @@ def start_list_data(args: Dict[str, Any]) -> None:
paircombs = [comb for comb in paircombs if comb[0] in args['pairs']]
print(f"Found {len(paircombs)} pair / timeframe combinations.")
groupedpair = defaultdict(list)
for pair, timeframe, candle_type in sorted(
paircombs,
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
):
groupedpair[(pair, candle_type)].append(timeframe)
if not config.get('show_timerange'):
groupedpair = defaultdict(list)
for pair, timeframe, candle_type in sorted(
paircombs,
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
):
groupedpair[(pair, candle_type)].append(timeframe)
if groupedpair:
if groupedpair:
print(tabulate([
(pair, ', '.join(timeframes), candle_type)
for (pair, candle_type), timeframes in groupedpair.items()
],
headers=("Pair", "Timeframe", "Type"),
tablefmt='psql', stralign='right'))
else:
paircombs1 = [(
pair, timeframe, candle_type,
*dhc.ohlcv_data_min_max(pair, timeframe, candle_type)
) for pair, timeframe, candle_type in paircombs]
print(tabulate([
(pair, ', '.join(timeframes), candle_type)
for (pair, candle_type), timeframes in groupedpair.items()
],
headers=("Pair", "Timeframe", "Type"),
(pair, timeframe, candle_type,
start.strftime(DATETIME_PRINT_FORMAT),
end.strftime(DATETIME_PRINT_FORMAT))
for pair, timeframe, candle_type, start, end in paircombs1
],
headers=("Pair", "Timeframe", "Type", 'From', 'To'),
tablefmt='psql', stralign='right'))

View File

@@ -302,6 +302,9 @@ class Configuration:
self._args_to_config(config, argname='spaces',
logstring='Parameter -s/--spaces detected: {}')
self._args_to_config(config, argname='analyze_per_epoch',
logstring='Parameter --analyze-per-epoch detected.')
self._args_to_config(config, argname='print_all',
logstring='Parameter --print-all detected ...')
@@ -426,6 +429,9 @@ class Configuration:
self._args_to_config(config, argname='dataformat_trades',
logstring='Using "{}" to store trades data.')
self._args_to_config(config, argname='show_timerange',
logstring='Detected --show-timerange')
def _process_data_options(self, config: Dict[str, Any]) -> None:
self._args_to_config(config, argname='new_pairs_days',
logstring='Detected --new-pairs-days: {}')

View File

@@ -302,8 +302,8 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
if trading_mode == 'futures':
# Predefined candletype (and timeframe) depending on exchange
# Downloads what is necessary to backtest based on futures data.
tf_mark = exchange._ft_has['mark_ohlcv_timeframe']
fr_candle_type = CandleType.from_string(exchange._ft_has['mark_ohlcv_price'])
tf_mark = exchange.get_option('mark_ohlcv_timeframe')
fr_candle_type = CandleType.from_string(exchange.get_option('mark_ohlcv_price'))
# All exchanges need FundingRate for futures trading.
# The timeframe is aligned to the mark-price timeframe.
for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type):
@@ -330,13 +330,12 @@ def _download_trades_history(exchange: Exchange,
try:
until = None
since = 0
if timerange:
if timerange.starttype == 'date':
since = timerange.startts * 1000
if timerange.stoptype == 'date':
until = timerange.stopts * 1000
else:
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
trades = data_handler.trades_load(pair)
@@ -349,6 +348,9 @@ def _download_trades_history(exchange: Exchange,
logger.info(f"Start earlier than available data. Redownloading trades for {pair}...")
trades = []
if not since:
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
from_id = trades[-1][1] if trades else None
if trades and since < trades[-1][0]:
# Reset since to the last available point

View File

@@ -9,7 +9,7 @@ from abc import ABC, abstractmethod
from copy import deepcopy
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional, Type
from typing import List, Optional, Tuple, Type
from pandas import DataFrame
@@ -84,6 +84,18 @@ class IDataHandler(ABC):
:return: None
"""
def ohlcv_data_min_max(self, pair: str, timeframe: str,
candle_type: CandleType) -> Tuple[datetime, datetime]:
"""
Returns the min and max timestamp for the given pair and timeframe.
:param pair: Pair to get min/max for
:param timeframe: Timeframe to get min/max for
:param candle_type: Any of the enum CandleType (must match trading mode!)
:return: (min, max)
"""
data = self._ohlcv_load(pair, timeframe, None, candle_type)
return data.iloc[0]['date'].to_pydatetime(), data.iloc[-1]['date'].to_pydatetime()
@abstractmethod
def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange],
candle_type: CandleType

View File

@@ -15,7 +15,7 @@ from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
from freqtrade.data.history import get_timerange, load_data, refresh_data
from freqtrade.enums import CandleType, ExitType, RunMode
from freqtrade.exceptions import OperationalException
from freqtrade.exchange.exchange import timeframe_to_seconds
from freqtrade.exchange import timeframe_to_seconds
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.strategy.interface import IStrategy

View File

@@ -3,6 +3,7 @@ from freqtrade.enums.backteststate import BacktestState
from freqtrade.enums.candletype import CandleType
from freqtrade.enums.exitchecktuple import ExitCheckTuple
from freqtrade.enums.exittype import ExitType
from freqtrade.enums.hyperoptstate import HyperoptState
from freqtrade.enums.marginmode import MarginMode
from freqtrade.enums.ordertypevalue import OrderTypeValues
from freqtrade.enums.rpcmessagetype import RPCMessageType

View File

@@ -0,0 +1,12 @@
from enum import Enum
class HyperoptState(Enum):
""" Hyperopt states """
STARTUP = 1
DATALOAD = 2
INDICATORS = 3
OPTIMIZE = 4
def __str__(self):
return f"{self.name.lower()}"

View File

@@ -9,10 +9,11 @@ from freqtrade.exchange.bitpanda import Bitpanda
from freqtrade.exchange.bittrex import Bittrex
from freqtrade.exchange.bybit import Bybit
from freqtrade.exchange.coinbasepro import Coinbasepro
from freqtrade.exchange.exchange import (amount_to_precision, available_exchanges, ccxt_exchanges,
date_minus_candles, is_exchange_known_ccxt,
is_exchange_officially_supported, market_is_active,
price_to_precision, timeframe_to_minutes,
from freqtrade.exchange.exchange import (amount_to_contract_precision, amount_to_contracts,
amount_to_precision, available_exchanges, ccxt_exchanges,
contracts_to_amount, date_minus_candles,
is_exchange_known_ccxt, is_exchange_officially_supported,
market_is_active, price_to_precision, timeframe_to_minutes,
timeframe_to_msecs, timeframe_to_next_date,
timeframe_to_prev_date, timeframe_to_seconds,
validate_exchange, validate_exchanges)

View File

@@ -137,23 +137,27 @@ class Binance(Exchange):
pair: str,
open_rate: float, # Entry price of position
is_short: bool,
position: float, # Absolute value of position size
amount: float,
stake_amount: float,
wallet_balance: float, # Or margin balance
mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]:
"""
Important: Must be fetching data from cached values as this is used by backtesting!
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
:param exchange_name:
:param open_rate: (EP1) Entry price of position
:param open_rate: Entry price of position
:param is_short: True if the trade is a short, false otherwise
:param position: Absolute value of position size (in base currency)
:param wallet_balance: (WB)
:param amount: Absolute value of position size incl. leverage (in base currency)
:param stake_amount: Stake amount - Collateral in settle currency.
:param trading_mode: SPOT, MARGIN, FUTURES, etc.
:param margin_mode: Either ISOLATED or CROSS
:param wallet_balance: Amount of margin_mode in the wallet being used to trade
Cross-Margin Mode: crossWalletBalance
Isolated-Margin Mode: isolatedWalletBalance
:param maintenance_amt:
# * Only required for Cross
:param mm_ex_1: (TMM)
@@ -165,12 +169,11 @@ class Binance(Exchange):
"""
side_1 = -1 if is_short else 1
position = abs(position)
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
# maintenance_amt: (CUM) Maintenance Amount of position
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, position)
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, stake_amount)
if (maintenance_amt is None):
raise OperationalException(
@@ -182,9 +185,9 @@ class Binance(Exchange):
return (
(
(wallet_balance + cross_vars + maintenance_amt) -
(side_1 * position * open_rate)
(side_1 * amount * open_rate)
) / (
(position * mm_ratio) - (side_1 * position)
(amount * mm_ratio) - (side_1 * amount)
)
)
else:

File diff suppressed because it is too large Load Diff

View File

@@ -17,6 +17,7 @@ import ccxt
import ccxt.async_support as ccxt_async
from cachetools import TTLCache
from ccxt import ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE, decimal_to_precision
from dateutil import parser
from pandas import DataFrame
from freqtrade.constants import (DEFAULT_AMOUNT_RESERVE_PERCENT, NON_OPEN_EXCHANGE_STATES, BuySell,
@@ -30,7 +31,8 @@ from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, BAD_EXCHANGE
EXCHANGE_HAS_OPTIONAL, EXCHANGE_HAS_REQUIRED,
SUPPORTED_EXCHANGES, remove_credentials, retrier,
retrier_async)
from freqtrade.misc import chunks, deep_merge_dicts, safe_value_fallback2
from freqtrade.misc import (chunks, deep_merge_dicts, file_dump_json, file_load_json,
safe_value_fallback2)
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.util import FtPrecise
@@ -52,8 +54,8 @@ class Exchange:
# Parameters to add directly to buy/sell calls (like agreeing to trading agreement)
_params: Dict = {}
# Additional headers - added to the ccxt object
_headers: Dict = {}
# Additional parameters - added to the ccxt object
_ccxt_params: Dict = {}
# Dict to specify which options each exchange implements
# This defines defaults, which can be selectively overridden by subclasses using _ft_has
@@ -240,9 +242,9 @@ class Exchange:
}
if ccxt_kwargs:
logger.info('Applying additional ccxt config: %s', ccxt_kwargs)
if self._headers:
# Inject static headers after the above output to not confuse users.
ccxt_kwargs = deep_merge_dicts({'headers': self._headers}, ccxt_kwargs)
if self._ccxt_params:
# Inject static options after the above output to not confuse users.
ccxt_kwargs = deep_merge_dicts(self._ccxt_params, ccxt_kwargs)
if ccxt_kwargs:
ex_config.update(ccxt_kwargs)
try:
@@ -406,7 +408,7 @@ class Exchange:
else:
return DataFrame()
def _get_contract_size(self, pair: str) -> float:
def get_contract_size(self, pair: str) -> float:
if self.trading_mode == TradingMode.FUTURES:
market = self.markets[pair]
contract_size: float = 1.0
@@ -419,7 +421,7 @@ class Exchange:
def _trades_contracts_to_amount(self, trades: List) -> List:
if len(trades) > 0 and 'symbol' in trades[0]:
contract_size = self._get_contract_size(trades[0]['symbol'])
contract_size = self.get_contract_size(trades[0]['symbol'])
if contract_size != 1:
for trade in trades:
trade['amount'] = trade['amount'] * contract_size
@@ -427,7 +429,7 @@ class Exchange:
def _order_contracts_to_amount(self, order: Dict) -> Dict:
if 'symbol' in order and order['symbol'] is not None:
contract_size = self._get_contract_size(order['symbol'])
contract_size = self.get_contract_size(order['symbol'])
if contract_size != 1:
for prop in self._ft_has.get('order_props_in_contracts', []):
if prop in order and order[prop] is not None:
@@ -436,19 +438,13 @@ class Exchange:
def _amount_to_contracts(self, pair: str, amount: float) -> float:
contract_size = self._get_contract_size(pair)
if contract_size and contract_size != 1:
return amount / contract_size
else:
return amount
contract_size = self.get_contract_size(pair)
return amount_to_contracts(amount, contract_size)
def _contracts_to_amount(self, pair: str, num_contracts: float) -> float:
contract_size = self._get_contract_size(pair)
if contract_size and contract_size != 1:
return num_contracts * contract_size
else:
return num_contracts
contract_size = self.get_contract_size(pair)
return contracts_to_amount(num_contracts, contract_size)
def set_sandbox(self, api: ccxt.Exchange, exchange_config: dict, name: str) -> None:
if exchange_config.get('sandbox'):
@@ -672,6 +668,12 @@ class Exchange:
f"Freqtrade does not support {mm_value} {trading_mode.value} on {self.name}"
)
def get_option(self, param: str, default: Any = None) -> Any:
"""
Get parameter value from _ft_has
"""
return self._ft_has.get(param, default)
def exchange_has(self, endpoint: str) -> bool:
"""
Checks if exchange implements a specific API endpoint.
@@ -2207,6 +2209,7 @@ class Exchange:
@retrier_async
async def get_market_leverage_tiers(self, symbol: str) -> Tuple[str, List[Dict]]:
""" Leverage tiers per symbol """
try:
tier = await self._api_async.fetch_market_leverage_tiers(symbol)
return symbol, tier
@@ -2238,12 +2241,21 @@ class Exchange:
tiers: Dict[str, List[Dict]] = {}
# Be verbose here, as this delays startup by ~1 minute.
logger.info(
f"Initializing leverage_tiers for {len(symbols)} markets. "
"This will take about a minute.")
tiers_cached = self.load_cached_leverage_tiers(self._config['stake_currency'])
if tiers_cached:
tiers = tiers_cached
coros = [self.get_market_leverage_tiers(symbol) for symbol in sorted(symbols)]
coros = [
self.get_market_leverage_tiers(symbol)
for symbol in sorted(symbols) if symbol not in tiers]
# Be verbose here, as this delays startup by ~1 minute.
if coros:
logger.info(
f"Initializing leverage_tiers for {len(symbols)} markets. "
"This will take about a minute.")
else:
logger.info("Using cached leverage_tiers.")
async def gather_results():
return await asyncio.gather(*input_coro, return_exceptions=True)
@@ -2255,7 +2267,8 @@ class Exchange:
for symbol, res in results:
tiers[symbol] = res
if len(coros) > 0:
self.cache_leverage_tiers(tiers, self._config['stake_currency'])
logger.info(f"Done initializing {len(symbols)} markets.")
return tiers
@@ -2264,6 +2277,30 @@ class Exchange:
else:
return {}
def cache_leverage_tiers(self, tiers: Dict[str, List[Dict]], stake_currency: str) -> None:
filename = self._config['datadir'] / "futures" / f"leverage_tiers_{stake_currency}.json"
if not filename.parent.is_dir():
filename.parent.mkdir(parents=True)
data = {
"updated": datetime.now(timezone.utc),
"data": tiers,
}
file_dump_json(filename, data)
def load_cached_leverage_tiers(self, stake_currency: str) -> Optional[Dict[str, List[Dict]]]:
filename = self._config['datadir'] / "futures" / f"leverage_tiers_{stake_currency}.json"
if filename.is_file():
tiers = file_load_json(filename)
updated = tiers.get('updated')
if updated:
updated_dt = parser.parse(updated)
if updated_dt < datetime.now(timezone.utc) - timedelta(days=1):
logger.info("Cached leverage tiers are outdated. Will update.")
return None
return tiers['data']
return None
def fill_leverage_tiers(self) -> None:
"""
Assigns property _leverage_tiers to a dictionary of information about the leverage
@@ -2279,10 +2316,10 @@ class Exchange:
def parse_leverage_tier(self, tier) -> Dict:
info = tier.get('info', {})
return {
'min': tier['minNotional'],
'max': tier['maxNotional'],
'mmr': tier['maintenanceMarginRate'],
'lev': tier['maxLeverage'],
'minNotional': tier['minNotional'],
'maxNotional': tier['maxNotional'],
'maintenanceMarginRate': tier['maintenanceMarginRate'],
'maxLeverage': tier['maxLeverage'],
'maintAmt': float(info['cum']) if 'cum' in info else None,
}
@@ -2311,18 +2348,18 @@ class Exchange:
pair_tiers = self._leverage_tiers[pair]
if stake_amount == 0:
return self._leverage_tiers[pair][0]['lev'] # Max lev for lowest amount
return self._leverage_tiers[pair][0]['maxLeverage'] # Max lev for lowest amount
for tier_index in range(len(pair_tiers)):
tier = pair_tiers[tier_index]
lev = tier['lev']
lev = tier['maxLeverage']
if tier_index < len(pair_tiers) - 1:
next_tier = pair_tiers[tier_index + 1]
next_floor = next_tier['min'] / next_tier['lev']
next_floor = next_tier['minNotional'] / next_tier['maxLeverage']
if next_floor > stake_amount: # Next tier min too high for stake amount
return min((tier['max'] / stake_amount), lev)
return min((tier['maxNotional'] / stake_amount), lev)
#
# With the two leverage tiers below,
# - a stake amount of 150 would mean a max leverage of (10000 / 150) = 66.66
@@ -2343,10 +2380,11 @@ class Exchange:
#
else: # if on the last tier
if stake_amount > tier['max']: # If stake is > than max tradeable amount
if stake_amount > tier['maxNotional']:
# If stake is > than max tradeable amount
raise InvalidOrderException(f'Amount {stake_amount} too high for {pair}')
else:
return tier['lev']
return tier['maxLeverage']
raise OperationalException(
'Looped through all tiers without finding a max leverage. Should never be reached'
@@ -2399,6 +2437,7 @@ class Exchange:
pair: str,
open_rate: float,
amount: float, # quote currency, includes leverage
stake_amount: float,
leverage: float,
is_short: bool
) -> Optional[float]:
@@ -2408,13 +2447,13 @@ class Exchange:
elif (
self.trading_mode == TradingMode.FUTURES
):
wallet_balance = (amount * open_rate) / leverage
isolated_liq = self.get_or_calculate_liquidation_price(
pair=pair,
open_rate=open_rate,
is_short=is_short,
position=amount,
wallet_balance=wallet_balance,
amount=amount,
stake_amount=stake_amount,
wallet_balance=stake_amount, # In isolated mode, stake-amount = wallet size
mm_ex_1=0.0,
upnl_ex_1=0.0,
)
@@ -2589,14 +2628,14 @@ class Exchange:
# Dry-run
open_rate: float, # Entry price of position
is_short: bool,
position: float, # Absolute value of position size
amount: float, # Absolute value of position size
stake_amount: float,
wallet_balance: float, # Or margin balance
mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]:
"""
Set's the margin mode on the exchange to cross or isolated for a specific pair
:param pair: base/quote currency pair (e.g. "ADA/USDT")
"""
if self.trading_mode == TradingMode.SPOT:
return None
@@ -2610,7 +2649,8 @@ class Exchange:
pair=pair,
open_rate=open_rate,
is_short=is_short,
position=position,
amount=amount,
stake_amount=stake_amount,
wallet_balance=wallet_balance,
mm_ex_1=mm_ex_1,
upnl_ex_1=upnl_ex_1
@@ -2639,22 +2679,24 @@ class Exchange:
pair: str,
open_rate: float, # Entry price of position
is_short: bool,
position: float, # Absolute value of position size
amount: float,
stake_amount: float,
wallet_balance: float, # Or margin balance
mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]:
"""
Important: Must be fetching data from cached values as this is used by backtesting!
PERPETUAL:
gateio: https://www.gate.io/help/futures/perpetual/22160/calculation-of-liquidation-price
okex: https://www.okex.com/support/hc/en-us/articles/
360053909592-VI-Introduction-to-the-isolated-mode-of-Single-Multi-currency-Portfolio-margin
Important: Must be fetching data from cached values as this is used by backtesting!
:param exchange_name:
:param open_rate: Entry price of position
:param is_short: True if the trade is a short, false otherwise
:param position: Absolute value of position size incl. leverage (in base currency)
:param amount: Absolute value of position size incl. leverage (in base currency)
:param stake_amount: Stake amount - Collateral in settle currency.
:param trading_mode: SPOT, MARGIN, FUTURES, etc.
:param margin_mode: Either ISOLATED or CROSS
:param wallet_balance: Amount of margin_mode in the wallet being used to trade
@@ -2668,7 +2710,7 @@ class Exchange:
market = self.markets[pair]
taker_fee_rate = market['taker']
mm_ratio, _ = self.get_maintenance_ratio_and_amt(pair, position)
mm_ratio, _ = self.get_maintenance_ratio_and_amt(pair, stake_amount)
if self.trading_mode == TradingMode.FUTURES and self.margin_mode == MarginMode.ISOLATED:
@@ -2676,7 +2718,7 @@ class Exchange:
raise OperationalException(
"Freqtrade does not yet support inverse contracts")
value = wallet_balance / position
value = wallet_balance / amount
mm_ratio_taker = (mm_ratio + taker_fee_rate)
if is_short:
@@ -2712,8 +2754,8 @@ class Exchange:
pair_tiers = self._leverage_tiers[pair]
for tier in reversed(pair_tiers):
if nominal_value >= tier['min']:
return (tier['mmr'], tier['maintAmt'])
if nominal_value >= tier['minNotional']:
return (tier['maintenanceMarginRate'], tier['maintAmt'])
raise OperationalException("nominal value can not be lower than 0")
# The lowest notional_floor for any pair in fetch_leverage_tiers is always 0 because it
@@ -2855,6 +2897,33 @@ def market_is_active(market: Dict) -> bool:
return market.get('active', True) is not False
def amount_to_contracts(amount: float, contract_size: Optional[float]) -> float:
"""
Convert amount to contracts.
:param amount: amount to convert
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: num-contracts
"""
if contract_size and contract_size != 1:
return amount / contract_size
else:
return amount
def contracts_to_amount(num_contracts: float, contract_size: Optional[float]) -> float:
"""
Takes num-contracts and converts it to contract size
:param num_contracts: number of contracts
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: Amount
"""
if contract_size and contract_size != 1:
return num_contracts * contract_size
else:
return num_contracts
def amount_to_precision(amount: float, amount_precision: Optional[float],
precisionMode: Optional[int]) -> float:
"""
@@ -2879,6 +2948,29 @@ def amount_to_precision(amount: float, amount_precision: Optional[float],
return amount
def amount_to_contract_precision(
amount, amount_precision: Optional[float], precisionMode: Optional[int],
contract_size: Optional[float]) -> float:
"""
Returns the amount to buy or sell to a precision the Exchange accepts
including calculation to and from contracts.
Re-implementation of ccxt internal methods - ensuring we can test the result is correct
based on our definitions.
:param amount: amount to truncate
:param amount_precision: amount precision to use.
should be retrieved from markets[pair]['precision']['amount']
:param precisionMode: precision mode to use. Should be used from precisionMode
one of ccxt's DECIMAL_PLACES, SIGNIFICANT_DIGITS, or TICK_SIZE
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: truncated amount
"""
if amount_precision is not None and precisionMode is not None:
contracts = amount_to_contracts(amount, contract_size)
amount_p = amount_to_precision(contracts, amount_precision, precisionMode)
return contracts_to_amount(amount_p, contract_size)
return amount
def price_to_precision(price: float, price_precision: Optional[float],
precisionMode: Optional[int]) -> float:
"""

View File

@@ -25,7 +25,6 @@ class Gateio(Exchange):
_ft_has: Dict = {
"ohlcv_candle_limit": 1000,
"ohlcv_volume_currency": "quote",
"time_in_force_parameter": "timeInForce",
"order_time_in_force": ['gtc', 'ioc'],
"stoploss_order_types": {"limit": "limit"},
@@ -34,7 +33,6 @@ class Gateio(Exchange):
_ft_has_futures: Dict = {
"needs_trading_fees": True,
"ohlcv_volume_currency": "base",
"fee_cost_in_contracts": False, # Set explicitly to false for clarity
"order_props_in_contracts": ['amount', 'filled', 'remaining'],
}

View File

@@ -39,6 +39,8 @@ class Okx(Exchange):
net_only = True
_ccxt_params: Dict = {'options': {'brokerId': 'ffb5405ad327SUDE'}}
def ohlcv_candle_limit(
self, timeframe: str, candle_type: CandleType, since_ms: Optional[int] = None) -> int:
"""
@@ -144,4 +146,4 @@ class Okx(Exchange):
return float('inf')
pair_tiers = self._leverage_tiers[pair]
return pair_tiers[-1]['max'] / leverage
return pair_tiers[-1]['maxNotional'] / leverage

View File

@@ -421,7 +421,7 @@ class FreqaiDataDrawer:
)
# if self.live:
self.model_dictionary[dk.model_filename] = model
self.model_dictionary[coin] = model
self.pair_dict[coin]["model_filename"] = dk.model_filename
self.pair_dict[coin]["data_path"] = str(dk.data_path)
self.save_drawer_to_disk()
@@ -460,8 +460,8 @@ class FreqaiDataDrawer:
)
# try to access model in memory instead of loading object from disk to save time
if dk.live and dk.model_filename in self.model_dictionary:
model = self.model_dictionary[dk.model_filename]
if dk.live and coin in self.model_dictionary:
model = self.model_dictionary[coin]
elif not dk.keras:
model = load(dk.data_path / f"{dk.model_filename}_model.joblib")
else:
@@ -566,7 +566,6 @@ class FreqaiDataDrawer:
for training according to user defined train_period_days
metadata: dict = strategy furnished pair metadata
"""
with self.history_lock:
corr_dataframes: Dict[Any, Any] = {}
base_dataframes: Dict[Any, Any] = {}

View File

@@ -454,7 +454,6 @@ class FreqaiDataKitchen:
logger.info("reduced feature dimension by %s", n_components - n_keep_components)
logger.info("explained variance %f", np.sum(pca2.explained_variance_ratio_))
train_components = pca2.transform(self.data_dictionary["train_features"])
test_components = pca2.transform(self.data_dictionary["test_features"])
self.data_dictionary["train_features"] = pd.DataFrame(
data=train_components,
@@ -468,6 +467,7 @@ class FreqaiDataKitchen:
self.training_features_list = self.data_dictionary["train_features"].columns
if self.freqai_config.get('data_split_parameters', {}).get('test_size', 0.1) != 0:
test_components = pca2.transform(self.data_dictionary["test_features"])
self.data_dictionary["test_features"] = pd.DataFrame(
data=test_components,
columns=["PC" + str(i) for i in range(0, n_keep_components)],
@@ -506,10 +506,26 @@ class FreqaiDataKitchen:
# logger.info("computing average mean distance for all training points")
pairwise = pairwise_distances(
self.data_dictionary["train_features"], n_jobs=self.thread_count)
avg_mean_dist = pairwise.mean(axis=1).mean()
# remove the diagonal distances which are itself distances ~0
np.fill_diagonal(pairwise, np.NaN)
pairwise = pairwise.reshape(-1, 1)
avg_mean_dist = pairwise[~np.isnan(pairwise)].mean()
return avg_mean_dist
def get_outlier_percentage(self, dropped_pts: npt.NDArray) -> float:
"""
Check if more than X% of points werer dropped during outlier detection.
"""
outlier_protection_pct = self.freqai_config["feature_parameters"].get(
"outlier_protection_percentage", 30)
outlier_pct = (dropped_pts.sum() / len(dropped_pts)) * 100
if outlier_pct >= outlier_protection_pct:
self.svm_model = None
return outlier_pct
else:
return 0.0
def use_SVM_to_remove_outliers(self, predict: bool) -> None:
"""
Build/inference a Support Vector Machine to detect outliers
@@ -547,8 +563,16 @@ class FreqaiDataKitchen:
self.data_dictionary["train_features"]
)
y_pred = self.svm_model.predict(self.data_dictionary["train_features"])
dropped_points = np.where(y_pred == -1, 0, y_pred)
kept_points = np.where(y_pred == -1, 0, y_pred)
# keep_index = np.where(y_pred == 1)
outlier_pct = self.get_outlier_percentage(1 - kept_points)
if outlier_pct:
logger.warning(
f"SVM detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
return
self.data_dictionary["train_features"] = self.data_dictionary["train_features"][
(y_pred == 1)
]
@@ -560,7 +584,7 @@ class FreqaiDataKitchen:
]
logger.info(
f"SVM tossed {len(y_pred) - dropped_points.sum()}"
f"SVM tossed {len(y_pred) - kept_points.sum()}"
f" train points from {len(y_pred)} total points."
)
@@ -569,7 +593,7 @@ class FreqaiDataKitchen:
# to reduce code duplication
if self.freqai_config['data_split_parameters'].get('test_size', 0.1) != 0:
y_pred = self.svm_model.predict(self.data_dictionary["test_features"])
dropped_points = np.where(y_pred == -1, 0, y_pred)
kept_points = np.where(y_pred == -1, 0, y_pred)
self.data_dictionary["test_features"] = self.data_dictionary["test_features"][
(y_pred == 1)
]
@@ -580,7 +604,7 @@ class FreqaiDataKitchen:
]
logger.info(
f"SVM tossed {len(y_pred) - dropped_points.sum()}"
f"SVM tossed {len(y_pred) - kept_points.sum()}"
f" test points from {len(y_pred)} total points."
)
@@ -598,6 +622,8 @@ class FreqaiDataKitchen:
is an outlier.
"""
from math import cos, sin
if predict:
train_ft_df = self.data_dictionary['train_features']
pred_ft_df = self.data_dictionary['prediction_features']
@@ -616,28 +642,60 @@ class FreqaiDataKitchen:
else:
MinPts = len(self.data_dictionary['train_features'].columns) * 2
# measure pairwise distances to train_features.shape[1]*2 nearest neighbours
def normalise_distances(distances):
normalised_distances = (distances - distances.min()) / \
(distances.max() - distances.min())
return normalised_distances
def rotate_point(origin, point, angle):
# rotate a point counterclockwise by a given angle (in radians)
# around a given origin
x = origin[0] + cos(angle) * (point[0] - origin[0]) - \
sin(angle) * (point[1] - origin[1])
y = origin[1] + sin(angle) * (point[0] - origin[0]) + \
cos(angle) * (point[1] - origin[1])
return (x, y)
MinPts = int(len(self.data_dictionary['train_features'].index) * 0.25)
# measure pairwise distances to nearest neighbours
neighbors = NearestNeighbors(
n_neighbors=MinPts, n_jobs=self.thread_count)
neighbors_fit = neighbors.fit(self.data_dictionary['train_features'])
distances, _ = neighbors_fit.kneighbors(self.data_dictionary['train_features'])
distances = np.sort(distances, axis=0)
index_ten_pct = int(len(distances[:, 1]) * 0.1)
distances = distances[index_ten_pct:, 1]
epsilon = distances[-1]
distances = np.sort(distances, axis=0).mean(axis=1)
normalised_distances = normalise_distances(distances)
x_range = np.linspace(0, 1, len(distances))
line = np.linspace(normalised_distances[0],
normalised_distances[-1], len(normalised_distances))
deflection = np.abs(normalised_distances - line)
max_deflection_loc = np.where(deflection == deflection.max())[0][0]
origin = x_range[max_deflection_loc], line[max_deflection_loc]
point = x_range[max_deflection_loc], normalised_distances[max_deflection_loc]
rot_angle = np.pi / 4
elbow_loc = rotate_point(origin, point, rot_angle)
epsilon = elbow_loc[1] * (distances[-1] - distances[0]) + distances[0]
clustering = DBSCAN(eps=epsilon, min_samples=MinPts,
n_jobs=int(self.thread_count)).fit(
self.data_dictionary['train_features']
)
logger.info(f'DBSCAN found eps of {epsilon}.')
logger.info(f'DBSCAN found eps of {epsilon:.2f}.')
self.data['DBSCAN_eps'] = epsilon
self.data['DBSCAN_min_samples'] = MinPts
dropped_points = np.where(clustering.labels_ == -1, 1, 0)
outlier_pct = self.get_outlier_percentage(dropped_points)
if outlier_pct:
logger.warning(
f"DBSCAN detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
return
self.data_dictionary['train_features'] = self.data_dictionary['train_features'][
(clustering.labels_ != -1)
]
@@ -655,114 +713,6 @@ class FreqaiDataKitchen:
return
def compute_inlier_metric(self, set_='train') -> None:
"""
Compute inlier metric from backwards distance distributions.
This metric defines how well features from a timepoint fit
into previous timepoints.
"""
import scipy.stats as ss
no_prev_pts = self.freqai_config["feature_parameters"]["inlier_metric_window"]
weib_pct = self.freqai_config["feature_parameters"]["inlier_metric_weibull_cutoff"]
if set_ == 'train':
compute_df = copy.deepcopy(self.data_dictionary['train_features'])
elif set_ == 'test':
compute_df = copy.deepcopy(self.data_dictionary['test_features'])
else:
compute_df = copy.deepcopy(self.data_dictionary['prediction_features'])
compute_df_reindexed = compute_df.reindex(
index=np.flip(compute_df.index)
)
pairwise = pd.DataFrame(
np.triu(
pairwise_distances(compute_df_reindexed, n_jobs=self.thread_count)
),
columns=compute_df_reindexed.index,
index=compute_df_reindexed.index
)
pairwise = pairwise.round(5)
column_labels = [
'{}{}'.format('d', i) for i in range(1, no_prev_pts + 1)
]
distances = pd.DataFrame(
columns=column_labels, index=compute_df.index
)
for index in compute_df.index[no_prev_pts:]:
current_row = pairwise.loc[[index]]
current_row_no_zeros = current_row.loc[
:, (current_row != 0).any(axis=0)
]
distances.loc[[index]] = current_row_no_zeros.iloc[
:, :no_prev_pts
]
distances = distances.replace([np.inf, -np.inf], np.nan)
drop_index = pd.isnull(distances).any(1)
distances = distances[drop_index == 0]
inliers = pd.DataFrame(index=distances.index)
for key in distances.keys():
current_distances = distances[key].dropna()
fit_params = ss.weibull_min.fit(current_distances)
cutoff = ss.weibull_min.ppf(weib_pct, *fit_params)
is_inlier = np.where(
current_distances <= cutoff, 1, 0
)
df_inlier = pd.DataFrame(
{key + '_IsInlier': is_inlier}, index=distances.index
)
inliers = pd.concat(
[inliers, df_inlier], axis=1
)
inlier_metric = pd.DataFrame(
data=inliers.sum(axis=1) / no_prev_pts,
columns=['inlier_metric'],
index=compute_df.index
)
inlier_metric = 2 * (inlier_metric - inlier_metric.min()) / \
(inlier_metric.max() - inlier_metric.min()) - 1
if set_ in ('train', 'test'):
inlier_metric = inlier_metric.iloc[no_prev_pts:]
compute_df = compute_df.iloc[no_prev_pts:]
self.remove_beginning_points_from_data_dict(set_, no_prev_pts)
self.data_dictionary[f'{set_}_features'] = pd.concat(
[compute_df, inlier_metric], axis=1)
else:
self.data_dictionary['prediction_features'] = pd.concat(
[compute_df, inlier_metric], axis=1)
self.data_dictionary['prediction_features'].fillna(0, inplace=True)
return None
def remove_beginning_points_from_data_dict(self, set_='train', no_prev_pts: int = 10):
features = self.data_dictionary[f'{set_}_features']
weights = self.data_dictionary[f'{set_}_weights']
labels = self.data_dictionary[f'{set_}_labels']
self.data_dictionary[f'{set_}_weights'] = weights[no_prev_pts:]
self.data_dictionary[f'{set_}_features'] = features.iloc[no_prev_pts:]
self.data_dictionary[f'{set_}_labels'] = labels.iloc[no_prev_pts:]
def add_noise_to_training_features(self) -> None:
"""
Add noise to train features to reduce the risk of overfitting.
"""
mu = 0 # no shift
sigma = self.freqai_config["feature_parameters"]["noise_standard_deviation"]
compute_df = self.data_dictionary['train_features']
noise = np.random.normal(mu, sigma, [compute_df.shape[0], compute_df.shape[1]])
self.data_dictionary['train_features'] += noise
return
def find_features(self, dataframe: DataFrame) -> None:
"""
Find features in the strategy provided dataframe
@@ -801,9 +751,17 @@ class FreqaiDataKitchen:
0,
)
outlier_pct = self.get_outlier_percentage(1 - do_predict)
if outlier_pct:
logger.warning(
f"DI detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
return
if (len(do_predict) - do_predict.sum()) > 0:
logger.info(
f"DI tossed {len(do_predict) - do_predict.sum():.2f} predictions for "
f"DI tossed {len(do_predict) - do_predict.sum()} predictions for "
"being too far from training data"
)
@@ -978,13 +936,6 @@ class FreqaiDataKitchen:
data_load_timerange.stopts = int(time)
retrain = True
# logger.info(
# f"downloading data for "
# f"{(data_load_timerange.stopts-data_load_timerange.startts)/SECONDS_IN_DAY:.2f} "
# " days. "
# f"Extension of {additional_seconds/SECONDS_IN_DAY:.2f} days"
# )
return retrain, trained_timerange, data_load_timerange
def set_new_model_names(self, pair: str, trained_timerange: TimeRange):

View File

@@ -66,6 +66,7 @@ class IFreqaiModel(ABC):
"data_split_parameters", {})
self.model_training_parameters: Dict[str, Any] = config.get("freqai", {}).get(
"model_training_parameters", {})
self.feature_parameters = config.get("freqai", {}).get("feature_parameters")
self.retrain = False
self.first = True
self.set_full_path()
@@ -73,21 +74,21 @@ class IFreqaiModel(ABC):
self.dd = FreqaiDataDrawer(Path(self.full_path), self.config, self.follow_mode)
self.identifier: str = self.freqai_info.get("identifier", "no_id_provided")
self.scanning = False
self.ft_params = self.freqai_info["feature_parameters"]
self.keras: bool = self.freqai_info.get("keras", False)
if self.keras and self.ft_params.get("DI_threshold", 0):
self.ft_params["DI_threshold"] = 0
if self.keras and self.freqai_info.get("feature_parameters", {}).get("DI_threshold", 0):
self.freqai_info["feature_parameters"]["DI_threshold"] = 0
logger.warning("DI threshold is not configured for Keras models yet. Deactivating.")
self.CONV_WIDTH = self.freqai_info.get("conv_width", 2)
if self.ft_params.get("inlier_metric_window", 0):
self.CONV_WIDTH = self.ft_params.get("inlier_metric_window", 0) * 2
self.pair_it = 0
self.pair_it_train = 0
self.total_pairs = len(self.config.get("exchange", {}).get("pair_whitelist"))
self.last_trade_database_summary: DataFrame = {}
self.current_trade_database_summary: DataFrame = {}
self.analysis_lock = Lock()
self.inference_time: float = 0
self.train_time: float = 0
self.begin_time: float = 0
self.begin_time_train: float = 0
self.base_tf_seconds = timeframe_to_seconds(self.config['timeframe'])
def assert_config(self, config: Dict[str, Any]) -> None:
@@ -130,11 +131,20 @@ class IFreqaiModel(ABC):
dk = self.start_backtesting(dataframe, metadata, self.dk)
dataframe = dk.remove_features_from_df(dk.return_dataframe)
del dk
self.clean_up()
if self.live:
self.inference_timer('stop')
return dataframe
def clean_up(self):
"""
Objects that should be handled by GC already between coins, but
are explicitly shown here to help demonstrate the non-persistence of these
objects.
"""
self.model = None
self.dk = None
@threaded
def start_scanning(self, strategy: IStrategy) -> None:
"""
@@ -161,9 +171,11 @@ class IFreqaiModel(ABC):
dk.set_paths(pair, new_trained_timerange.stopts)
if retrain:
self.train_timer('start')
self.train_model_in_series(
new_trained_timerange, pair, strategy, dk, data_load_timerange
)
self.train_timer('stop')
self.dd.save_historic_predictions_to_disk()
@@ -385,25 +397,24 @@ class IFreqaiModel(ABC):
def data_cleaning_train(self, dk: FreqaiDataKitchen) -> None:
"""
Base data cleaning method for train.
Functions here improve/modify the input data by identifying outliers,
computing additional metrics, adding noise, reducing dimensionality etc.
Base data cleaning method for train
Any function inside this method should drop training data points from the filtered_dataframe
based on user decided logic. See FreqaiDataKitchen::use_SVM_to_remove_outliers() for an
example of how outlier data points are dropped from the dataframe used for training.
"""
ft_params = self.freqai_info["feature_parameters"]
if ft_params.get(
if self.freqai_info["feature_parameters"].get(
"principal_component_analysis", False
):
dk.principal_component_analysis()
if ft_params.get("use_SVM_to_remove_outliers", False):
if self.freqai_info["feature_parameters"].get("use_SVM_to_remove_outliers", False):
dk.use_SVM_to_remove_outliers(predict=False)
if ft_params.get("DI_threshold", 0):
if self.freqai_info["feature_parameters"].get("DI_threshold", 0):
dk.data["avg_mean_dist"] = dk.compute_distances()
if ft_params.get("use_DBSCAN_to_remove_outliers", False):
if self.freqai_info["feature_parameters"].get("use_DBSCAN_to_remove_outliers", False):
if dk.pair in self.dd.old_DBSCAN_eps:
eps = self.dd.old_DBSCAN_eps[dk.pair]
else:
@@ -411,36 +422,29 @@ class IFreqaiModel(ABC):
dk.use_DBSCAN_to_remove_outliers(predict=False, eps=eps)
self.dd.old_DBSCAN_eps[dk.pair] = dk.data['DBSCAN_eps']
if ft_params.get('inlier_metric_window', 0):
dk.compute_inlier_metric(set_='train')
if self.freqai_info["data_split_parameters"]["test_size"] > 0:
dk.compute_inlier_metric(set_='test')
if self.freqai_info["feature_parameters"].get('noise_standard_deviation', 0):
dk.add_noise_to_training_features()
def data_cleaning_predict(self, dk: FreqaiDataKitchen, dataframe: DataFrame) -> None:
"""
Base data cleaning method for predict.
Functions here are complementary to the functions of data_cleaning_train.
These functions each modify dk.do_predict, which is a dataframe with equal length
to the number of candles coming from and returning to the strategy. Inside do_predict,
1 allows prediction and < 0 signals to the strategy that the model is not confident in
the prediction.
See FreqaiDataKitchen::remove_outliers() for an example
of how the do_predict vector is modified. do_predict is ultimately passed back to strategy
for buy signals.
"""
ft_params = self.freqai_info["feature_parameters"]
if ft_params.get('inlier_metric_window', 0):
dk.compute_inlier_metric(set_='predict')
if ft_params.get(
if self.freqai_info["feature_parameters"].get(
"principal_component_analysis", False
):
dk.pca_transform(dataframe)
if ft_params.get("use_SVM_to_remove_outliers", False):
if self.freqai_info["feature_parameters"].get("use_SVM_to_remove_outliers", False):
dk.use_SVM_to_remove_outliers(predict=True)
if ft_params.get("DI_threshold", 0):
if self.freqai_info["feature_parameters"].get("DI_threshold", 0):
dk.check_if_pred_in_training_spaces()
if ft_params.get("use_DBSCAN_to_remove_outliers", False):
if self.freqai_info["feature_parameters"].get("use_DBSCAN_to_remove_outliers", False):
dk.use_DBSCAN_to_remove_outliers(predict=True)
def model_exists(
@@ -490,8 +494,7 @@ class IFreqaiModel(ABC):
data_load_timerange: TimeRange,
):
"""
Retrieve data and train model in single threaded mode (only used if model directory is empty
upon startup for dry/live )
Retrieve data and train model.
:param new_trained_timerange: TimeRange = the timerange to train the model on
:param metadata: dict = strategy provided metadata
:param strategy: IStrategy = user defined strategy object
@@ -622,6 +625,24 @@ class IFreqaiModel(ABC):
self.inference_time = 0
return
def train_timer(self, do='start'):
"""
Timer designed to track the cumulative time spent training the full pairlist in
FreqAI.
"""
if do == 'start':
self.pair_it_train += 1
self.begin_time_train = time.time()
elif do == 'stop':
end = time.time()
self.train_time += (end - self.begin_time_train)
if self.pair_it_train == self.total_pairs:
logger.info(
f'Total time spent training pairlist {self.train_time:.2f} seconds')
self.pair_it_train = 0
self.train_time = 0
return
# Following methods which are overridden by user made prediction models.
# See freqai/prediction_models/CatboostPredictionModel.py for an example.

View File

@@ -21,8 +21,7 @@ from freqtrade.enums import (ExitCheckTuple, ExitType, RPCMessageType, RunMode,
State, TradingMode)
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
InvalidOrderException, PricingError)
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
from freqtrade.exchange.exchange import timeframe_to_next_date
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds
from freqtrade.misc import safe_value_fallback, safe_value_fallback2
from freqtrade.mixins import LoggingMixin
from freqtrade.persistence import Order, PairLocks, Trade, init_db
@@ -240,7 +239,7 @@ class FreqtradeBot(LoggingMixin):
'status':
f"{len(open_trades)} open trades active.\n\n"
f"Handle these trades manually on {self.exchange.name}, "
f"or '/start' the bot again and use '/stopbuy' "
f"or '/start' the bot again and use '/stopentry' "
f"to handle open trades gracefully. \n"
f"{'Note: Trades are simulated (dry run).' if self.config['dry_run'] else ''}",
}
@@ -271,7 +270,7 @@ class FreqtradeBot(LoggingMixin):
Return the number of free open trades slots or 0 if
max number of open trades reached
"""
open_trades = len(Trade.get_open_trades())
open_trades = Trade.get_open_trade_count()
return max(0, self.config['max_open_trades'] - open_trades)
def update_funding_fees(self):
@@ -290,13 +289,14 @@ class FreqtradeBot(LoggingMixin):
def startup_backpopulate_precision(self):
trades = Trade.get_trades([Trade.precision_mode.is_(None)])
trades = Trade.get_trades([Trade.contract_size.is_(None)])
for trade in trades:
if trade.exchange != self.exchange.id:
continue
trade.precision_mode = self.exchange.precisionMode
trade.amount_precision = self.exchange.get_precision_amount(trade.pair)
trade.price_precision = self.exchange.get_precision_price(trade.pair)
trade.contract_size = self.exchange.get_contract_size(trade.pair)
Trade.commit()
def startup_update_open_orders(self):
@@ -755,6 +755,7 @@ class FreqtradeBot(LoggingMixin):
amount_precision=self.exchange.get_precision_amount(pair),
price_precision=self.exchange.get_precision_price(pair),
precision_mode=self.exchange.precisionMode,
contract_size=self.exchange.get_contract_size(pair),
)
else:
# This is additional buy, we reset fee_open_currency so timeout checking can work
@@ -1551,9 +1552,10 @@ class FreqtradeBot(LoggingMixin):
trade.close_rate_requested = limit
trade.exit_reason = exit_reason
# Lock pair for one candle to prevent immediate re-trading
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),
reason='Auto lock')
if not sub_trade_amt:
# Lock pair for one candle to prevent immediate re-trading
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),
reason='Auto lock')
self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj)
# In case of market sell orders the order can be closed immediately
@@ -1733,6 +1735,7 @@ class FreqtradeBot(LoggingMixin):
leverage=trade.leverage,
pair=trade.pair,
amount=trade.amount,
stake_amount=trade.stake_amount,
open_rate=trade.open_rate,
is_short=trade.is_short
))

View File

@@ -23,7 +23,8 @@ from freqtrade.data.dataprovider import DataProvider
from freqtrade.enums import (BacktestState, CandleType, ExitCheckTuple, ExitType, RunMode,
TradingMode)
from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
from freqtrade.exchange import (amount_to_contract_precision, price_to_precision,
timeframe_to_minutes, timeframe_to_seconds)
from freqtrade.mixins import LoggingMixin
from freqtrade.optimize.backtest_caching import get_strategy_run_id
from freqtrade.optimize.bt_progress import BTProgress
@@ -266,7 +267,7 @@ class Backtesting:
funding_rates_dict = history.load_data(
datadir=self.config['datadir'],
pairs=self.pairlists.whitelist,
timeframe=self.exchange._ft_has['mark_ohlcv_timeframe'],
timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
timerange=self.timerange,
startup_candles=0,
fail_without_data=True,
@@ -278,12 +279,12 @@ class Backtesting:
mark_rates_dict = history.load_data(
datadir=self.config['datadir'],
pairs=self.pairlists.whitelist,
timeframe=self.exchange._ft_has['mark_ohlcv_timeframe'],
timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
timerange=self.timerange,
startup_candles=0,
fail_without_data=True,
data_format=self.config.get('dataformat_ohlcv', 'json'),
candle_type=CandleType.from_string(self.exchange._ft_has["mark_ohlcv_price"])
candle_type=CandleType.from_string(self.exchange.get_option("mark_ohlcv_price"))
)
# Combine data to avoid combining the data per trade.
unavailable_pairs = []
@@ -533,12 +534,16 @@ class Backtesting:
# Check if we should increase our position
if stake_amount is not None and stake_amount > 0.0:
pos_trade = self._enter_trade(
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade)
if pos_trade is not None:
self.wallets.update()
return pos_trade
check_adjust_entry = True
if self.strategy.max_entry_position_adjustment > -1:
entry_count = trade.nr_of_successful_entries
check_adjust_entry = (entry_count <= self.strategy.max_entry_position_adjustment)
if check_adjust_entry:
pos_trade = self._enter_trade(
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade)
if pos_trade is not None:
self.wallets.update()
return pos_trade
if stake_amount is not None and stake_amount < 0.0:
amount = abs(stake_amount) / current_rate
@@ -549,7 +554,8 @@ class Backtesting:
if remaining < min_stake:
# Remaining stake is too low to be sold.
return trade
pos_trade = self._exit_trade(trade, row, current_rate, amount)
exit_ = ExitCheckTuple(ExitType.PARTIAL_EXIT)
pos_trade = self._get_exit_for_signal(trade, row, exit_, amount)
if pos_trade is not None:
order = pos_trade.orders[-1]
if self._get_order_filled(order.price, row):
@@ -569,12 +575,7 @@ class Backtesting:
# Check if we need to adjust our current positions
if self.strategy.position_adjustment_enable:
check_adjust_entry = True
if self.strategy.max_entry_position_adjustment > -1:
entry_count = trade.nr_of_successful_entries
check_adjust_entry = (entry_count <= self.strategy.max_entry_position_adjustment)
if check_adjust_entry:
trade = self._get_adjust_trade_entry_for_candle(trade, row)
trade = self._get_adjust_trade_entry_for_candle(trade, row)
enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX]
exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX]
@@ -589,14 +590,15 @@ class Backtesting:
return t
return None
def _get_exit_for_signal(self, trade: LocalTrade, row: Tuple,
exit_: ExitCheckTuple) -> Optional[LocalTrade]:
def _get_exit_for_signal(
self, trade: LocalTrade, row: Tuple, exit_: ExitCheckTuple,
amount: Optional[float] = None) -> Optional[LocalTrade]:
exit_candle_time: datetime = row[DATE_IDX].to_pydatetime()
if exit_.exit_flag:
trade.close_date = exit_candle_time
exit_reason = exit_.exit_reason
amount_ = amount if amount is not None else trade.amount
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
try:
close_rate = self._get_close_rate(row, trade, exit_, trade_dur)
@@ -605,7 +607,8 @@ class Backtesting:
# call the custom exit price,with default value as previous close_rate
current_profit = trade.calc_profit_ratio(close_rate)
order_type = self.strategy.order_types['exit']
if exit_.exit_type in (ExitType.EXIT_SIGNAL, ExitType.CUSTOM_EXIT):
if exit_.exit_type in (ExitType.EXIT_SIGNAL, ExitType.CUSTOM_EXIT,
ExitType.PARTIAL_EXIT):
# Checks and adds an exit tag, after checking that the length of the
# row has the length for an exit tag column
if (
@@ -633,22 +636,23 @@ class Backtesting:
# Confirm trade exit:
time_in_force = self.strategy.order_time_in_force['exit']
if (exit_.exit_type != ExitType.LIQUIDATION and not strategy_safe_wrapper(
self.strategy.confirm_trade_exit, default_retval=True)(
pair=trade.pair,
trade=trade, # type: ignore[arg-type]
order_type=order_type,
amount=trade.amount,
rate=close_rate,
time_in_force=time_in_force,
sell_reason=exit_reason, # deprecated
exit_reason=exit_reason,
current_time=exit_candle_time)):
if (exit_.exit_type not in (ExitType.LIQUIDATION, ExitType.PARTIAL_EXIT)
and not strategy_safe_wrapper(
self.strategy.confirm_trade_exit, default_retval=True)(
pair=trade.pair,
trade=trade, # type: ignore[arg-type]
order_type=order_type,
amount=amount_,
rate=close_rate,
time_in_force=time_in_force,
sell_reason=exit_reason, # deprecated
exit_reason=exit_reason,
current_time=exit_candle_time)):
return None
trade.exit_reason = exit_reason
return self._exit_trade(trade, row, close_rate, trade.amount)
return self._exit_trade(trade, row, close_rate, amount_)
return None
def _exit_trade(self, trade: LocalTrade, sell_row: Tuple,
@@ -656,7 +660,10 @@ class Backtesting:
self.order_id_counter += 1
exit_candle_time = sell_row[DATE_IDX].to_pydatetime()
order_type = self.strategy.order_types['exit']
amount = amount or trade.amount
# amount = amount or trade.amount
amount = amount_to_contract_precision(amount or trade.amount, trade.amount_precision,
self.precision_mode, trade.contract_size)
rate = price_to_precision(close_rate, trade.price_precision, self.precision_mode)
order = Order(
id=self.order_id_counter,
ft_trade_id=trade.id,
@@ -670,12 +677,12 @@ class Backtesting:
side=trade.exit_side,
order_type=order_type,
status="open",
price=close_rate,
average=close_rate,
price=rate,
average=rate,
amount=amount,
filled=0,
remaining=amount,
cost=amount * close_rate,
cost=amount * rate,
)
trade.orders.append(order)
return trade
@@ -821,7 +828,17 @@ class Backtesting:
if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount):
self.order_id_counter += 1
base_currency = self.exchange.get_pair_base_currency(pair)
amount = round((stake_amount / propose_rate) * leverage, 8)
precision_price = self.exchange.get_precision_price(pair)
propose_rate = price_to_precision(propose_rate, precision_price, self.precision_mode)
amount_p = (stake_amount / propose_rate) * leverage
contract_size = self.exchange.get_contract_size(pair)
precision_amount = self.exchange.get_precision_amount(pair)
amount = amount_to_contract_precision(amount_p, precision_amount, self.precision_mode,
contract_size)
# Backcalculate actual stake amount.
stake_amount = amount * propose_rate / leverage
is_short = (direction == 'short')
# Necessary for Margin trading. Disabled until support is enabled.
# interest_rate = self.exchange.get_interest_rate()
@@ -850,9 +867,10 @@ class Backtesting:
trading_mode=self.trading_mode,
leverage=leverage,
# interest_rate=interest_rate,
amount_precision=self.exchange.get_precision_amount(pair),
price_precision=self.exchange.get_precision_price(pair),
amount_precision=precision_amount,
price_precision=precision_price,
precision_mode=self.precision_mode,
contract_size=contract_size,
orders=[],
)
@@ -862,6 +880,7 @@ class Backtesting:
pair=pair,
open_rate=propose_rate,
amount=amount,
stake_amount=trade.stake_amount,
leverage=leverage,
is_short=is_short,
))

View File

@@ -24,13 +24,15 @@ from pandas import DataFrame
from freqtrade.constants import DATETIME_PRINT_FORMAT, FTHYPT_FILEVERSION, LAST_BT_RESULT_FN
from freqtrade.data.converter import trim_dataframes
from freqtrade.data.history import get_timerange
from freqtrade.enums import HyperoptState
from freqtrade.exceptions import OperationalException
from freqtrade.misc import deep_merge_dicts, file_dump_json, plural
from freqtrade.optimize.backtesting import Backtesting
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
from freqtrade.optimize.hyperopt_auto import HyperOptAuto
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss
from freqtrade.optimize.hyperopt_tools import HyperoptTools, hyperopt_serializer
from freqtrade.optimize.hyperopt_tools import (HyperoptStateContainer, HyperoptTools,
hyperopt_serializer)
from freqtrade.optimize.optimize_reports import generate_strategy_stats
from freqtrade.resolvers.hyperopt_resolver import HyperOptLossResolver
@@ -74,10 +76,14 @@ class Hyperopt:
self.dimensions: List[Dimension] = []
self.config = config
self.min_date: datetime
self.max_date: datetime
self.backtesting = Backtesting(self.config)
self.pairlist = self.backtesting.pairlists.whitelist
self.custom_hyperopt: HyperOptAuto
self.analyze_per_epoch = self.config.get('analyze_per_epoch', False)
HyperoptStateContainer.set_state(HyperoptState.STARTUP)
if not self.config.get('hyperopt'):
self.custom_hyperopt = HyperOptAuto(self.config)
@@ -290,6 +296,7 @@ class Hyperopt:
Called once per epoch to optimize whatever is configured.
Keep this function as optimized as possible!
"""
HyperoptStateContainer.set_state(HyperoptState.OPTIMIZE)
backtest_start_time = datetime.now(timezone.utc)
params_dict = self._get_params_dict(self.dimensions, raw_params)
@@ -321,6 +328,10 @@ class Hyperopt:
with self.data_pickle_file.open('rb') as f:
processed = load(f, mmap_mode='r')
if self.analyze_per_epoch:
# Data is not yet analyzed, rerun populate_indicators.
processed = self.advise_and_trim(processed)
bt_results = self.backtesting.backtest(
processed=processed,
start_date=self.min_date,
@@ -406,22 +417,33 @@ class Hyperopt:
def _set_random_state(self, random_state: Optional[int]) -> int:
return random_state or random.randint(1, 2**16 - 1)
def prepare_hyperopt_data(self) -> None:
data, timerange = self.backtesting.load_bt_data()
self.backtesting.load_bt_data_detail()
logger.info("Dataload complete. Calculating indicators")
def advise_and_trim(self, data: Dict[str, DataFrame]) -> Dict[str, DataFrame]:
preprocessed = self.backtesting.strategy.advise_all_indicators(data)
# Trim startup period from analyzed dataframe to get correct dates for output.
processed = trim_dataframes(preprocessed, timerange, self.backtesting.required_startup)
processed = trim_dataframes(preprocessed, self.timerange, self.backtesting.required_startup)
self.min_date, self.max_date = get_timerange(processed)
return processed
logger.info(f'Hyperopting with data from {self.min_date.strftime(DATETIME_PRINT_FORMAT)} '
f'up to {self.max_date.strftime(DATETIME_PRINT_FORMAT)} '
f'({(self.max_date - self.min_date).days} days)..')
# Store non-trimmed data - will be trimmed after signal generation.
dump(preprocessed, self.data_pickle_file)
def prepare_hyperopt_data(self) -> None:
HyperoptStateContainer.set_state(HyperoptState.DATALOAD)
data, self.timerange = self.backtesting.load_bt_data()
self.backtesting.load_bt_data_detail()
logger.info("Dataload complete. Calculating indicators")
if not self.analyze_per_epoch:
HyperoptStateContainer.set_state(HyperoptState.INDICATORS)
preprocessed = self.advise_and_trim(data)
logger.info(f'Hyperopting with data from '
f'{self.min_date.strftime(DATETIME_PRINT_FORMAT)} '
f'up to {self.max_date.strftime(DATETIME_PRINT_FORMAT)} '
f'({(self.max_date - self.min_date).days} days)..')
# Store non-trimmed data - will be trimmed after signal generation.
dump(preprocessed, self.data_pickle_file)
else:
dump(data, self.data_pickle_file)
def get_asked_points(self, n_points: int) -> Tuple[List[List[Any]], List[bool]]:
"""

View File

@@ -13,6 +13,7 @@ from colorama import Fore, Style
from pandas import isna, json_normalize
from freqtrade.constants import FTHYPT_FILEVERSION, USERPATH_STRATEGIES
from freqtrade.enums import HyperoptState
from freqtrade.exceptions import OperationalException
from freqtrade.misc import deep_merge_dicts, round_coin_value, round_dict, safe_value_fallback2
from freqtrade.optimize.hyperopt_epoch_filters import hyperopt_filter_epochs
@@ -32,6 +33,15 @@ def hyperopt_serializer(x):
return str(x)
class HyperoptStateContainer():
""" Singleton class to track state of hyperopt"""
state: HyperoptState = HyperoptState.OPTIMIZE
@classmethod
def set_state(cls, value: HyperoptState):
cls.state = value
class HyperoptTools():
@staticmethod

View File

@@ -133,6 +133,7 @@ def migrate_trades_and_orders_table(
amount_precision = get_column_def(cols, 'amount_precision', 'null')
price_precision = get_column_def(cols, 'price_precision', 'null')
precision_mode = get_column_def(cols, 'precision_mode', 'null')
contract_size = get_column_def(cols, 'contract_size', 'null')
# Schema migration necessary
with engine.begin() as connection:
@@ -161,7 +162,7 @@ def migrate_trades_and_orders_table(
timeframe, open_trade_value, close_profit_abs,
trading_mode, leverage, liquidation_price, is_short,
interest_rate, funding_fees, realized_profit,
amount_precision, price_precision, precision_mode
amount_precision, price_precision, precision_mode, contract_size
)
select id, lower(exchange), pair, {base_currency} base_currency,
{stake_currency} stake_currency,
@@ -189,7 +190,7 @@ def migrate_trades_and_orders_table(
{is_short} is_short, {interest_rate} interest_rate,
{funding_fees} funding_fees, {realized_profit} realized_profit,
{amount_precision} amount_precision, {price_precision} price_precision,
{precision_mode} precision_mode
{precision_mode} precision_mode, {contract_size} contract_size
from {trade_back_name}
"""))
@@ -308,7 +309,7 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
# if ('orders' not in previous_tables
# or not has_column(cols_orders, 'stop_price')):
migrating = False
if not has_column(cols_trades, 'precision_mode'):
if not has_column(cols_trades, 'contract_size'):
migrating = True
logger.info(f"Running database migration for trades - "
f"backup: {table_back_name}, {order_table_bak_name}")

View File

@@ -14,7 +14,7 @@ from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPE
BuySell, LongShort)
from freqtrade.enums import ExitType, TradingMode
from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import amount_to_precision, price_to_precision
from freqtrade.exchange import amount_to_contract_precision, price_to_precision
from freqtrade.leverage import interest
from freqtrade.persistence.base import _DECL_BASE
from freqtrade.util import FtPrecise
@@ -296,6 +296,7 @@ class LocalTrade():
amount_precision: Optional[float] = None
price_precision: Optional[float] = None
precision_mode: Optional[int] = None
contract_size: Optional[float] = None
# Leverage trading properties
liquidation_price: Optional[float] = None
@@ -623,7 +624,8 @@ class LocalTrade():
else:
logger.warning(
f'Got different open_order_id {self.open_order_id} != {order.order_id}')
amount_tr = amount_to_precision(self.amount, self.amount_precision, self.precision_mode)
amount_tr = amount_to_contract_precision(self.amount, self.amount_precision,
self.precision_mode, self.contract_size)
if isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC):
self.close(order.safe_price)
else:
@@ -841,7 +843,7 @@ class LocalTrade():
avg_price = FtPrecise(0.0)
close_profit = 0.0
close_profit_abs = 0.0
profit = None
for o in self.orders:
if o.ft_is_open or not o.filled:
continue
@@ -868,8 +870,6 @@ class LocalTrade():
close_profit_abs += profit
close_profit = self.calc_profit_ratio(
exit_rate, amount=exit_amount, open_rate=avg_price)
if current_amount <= ZERO:
profit = close_profit_abs
else:
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
@@ -878,8 +878,8 @@ class LocalTrade():
self.realized_profit = close_profit_abs
self.close_profit_abs = profit
current_amount_tr = amount_to_precision(float(current_amount),
self.amount_precision, self.precision_mode)
current_amount_tr = amount_to_contract_precision(
float(current_amount), self.amount_precision, self.precision_mode, self.contract_size)
if current_amount_tr > 0.0:
# Trade is still open
# Leverage not updated, as we don't allow changing leverage through DCA at the moment.
@@ -894,6 +894,7 @@ class LocalTrade():
# Close profit abs / maximum owned
# Fees are considered as they are part of close_profit_abs
self.close_profit = (close_profit_abs / total_stake) * self.leverage
self.close_profit_abs = close_profit_abs
def select_order_by_order_id(self, order_id: str) -> Optional[Order]:
"""
@@ -1044,6 +1045,16 @@ class LocalTrade():
"""
return Trade.get_trades_proxy(is_open=True)
@staticmethod
def get_open_trade_count() -> int:
"""
get open trade count
"""
if Trade.use_db:
return Trade.query.filter(Trade.is_open.is_(True)).count()
else:
return len(LocalTrade.trades_open)
@staticmethod
def stoploss_reinitialization(desired_stoploss):
"""
@@ -1132,6 +1143,7 @@ class Trade(_DECL_BASE, LocalTrade):
amount_precision = Column(Float, nullable=True)
price_precision = Column(Float, nullable=True)
precision_mode = Column(Integer, nullable=True)
contract_size = Column(Float, nullable=True)
# Leverage trading properties
leverage = Column(Float, nullable=True, default=1.0)

View File

@@ -73,7 +73,7 @@ class VolumePairList(IPairList):
if (not self._use_range and not (
self._exchange.exchange_has('fetchTickers')
and self._exchange._ft_has["tickers_have_quoteVolume"])):
and self._exchange.get_option("tickers_have_quoteVolume"))):
raise OperationalException(
"Exchange does not support dynamic whitelist in this configuration. "
"Please edit your config and either remove Volumepairlist, "
@@ -193,7 +193,7 @@ class VolumePairList(IPairList):
) in candles else None
# in case of candle data calculate typical price and quoteVolume for candle
if pair_candles is not None and not pair_candles.empty:
if self._exchange._ft_has["ohlcv_volume_currency"] == "base":
if self._exchange.get_option("ohlcv_volume_currency") == "base":
pair_candles['typical_price'] = (pair_candles['high'] + pair_candles['low']
+ pair_candles['close']) / 3

View File

@@ -193,7 +193,10 @@ class IResolver:
:return: List of dicts containing 'name', 'class' and 'location' entries
"""
logger.debug(f"Searching for {cls.object_type.__name__} '{directory}'")
objects = []
objects: List[Dict[str, Any]] = []
if not directory.is_dir():
logger.info(f"'{directory}' is not a directory, skipping.")
return objects
for entry in directory.iterdir():
if (
recursive and entry.is_dir()

View File

@@ -216,9 +216,10 @@ def stop(rpc: RPC = Depends(get_rpc)):
return rpc._rpc_stop()
@router.post('/stopentry', response_model=StatusMsg, tags=['botcontrol'])
@router.post('/stopbuy', response_model=StatusMsg, tags=['botcontrol'])
def stop_buy(rpc: RPC = Depends(get_rpc)):
return rpc._rpc_stopbuy()
return rpc._rpc_stopentry()
@router.post('/reload_config', response_model=StatusMsg, tags=['botcontrol'])

View File

@@ -657,7 +657,7 @@ class RPC:
self._freqtrade.state = State.RELOAD_CONFIG
return {'status': 'Reloading config ...'}
def _rpc_stopbuy(self) -> Dict[str, str]:
def _rpc_stopentry(self) -> Dict[str, str]:
"""
Handler to stop buying, but handle open trades gracefully.
"""
@@ -665,7 +665,7 @@ class RPC:
# Set 'max_open_trades' to 0
self._freqtrade.config['max_open_trades'] = 0
return {'status': 'No more buy will occur from now. Run /reload_config to reset.'}
return {'status': 'No more entries will occur from now. Run /reload_config to reset.'}
def __exec_force_exit(self, trade: Trade, ordertype: Optional[str],
amount: Optional[float] = None) -> None:

View File

@@ -114,18 +114,20 @@ class Telegram(RPCHandler):
# TODO: DRY! - its not good to list all valid cmds here. But otherwise
# this needs refactoring of the whole telegram module (same
# problem in _help()).
valid_keys: List[str] = [r'/start$', r'/stop$', r'/status$', r'/status table$',
r'/trades$', r'/performance$', r'/buys', r'/entries',
r'/sells', r'/exits', r'/mix_tags',
r'/daily$', r'/daily \d+$', r'/profit$', r'/profit \d+',
r'/stats$', r'/count$', r'/locks$', r'/balance$',
r'/stopbuy$', r'/reload_config$', r'/show_config$',
r'/logs$', r'/whitelist$', r'/whitelist(\ssorted|\sbaseonly)+$',
r'/blacklist$', r'/bl_delete$',
r'/weekly$', r'/weekly \d+$', r'/monthly$', r'/monthly \d+$',
r'/forcebuy$', r'/forcelong$', r'/forceshort$',
r'/forcesell$', r'/forceexit$',
r'/edge$', r'/health$', r'/help$', r'/version$']
valid_keys: List[str] = [
r'/start$', r'/stop$', r'/status$', r'/status table$',
r'/trades$', r'/performance$', r'/buys', r'/entries',
r'/sells', r'/exits', r'/mix_tags',
r'/daily$', r'/daily \d+$', r'/profit$', r'/profit \d+',
r'/stats$', r'/count$', r'/locks$', r'/balance$',
r'/stopbuy$', r'/stopentry$', r'/reload_config$', r'/show_config$',
r'/logs$', r'/whitelist$', r'/whitelist(\ssorted|\sbaseonly)+$',
r'/blacklist$', r'/bl_delete$',
r'/weekly$', r'/weekly \d+$', r'/monthly$', r'/monthly \d+$',
r'/forcebuy$', r'/forcelong$', r'/forceshort$',
r'/forcesell$', r'/forceexit$',
r'/edge$', r'/health$', r'/help$', r'/version$'
]
# Create keys for generation
valid_keys_print = [k.replace('$', '') for k in valid_keys]
@@ -182,7 +184,7 @@ class Telegram(RPCHandler):
CommandHandler(['unlock', 'delete_locks'], self._delete_locks),
CommandHandler(['reload_config', 'reload_conf'], self._reload_config),
CommandHandler(['show_config', 'show_conf'], self._show_config),
CommandHandler('stopbuy', self._stopbuy),
CommandHandler(['stopbuy', 'stopentry'], self._stopentry),
CommandHandler('whitelist', self._whitelist),
CommandHandler('blacklist', self._blacklist),
CommandHandler(['blacklist_delete', 'bl_delete'], self._blacklist_delete),
@@ -984,7 +986,7 @@ class Telegram(RPCHandler):
self._send_msg(f"Status: `{msg['status']}`")
@authorized_only
def _stopbuy(self, update: Update, context: CallbackContext) -> None:
def _stopentry(self, update: Update, context: CallbackContext) -> None:
"""
Handler for /stop_buy.
Sets max_open_trades to 0 and gracefully sells all open trades
@@ -992,7 +994,7 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
msg = self._rpc._rpc_stopbuy()
msg = self._rpc._rpc_stopentry()
self._send_msg(f"Status: `{msg['status']}`")
@authorized_only
@@ -1488,7 +1490,7 @@ class Telegram(RPCHandler):
"------------\n"
"*/start:* `Starts the trader`\n"
"*/stop:* Stops the trader\n"
"*/stopbuy:* `Stops buying, but handles open trades gracefully` \n"
"*/stopentry:* `Stops entering, but handles open trades gracefully` \n"
"*/forceexit <trade_id>|all:* `Instantly exits the given trade or all trades, "
"regardless of profit`\n"
"*/fx <trade_id>|all:* `Alias to /forceexit`\n"

View File

@@ -7,6 +7,9 @@ from abc import ABC, abstractmethod
from contextlib import suppress
from typing import Any, Optional, Sequence, Union
from freqtrade.enums.hyperoptstate import HyperoptState
from freqtrade.optimize.hyperopt_tools import HyperoptStateContainer
with suppress(ImportError):
from skopt.space import Integer, Real, Categorical
@@ -57,6 +60,13 @@ class BaseParameter(ABC):
Get-space - will be used by Hyperopt to get the hyperopt Space
"""
def can_optimize(self):
return (
self.in_space
and self.optimize
and HyperoptStateContainer.state != HyperoptState.OPTIMIZE
)
class NumericParameter(BaseParameter):
""" Internal parameter used for Numeric purposes """
@@ -133,7 +143,7 @@ class IntParameter(NumericParameter):
Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid
calculating 100ds of indicators.
"""
if self.in_space and self.optimize:
if self.can_optimize():
# Scikit-optimize ranges are "inclusive", while python's "range" is exclusive
return range(self.low, self.high + 1)
else:
@@ -212,7 +222,7 @@ class DecimalParameter(NumericParameter):
Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid
calculating 100ds of indicators.
"""
if self.in_space and self.optimize:
if self.can_optimize():
low = int(self.low * pow(10, self._decimals))
high = int(self.high * pow(10, self._decimals)) + 1
return [round(n * pow(0.1, self._decimals), self._decimals) for n in range(low, high)]
@@ -261,7 +271,7 @@ class CategoricalParameter(BaseParameter):
Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid
calculating 100ds of indicators.
"""
if self.in_space and self.optimize:
if self.can_optimize():
return self.opt_range
else:
return [self.value]

View File

@@ -17,7 +17,7 @@ pytest-mock==3.8.2
pytest-random-order==1.0.4
isort==5.10.1
# For datetime mocking
time-machine==2.7.1
time-machine==2.8.1
# Convert jupyter notebooks to markdown documents
nbconvert==6.5.3
@@ -25,6 +25,6 @@ nbconvert==6.5.3
# mypy types
types-cachetools==5.2.1
types-filelock==3.2.7
types-requests==2.28.8
types-requests==2.28.9
types-tabulate==0.8.11
types-python-dateutil==2.8.19

View File

@@ -2,7 +2,7 @@ numpy==1.23.2
pandas==1.4.3
pandas-ta==0.3.14b
ccxt==1.92.20
ccxt==1.92.52
# Pin cryptography for now due to rust build errors with piwheels
cryptography==37.0.4
aiohttp==3.8.1
@@ -12,7 +12,7 @@ arrow==1.2.2
cachetools==4.2.2
requests==2.28.1
urllib3==1.26.11
jsonschema==4.9.1
jsonschema==4.14.0
TA-Lib==0.4.24
technical==1.3.0
tabulate==0.8.10
@@ -34,7 +34,7 @@ orjson==3.7.12
sdnotify==0.3.2
# API Server
fastapi==0.79.0
fastapi==0.79.1
uvicorn==0.18.2
pyjwt==2.4.0
aiofiles==0.8.0

View File

@@ -361,6 +361,13 @@ class FtRestClient():
"""
return self._get("sysinfo")
def health(self):
"""Provides a quick health check of the running bot.
:return: json object
"""
return self._get("health")
def add_arguments():
parser = argparse.ArgumentParser()

View File

@@ -1430,6 +1430,27 @@ def test_start_list_data(testdatadir, capsys):
assert "\n| XRP/USDT | 1h | futures |\n" in captured.out
assert "\n| XRP/USDT | 1h, 8h | mark |\n" in captured.out
args = [
"list-data",
"--data-format-ohlcv",
"json",
"--pairs", "XRP/ETH",
"--datadir",
str(testdatadir),
"--show-timerange",
]
pargs = get_args(args)
pargs['config'] = None
start_list_data(pargs)
captured = capsys.readouterr()
assert "Found 2 pair / timeframe combinations." in captured.out
assert ("\n| Pair | Timeframe | Type | From | To |\n"
in captured.out)
assert "UNITTEST/BTC" not in captured.out
assert (
"\n| XRP/ETH | 1m | spot | 2019-10-11 00:00:00 | 2019-10-13 11:19:00 |\n"
in captured.out)
@pytest.mark.usefixtures("init_persistence")
def test_show_trades(mocker, fee, capsys, caplog):

View File

@@ -3085,416 +3085,416 @@ def leverage_tiers():
return {
"1000SHIB/USDT": [
{
'min': 0,
'max': 50000,
'mmr': 0.01,
'lev': 50,
'minNotional': 0,
'maxNotional': 50000,
'maintenanceMarginRate': 0.01,
'maxLeverage': 50,
'maintAmt': 0.0
},
{
'min': 50000,
'max': 150000,
'mmr': 0.025,
'lev': 20,
'minNotional': 50000,
'maxNotional': 150000,
'maintenanceMarginRate': 0.025,
'maxLeverage': 20,
'maintAmt': 750.0
},
{
'min': 150000,
'max': 250000,
'mmr': 0.05,
'lev': 10,
'minNotional': 150000,
'maxNotional': 250000,
'maintenanceMarginRate': 0.05,
'maxLeverage': 10,
'maintAmt': 4500.0
},
{
'min': 250000,
'max': 500000,
'mmr': 0.1,
'lev': 5,
'minNotional': 250000,
'maxNotional': 500000,
'maintenanceMarginRate': 0.1,
'maxLeverage': 5,
'maintAmt': 17000.0
},
{
'min': 500000,
'max': 1000000,
'mmr': 0.125,
'lev': 4,
'minNotional': 500000,
'maxNotional': 1000000,
'maintenanceMarginRate': 0.125,
'maxLeverage': 4,
'maintAmt': 29500.0
},
{
'min': 1000000,
'max': 2000000,
'mmr': 0.25,
'lev': 2,
'minNotional': 1000000,
'maxNotional': 2000000,
'maintenanceMarginRate': 0.25,
'maxLeverage': 2,
'maintAmt': 154500.0
},
{
'min': 2000000,
'max': 30000000,
'mmr': 0.5,
'lev': 1,
'minNotional': 2000000,
'maxNotional': 30000000,
'maintenanceMarginRate': 0.5,
'maxLeverage': 1,
'maintAmt': 654500.0
},
],
"1INCH/USDT": [
{
'min': 0,
'max': 5000,
'mmr': 0.012,
'lev': 50,
'minNotional': 0,
'maxNotional': 5000,
'maintenanceMarginRate': 0.012,
'maxLeverage': 50,
'maintAmt': 0.0
},
{
'min': 5000,
'max': 25000,
'mmr': 0.025,
'lev': 20,
'minNotional': 5000,
'maxNotional': 25000,
'maintenanceMarginRate': 0.025,
'maxLeverage': 20,
'maintAmt': 65.0
},
{
'min': 25000,
'max': 100000,
'mmr': 0.05,
'lev': 10,
'minNotional': 25000,
'maxNotional': 100000,
'maintenanceMarginRate': 0.05,
'maxLeverage': 10,
'maintAmt': 690.0
},
{
'min': 100000,
'max': 250000,
'mmr': 0.1,
'lev': 5,
'minNotional': 100000,
'maxNotional': 250000,
'maintenanceMarginRate': 0.1,
'maxLeverage': 5,
'maintAmt': 5690.0
},
{
'min': 250000,
'max': 1000000,
'mmr': 0.125,
'lev': 2,
'minNotional': 250000,
'maxNotional': 1000000,
'maintenanceMarginRate': 0.125,
'maxLeverage': 2,
'maintAmt': 11940.0
},
{
'min': 1000000,
'max': 100000000,
'mmr': 0.5,
'lev': 1,
'minNotional': 1000000,
'maxNotional': 100000000,
'maintenanceMarginRate': 0.5,
'maxLeverage': 1,
'maintAmt': 386940.0
},
],
"AAVE/USDT": [
{
'min': 0,
'max': 5000,
'mmr': 0.01,
'lev': 50,
'minNotional': 0,
'maxNotional': 5000,
'maintenanceMarginRate': 0.01,
'maxLeverage': 50,
'maintAmt': 0.0
},
{
'min': 5000,
'max': 25000,
'mmr': 0.02,
'lev': 25,
'minNotional': 5000,
'maxNotional': 25000,
'maintenanceMarginRate': 0.02,
'maxLeverage': 25,
'maintAmt': 75.0
},
{
'min': 25000,
'max': 100000,
'mmr': 0.05,
'lev': 10,
'minNotional': 25000,
'maxNotional': 100000,
'maintenanceMarginRate': 0.05,
'maxLeverage': 10,
'maintAmt': 700.0
},
{
'min': 100000,
'max': 250000,
'mmr': 0.1,
'lev': 5,
'minNotional': 100000,
'maxNotional': 250000,
'maintenanceMarginRate': 0.1,
'maxLeverage': 5,
'maintAmt': 5700.0
},
{
'min': 250000,
'max': 1000000,
'mmr': 0.125,
'lev': 2,
'minNotional': 250000,
'maxNotional': 1000000,
'maintenanceMarginRate': 0.125,
'maxLeverage': 2,
'maintAmt': 11950.0
},
{
'min': 10000000,
'max': 50000000,
'mmr': 0.5,
'lev': 1,
'minNotional': 10000000,
'maxNotional': 50000000,
'maintenanceMarginRate': 0.5,
'maxLeverage': 1,
'maintAmt': 386950.0
},
],
"ADA/BUSD": [
{
"min": 0,
"max": 100000,
"mmr": 0.025,
"lev": 20,
"minNotional": 0,
"maxNotional": 100000,
"maintenanceMarginRate": 0.025,
"maxLeverage": 20,
"maintAmt": 0.0
},
{
"min": 100000,
"max": 500000,
"mmr": 0.05,
"lev": 10,
"minNotional": 100000,
"maxNotional": 500000,
"maintenanceMarginRate": 0.05,
"maxLeverage": 10,
"maintAmt": 2500.0
},
{
"min": 500000,
"max": 1000000,
"mmr": 0.1,
"lev": 5,
"minNotional": 500000,
"maxNotional": 1000000,
"maintenanceMarginRate": 0.1,
"maxLeverage": 5,
"maintAmt": 27500.0
},
{
"min": 1000000,
"max": 2000000,
"mmr": 0.15,
"lev": 3,
"minNotional": 1000000,
"maxNotional": 2000000,
"maintenanceMarginRate": 0.15,
"maxLeverage": 3,
"maintAmt": 77500.0
},
{
"min": 2000000,
"max": 5000000,
"mmr": 0.25,
"lev": 2,
"minNotional": 2000000,
"maxNotional": 5000000,
"maintenanceMarginRate": 0.25,
"maxLeverage": 2,
"maintAmt": 277500.0
},
{
"min": 5000000,
"max": 30000000,
"mmr": 0.5,
"lev": 1,
"minNotional": 5000000,
"maxNotional": 30000000,
"maintenanceMarginRate": 0.5,
"maxLeverage": 1,
"maintAmt": 1527500.0
},
],
'BNB/BUSD': [
{
"min": 0, # stake(before leverage) = 0
"max": 100000, # max stake(before leverage) = 5000
"mmr": 0.025,
"lev": 20,
"minNotional": 0, # stake(before leverage) = 0
"maxNotional": 100000, # max stake(before leverage) = 5000
"maintenanceMarginRate": 0.025,
"maxLeverage": 20,
"maintAmt": 0.0
},
{
"min": 100000, # stake = 10000.0
"max": 500000, # max_stake = 50000.0
"mmr": 0.05,
"lev": 10,
"minNotional": 100000, # stake = 10000.0
"maxNotional": 500000, # max_stake = 50000.0
"maintenanceMarginRate": 0.05,
"maxLeverage": 10,
"maintAmt": 2500.0
},
{
"min": 500000, # stake = 100000.0
"max": 1000000, # max_stake = 200000.0
"mmr": 0.1,
"lev": 5,
"minNotional": 500000, # stake = 100000.0
"maxNotional": 1000000, # max_stake = 200000.0
"maintenanceMarginRate": 0.1,
"maxLeverage": 5,
"maintAmt": 27500.0
},
{
"min": 1000000, # stake = 333333.3333333333
"max": 2000000, # max_stake = 666666.6666666666
"mmr": 0.15,
"lev": 3,
"minNotional": 1000000, # stake = 333333.3333333333
"maxNotional": 2000000, # max_stake = 666666.6666666666
"maintenanceMarginRate": 0.15,
"maxLeverage": 3,
"maintAmt": 77500.0
},
{
"min": 2000000, # stake = 1000000.0
"max": 5000000, # max_stake = 2500000.0
"mmr": 0.25,
"lev": 2,
"minNotional": 2000000, # stake = 1000000.0
"maxNotional": 5000000, # max_stake = 2500000.0
"maintenanceMarginRate": 0.25,
"maxLeverage": 2,
"maintAmt": 277500.0
},
{
"min": 5000000, # stake = 5000000.0
"max": 30000000, # max_stake = 30000000.0
"mmr": 0.5,
"lev": 1,
"minNotional": 5000000, # stake = 5000000.0
"maxNotional": 30000000, # max_stake = 30000000.0
"maintenanceMarginRate": 0.5,
"maxLeverage": 1,
"maintAmt": 1527500.0
}
],
'BNB/USDT': [
{
"min": 0, # stake = 0.0
"max": 10000, # max_stake = 133.33333333333334
"mmr": 0.0065,
"lev": 75,
"minNotional": 0, # stake = 0.0
"maxNotional": 10000, # max_stake = 133.33333333333334
"maintenanceMarginRate": 0.0065,
"maxLeverage": 75,
"maintAmt": 0.0
},
{
"min": 10000, # stake = 200.0
"max": 50000, # max_stake = 1000.0
"mmr": 0.01,
"lev": 50,
"minNotional": 10000, # stake = 200.0
"maxNotional": 50000, # max_stake = 1000.0
"maintenanceMarginRate": 0.01,
"maxLeverage": 50,
"maintAmt": 35.0
},
{
"min": 50000, # stake = 2000.0
"max": 250000, # max_stake = 10000.0
"mmr": 0.02,
"lev": 25,
"minNotional": 50000, # stake = 2000.0
"maxNotional": 250000, # max_stake = 10000.0
"maintenanceMarginRate": 0.02,
"maxLeverage": 25,
"maintAmt": 535.0
},
{
"min": 250000, # stake = 25000.0
"max": 1000000, # max_stake = 100000.0
"mmr": 0.05,
"lev": 10,
"minNotional": 250000, # stake = 25000.0
"maxNotional": 1000000, # max_stake = 100000.0
"maintenanceMarginRate": 0.05,
"maxLeverage": 10,
"maintAmt": 8035.0
},
{
"min": 1000000, # stake = 200000.0
"max": 2000000, # max_stake = 400000.0
"mmr": 0.1,
"lev": 5,
"minNotional": 1000000, # stake = 200000.0
"maxNotional": 2000000, # max_stake = 400000.0
"maintenanceMarginRate": 0.1,
"maxLeverage": 5,
"maintAmt": 58035.0
},
{
"min": 2000000, # stake = 500000.0
"max": 5000000, # max_stake = 1250000.0
"mmr": 0.125,
"lev": 4,
"minNotional": 2000000, # stake = 500000.0
"maxNotional": 5000000, # max_stake = 1250000.0
"maintenanceMarginRate": 0.125,
"maxLeverage": 4,
"maintAmt": 108035.0
},
{
"min": 5000000, # stake = 1666666.6666666667
"max": 10000000, # max_stake = 3333333.3333333335
"mmr": 0.15,
"lev": 3,
"minNotional": 5000000, # stake = 1666666.6666666667
"maxNotional": 10000000, # max_stake = 3333333.3333333335
"maintenanceMarginRate": 0.15,
"maxLeverage": 3,
"maintAmt": 233035.0
},
{
"min": 10000000, # stake = 5000000.0
"max": 20000000, # max_stake = 10000000.0
"mmr": 0.25,
"lev": 2,
"minNotional": 10000000, # stake = 5000000.0
"maxNotional": 20000000, # max_stake = 10000000.0
"maintenanceMarginRate": 0.25,
"maxLeverage": 2,
"maintAmt": 1233035.0
},
{
"min": 20000000, # stake = 20000000.0
"max": 50000000, # max_stake = 50000000.0
"mmr": 0.5,
"lev": 1,
"minNotional": 20000000, # stake = 20000000.0
"maxNotional": 50000000, # max_stake = 50000000.0
"maintenanceMarginRate": 0.5,
"maxLeverage": 1,
"maintAmt": 6233035.0
},
],
'BTC/USDT': [
{
"min": 0, # stake = 0.0
"max": 50000, # max_stake = 400.0
"mmr": 0.004,
"lev": 125,
"minNotional": 0, # stake = 0.0
"maxNotional": 50000, # max_stake = 400.0
"maintenanceMarginRate": 0.004,
"maxLeverage": 125,
"maintAmt": 0.0
},
{
"min": 50000, # stake = 500.0
"max": 250000, # max_stake = 2500.0
"mmr": 0.005,
"lev": 100,
"minNotional": 50000, # stake = 500.0
"maxNotional": 250000, # max_stake = 2500.0
"maintenanceMarginRate": 0.005,
"maxLeverage": 100,
"maintAmt": 50.0
},
{
"min": 250000, # stake = 5000.0
"max": 1000000, # max_stake = 20000.0
"mmr": 0.01,
"lev": 50,
"minNotional": 250000, # stake = 5000.0
"maxNotional": 1000000, # max_stake = 20000.0
"maintenanceMarginRate": 0.01,
"maxLeverage": 50,
"maintAmt": 1300.0
},
{
"min": 1000000, # stake = 50000.0
"max": 7500000, # max_stake = 375000.0
"mmr": 0.025,
"lev": 20,
"minNotional": 1000000, # stake = 50000.0
"maxNotional": 7500000, # max_stake = 375000.0
"maintenanceMarginRate": 0.025,
"maxLeverage": 20,
"maintAmt": 16300.0
},
{
"min": 7500000, # stake = 750000.0
"max": 40000000, # max_stake = 4000000.0
"mmr": 0.05,
"lev": 10,
"minNotional": 7500000, # stake = 750000.0
"maxNotional": 40000000, # max_stake = 4000000.0
"maintenanceMarginRate": 0.05,
"maxLeverage": 10,
"maintAmt": 203800.0
},
{
"min": 40000000, # stake = 8000000.0
"max": 100000000, # max_stake = 20000000.0
"mmr": 0.1,
"lev": 5,
"minNotional": 40000000, # stake = 8000000.0
"maxNotional": 100000000, # max_stake = 20000000.0
"maintenanceMarginRate": 0.1,
"maxLeverage": 5,
"maintAmt": 2203800.0
},
{
"min": 100000000, # stake = 25000000.0
"max": 200000000, # max_stake = 50000000.0
"mmr": 0.125,
"lev": 4,
"minNotional": 100000000, # stake = 25000000.0
"maxNotional": 200000000, # max_stake = 50000000.0
"maintenanceMarginRate": 0.125,
"maxLeverage": 4,
"maintAmt": 4703800.0
},
{
"min": 200000000, # stake = 66666666.666666664
"max": 400000000, # max_stake = 133333333.33333333
"mmr": 0.15,
"lev": 3,
"minNotional": 200000000, # stake = 66666666.666666664
"maxNotional": 400000000, # max_stake = 133333333.33333333
"maintenanceMarginRate": 0.15,
"maxLeverage": 3,
"maintAmt": 9703800.0
},
{
"min": 400000000, # stake = 200000000.0
"max": 600000000, # max_stake = 300000000.0
"mmr": 0.25,
"lev": 2,
"minNotional": 400000000, # stake = 200000000.0
"maxNotional": 600000000, # max_stake = 300000000.0
"maintenanceMarginRate": 0.25,
"maxLeverage": 2,
"maintAmt": 4.97038E7
},
{
"min": 600000000, # stake = 600000000.0
"max": 1000000000, # max_stake = 1000000000.0
"mmr": 0.5,
"lev": 1,
"minNotional": 600000000, # stake = 600000000.0
"maxNotional": 1000000000, # max_stake = 1000000000.0
"maintenanceMarginRate": 0.5,
"maxLeverage": 1,
"maintAmt": 1.997038E8
},
],
"ZEC/USDT": [
{
'min': 0,
'max': 50000,
'mmr': 0.01,
'lev': 50,
'minNotional': 0,
'maxNotional': 50000,
'maintenanceMarginRate': 0.01,
'maxLeverage': 50,
'maintAmt': 0.0
},
{
'min': 50000,
'max': 150000,
'mmr': 0.025,
'lev': 20,
'minNotional': 50000,
'maxNotional': 150000,
'maintenanceMarginRate': 0.025,
'maxLeverage': 20,
'maintAmt': 750.0
},
{
'min': 150000,
'max': 250000,
'mmr': 0.05,
'lev': 10,
'minNotional': 150000,
'maxNotional': 250000,
'maintenanceMarginRate': 0.05,
'maxLeverage': 10,
'maintAmt': 4500.0
},
{
'min': 250000,
'max': 500000,
'mmr': 0.1,
'lev': 5,
'minNotional': 250000,
'maxNotional': 500000,
'maintenanceMarginRate': 0.1,
'maxLeverage': 5,
'maintAmt': 17000.0
},
{
'min': 500000,
'max': 1000000,
'mmr': 0.125,
'lev': 4,
'minNotional': 500000,
'maxNotional': 1000000,
'maintenanceMarginRate': 0.125,
'maxLeverage': 4,
'maintAmt': 29500.0
},
{
'min': 1000000,
'max': 2000000,
'mmr': 0.25,
'lev': 2,
'minNotional': 1000000,
'maxNotional': 2000000,
'maintenanceMarginRate': 0.25,
'maxLeverage': 2,
'maintAmt': 154500.0
},
{
'min': 2000000,
'max': 30000000,
'mmr': 0.5,
'lev': 1,
'minNotional': 2000000,
'maxNotional': 30000000,
'maintenanceMarginRate': 0.5,
'maxLeverage': 1,
'maintAmt': 654500.0
},
]

View File

@@ -376,96 +376,96 @@ def test_fill_leverage_tiers_binance(default_conf, mocker):
assert exchange._leverage_tiers == {
'ADA/BUSD': [
{
"min": 0,
"max": 100000,
"mmr": 0.025,
"lev": 20,
"minNotional": 0,
"maxNotional": 100000,
"maintenanceMarginRate": 0.025,
"maxLeverage": 20,
"maintAmt": 0.0
},
{
"min": 100000,
"max": 500000,
"mmr": 0.05,
"lev": 10,
"minNotional": 100000,
"maxNotional": 500000,
"maintenanceMarginRate": 0.05,
"maxLeverage": 10,
"maintAmt": 2500.0
},
{
"min": 500000,
"max": 1000000,
"mmr": 0.1,
"lev": 5,
"minNotional": 500000,
"maxNotional": 1000000,
"maintenanceMarginRate": 0.1,
"maxLeverage": 5,
"maintAmt": 27500.0
},
{
"min": 1000000,
"max": 2000000,
"mmr": 0.15,
"lev": 3,
"minNotional": 1000000,
"maxNotional": 2000000,
"maintenanceMarginRate": 0.15,
"maxLeverage": 3,
"maintAmt": 77500.0
},
{
"min": 2000000,
"max": 5000000,
"mmr": 0.25,
"lev": 2,
"minNotional": 2000000,
"maxNotional": 5000000,
"maintenanceMarginRate": 0.25,
"maxLeverage": 2,
"maintAmt": 277500.0
},
{
"min": 5000000,
"max": 30000000,
"mmr": 0.5,
"lev": 1,
"minNotional": 5000000,
"maxNotional": 30000000,
"maintenanceMarginRate": 0.5,
"maxLeverage": 1,
"maintAmt": 1527500.0
}
],
"ZEC/USDT": [
{
'min': 0,
'max': 50000,
'mmr': 0.01,
'lev': 50,
'minNotional': 0,
'maxNotional': 50000,
'maintenanceMarginRate': 0.01,
'maxLeverage': 50,
'maintAmt': 0.0
},
{
'min': 50000,
'max': 150000,
'mmr': 0.025,
'lev': 20,
'minNotional': 50000,
'maxNotional': 150000,
'maintenanceMarginRate': 0.025,
'maxLeverage': 20,
'maintAmt': 750.0
},
{
'min': 150000,
'max': 250000,
'mmr': 0.05,
'lev': 10,
'minNotional': 150000,
'maxNotional': 250000,
'maintenanceMarginRate': 0.05,
'maxLeverage': 10,
'maintAmt': 4500.0
},
{
'min': 250000,
'max': 500000,
'mmr': 0.1,
'lev': 5,
'minNotional': 250000,
'maxNotional': 500000,
'maintenanceMarginRate': 0.1,
'maxLeverage': 5,
'maintAmt': 17000.0
},
{
'min': 500000,
'max': 1000000,
'mmr': 0.125,
'lev': 4,
'minNotional': 500000,
'maxNotional': 1000000,
'maintenanceMarginRate': 0.125,
'maxLeverage': 4,
'maintAmt': 29500.0
},
{
'min': 1000000,
'max': 2000000,
'mmr': 0.25,
'lev': 2,
'minNotional': 1000000,
'maxNotional': 2000000,
'maintenanceMarginRate': 0.25,
'maxLeverage': 2,
'maintAmt': 154500.0
},
{
'min': 2000000,
'max': 30000000,
'mmr': 0.5,
'lev': 1,
'minNotional': 2000000,
'maxNotional': 30000000,
'maintenanceMarginRate': 0.5,
'maxLeverage': 1,
'maintAmt': 654500.0
},
]

View File

@@ -137,6 +137,10 @@ def exchange_futures(request, exchange_conf, class_mocker):
'freqtrade.exchange.binance.Binance.fill_leverage_tiers')
class_mocker.patch('freqtrade.exchange.exchange.Exchange.fetch_trading_fees')
class_mocker.patch('freqtrade.exchange.okx.Okx.additional_exchange_init')
class_mocker.patch('freqtrade.exchange.exchange.Exchange.load_cached_leverage_tiers',
return_value=None)
class_mocker.patch('freqtrade.exchange.exchange.Exchange.cache_leverage_tiers')
exchange = ExchangeResolver.load_exchange(
request.param, exchange_conf, validate=True, load_leverage_tiers=True)
@@ -405,14 +409,14 @@ class TestCCXTExchange():
assert (isinstance(futures_leverage, float) or isinstance(futures_leverage, int))
assert futures_leverage >= 1.0
def test_ccxt__get_contract_size(self, exchange_futures):
def test_ccxt_get_contract_size(self, exchange_futures):
futures, futures_name = exchange_futures
if futures:
futures_pair = EXCHANGES[futures_name].get(
'futures_pair',
EXCHANGES[futures_name]['pair']
)
contract_size = futures._get_contract_size(futures_pair)
contract_size = futures.get_contract_size(futures_pair)
assert (isinstance(contract_size, float) or isinstance(contract_size, int))
assert contract_size >= 0.0
@@ -464,6 +468,7 @@ class TestCCXTExchange():
False,
100,
100,
100,
)
assert (isinstance(liquidation_price, float))
assert liquidation_price >= 0.0
@@ -474,6 +479,7 @@ class TestCCXTExchange():
False,
100,
100,
100,
)
assert (isinstance(liquidation_price, float))
assert liquidation_price >= 0.0

View File

@@ -181,11 +181,11 @@ def test_init_ccxt_kwargs(default_conf, mocker, caplog):
assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog)
assert log_has(asynclogmsg, caplog)
# Test additional headers case
Exchange._headers = {'hello': 'world'}
Exchange._ccxt_params = {'hello': 'world'}
ex = Exchange(conf)
assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog)
assert ex._api.headers == {'hello': 'world'}
assert ex._api.hello == 'world'
assert ex._ccxt_config == {}
Exchange._headers = {}
@@ -2352,10 +2352,11 @@ def test_fetch_l2_order_book(default_conf, mocker, order_book_l2, exchange_name)
order_book = exchange.fetch_l2_order_book(pair='ETH/BTC', limit=val)
assert api_mock.fetch_l2_order_book.call_args_list[0][0][0] == 'ETH/BTC'
# Not all exchanges support all limits for orderbook
if not exchange._ft_has['l2_limit_range'] or val in exchange._ft_has['l2_limit_range']:
if (not exchange.get_option('l2_limit_range')
or val in exchange.get_option('l2_limit_range')):
assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == val
else:
next_limit = exchange.get_next_limit_in_list(val, exchange._ft_has['l2_limit_range'])
next_limit = exchange.get_next_limit_in_list(val, exchange.get_option('l2_limit_range'))
assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == next_limit
@@ -3311,16 +3312,16 @@ def test_merge_ft_has_dict(default_conf, mocker):
ex = Kraken(default_conf)
assert ex._ft_has != Exchange._ft_has_default
assert ex._ft_has['trades_pagination'] == 'id'
assert ex._ft_has['trades_pagination_arg'] == 'since'
assert ex.get_option('trades_pagination') == 'id'
assert ex.get_option('trades_pagination_arg') == 'since'
# Binance defines different values
ex = Binance(default_conf)
assert ex._ft_has != Exchange._ft_has_default
assert ex._ft_has['stoploss_on_exchange']
assert ex._ft_has['order_time_in_force'] == ['gtc', 'fok', 'ioc']
assert ex._ft_has['trades_pagination'] == 'id'
assert ex._ft_has['trades_pagination_arg'] == 'fromId'
assert ex.get_option('stoploss_on_exchange')
assert ex.get_option('order_time_in_force') == ['gtc', 'fok', 'ioc']
assert ex.get_option('trades_pagination') == 'id'
assert ex.get_option('trades_pagination_arg') == 'fromId'
conf = copy.deepcopy(default_conf)
conf['exchange']['_ft_has_params'] = {"DeadBeef": 20,
@@ -4131,7 +4132,8 @@ def test_get_or_calculate_liquidation_price(mocker, default_conf):
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
position=0.8,
amount=0.8,
stake_amount=18.884 * 0.8,
wallet_balance=0.8,
)
assert liq_price == 17.47
@@ -4142,7 +4144,8 @@ def test_get_or_calculate_liquidation_price(mocker, default_conf):
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
position=0.8,
amount=0.8,
stake_amount=18.884 * 0.8,
wallet_balance=0.8,
)
assert liq_price == 17.540699999999998
@@ -4287,7 +4290,7 @@ def test__fetch_and_calculate_funding_fees_datetime_called(
('XLTCUSDT', 0.01, 'futures'),
('ETH/USDT:USDT', 10, 'futures')
])
def test__get_contract_size(mocker, default_conf, pair, expected_size, trading_mode):
def est__get_contract_size(mocker, default_conf, pair, expected_size, trading_mode):
api_mock = MagicMock()
default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = 'isolated'
@@ -4306,7 +4309,7 @@ def test__get_contract_size(mocker, default_conf, pair, expected_size, trading_m
'contractSize': '10',
}
})
size = exchange._get_contract_size(pair)
size = exchange.get_contract_size(pair)
assert expected_size == size
@@ -4542,7 +4545,8 @@ def test_liquidation_price_is_none(
pair='DOGE/USDT',
open_rate=open_rate,
is_short=is_short,
position=71200.81144,
amount=71200.81144,
stake_amount=open_rate * 71200.81144,
wallet_balance=-56354.57,
mm_ex_1=0.10,
upnl_ex_1=0.0
@@ -4551,7 +4555,7 @@ def test_liquidation_price_is_none(
@pytest.mark.parametrize(
'exchange_name, is_short, trading_mode, margin_mode, wallet_balance, '
'mm_ex_1, upnl_ex_1, maintenance_amt, position, open_rate, '
'mm_ex_1, upnl_ex_1, maintenance_amt, amount, open_rate, '
'mm_ratio, expected',
[
("binance", False, 'futures', 'isolated', 1535443.01, 0.0,
@@ -4565,7 +4569,7 @@ def test_liquidation_price_is_none(
])
def test_liquidation_price(
mocker, default_conf, exchange_name, open_rate, is_short, trading_mode,
margin_mode, wallet_balance, mm_ex_1, upnl_ex_1, maintenance_amt, position, mm_ratio, expected
margin_mode, wallet_balance, mm_ex_1, upnl_ex_1, maintenance_amt, amount, mm_ratio, expected
):
default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = margin_mode
@@ -4579,7 +4583,8 @@ def test_liquidation_price(
wallet_balance=wallet_balance,
mm_ex_1=mm_ex_1,
upnl_ex_1=upnl_ex_1,
position=position,
amount=amount,
stake_amount=open_rate * amount,
), 2), expected)
@@ -4791,6 +4796,20 @@ def test_load_leverage_tiers(mocker, default_conf, leverage_tiers, exchange_name
)
@pytest.mark.asyncio
@pytest.mark.parametrize('exchange_name', EXCHANGES)
async def test_get_market_leverage_tiers(mocker, default_conf, exchange_name):
default_conf['exchange']['name'] = exchange_name
await async_ccxt_exception(
mocker,
default_conf,
MagicMock(),
"get_market_leverage_tiers",
"fetch_market_leverage_tiers",
symbol='BTC/USDT:USDT'
)
def test_parse_leverage_tier(mocker, default_conf):
exchange = get_patched_exchange(mocker, default_conf)
@@ -4811,10 +4830,10 @@ def test_parse_leverage_tier(mocker, default_conf):
}
assert exchange.parse_leverage_tier(tier) == {
"min": 0,
"max": 100000,
"mmr": 0.025,
"lev": 20,
"minNotional": 0,
"maxNotional": 100000,
"maintenanceMarginRate": 0.025,
"maxLeverage": 20,
"maintAmt": 0.0,
}
@@ -4840,10 +4859,10 @@ def test_parse_leverage_tier(mocker, default_conf):
}
assert exchange.parse_leverage_tier(tier2) == {
'min': 0,
'max': 2000,
'mmr': 0.01,
'lev': 75,
'minNotional': 0,
'maxNotional': 2000,
'maintenanceMarginRate': 0.01,
'maxLeverage': 75,
"maintAmt": None,
}
@@ -5096,6 +5115,7 @@ def test_get_liquidation_price(
pair='ETH/USDT:USDT',
open_rate=open_rate,
amount=amount,
stake_amount=amount * open_rate / leverage,
leverage=leverage,
is_short=is_short,
)
@@ -5131,7 +5151,7 @@ def test_stoploss_contract_size(mocker, default_conf, contract_size, order_amoun
mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y)
exchange = get_patched_exchange(mocker, default_conf, api_mock)
exchange._get_contract_size = MagicMock(return_value=contract_size)
exchange.get_contract_size = MagicMock(return_value=contract_size)
api_mock.create_order.reset_mock()
order = exchange.stoploss(

View File

@@ -1,4 +1,5 @@
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import MagicMock, PropertyMock
import pytest
@@ -6,7 +7,7 @@ import pytest
from freqtrade.enums import MarginMode, TradingMode
from freqtrade.enums.candletype import CandleType
from freqtrade.exchange.exchange import timeframe_to_minutes
from tests.conftest import get_mock_coro, get_patched_exchange
from tests.conftest import get_mock_coro, get_patched_exchange, log_has
from tests.exchange.test_exchange import ccxt_exceptionhandlers
@@ -267,7 +268,10 @@ def test_additional_exchange_init_okx(default_conf, mocker):
"additional_exchange_init", "fetch_accounts")
def test_load_leverage_tiers_okx(default_conf, mocker, markets):
def test_load_leverage_tiers_okx(default_conf, mocker, markets, tmpdir, caplog, time_machine):
default_conf['datadir'] = Path(tmpdir)
# fd_mock = mocker.patch('freqtrade.exchange.exchange.file_dump_json')
api_mock = MagicMock()
type(api_mock).has = PropertyMock(return_value={
'fetchLeverageTiers': False,
@@ -410,48 +414,66 @@ def test_load_leverage_tiers_okx(default_conf, mocker, markets):
assert exchange._leverage_tiers == {
'ADA/USDT:USDT': [
{
'min': 0,
'max': 500,
'mmr': 0.02,
'lev': 75,
'minNotional': 0,
'maxNotional': 500,
'maintenanceMarginRate': 0.02,
'maxLeverage': 75,
'maintAmt': None
},
{
'min': 501,
'max': 1000,
'mmr': 0.025,
'lev': 50,
'minNotional': 501,
'maxNotional': 1000,
'maintenanceMarginRate': 0.025,
'maxLeverage': 50,
'maintAmt': None
},
{
'min': 1001,
'max': 2000,
'mmr': 0.03,
'lev': 20,
'minNotional': 1001,
'maxNotional': 2000,
'maintenanceMarginRate': 0.03,
'maxLeverage': 20,
'maintAmt': None
},
],
'ETH/USDT:USDT': [
{
'min': 0,
'max': 2000,
'mmr': 0.01,
'lev': 75,
'minNotional': 0,
'maxNotional': 2000,
'maintenanceMarginRate': 0.01,
'maxLeverage': 75,
'maintAmt': None
},
{
'min': 2001,
'max': 4000,
'mmr': 0.015,
'lev': 50,
'minNotional': 2001,
'maxNotional': 4000,
'maintenanceMarginRate': 0.015,
'maxLeverage': 50,
'maintAmt': None
},
{
'min': 4001,
'max': 8000,
'mmr': 0.02,
'lev': 20,
'minNotional': 4001,
'maxNotional': 8000,
'maintenanceMarginRate': 0.02,
'maxLeverage': 20,
'maintAmt': None
},
],
}
filename = (default_conf['datadir'] /
f"futures/leverage_tiers_{default_conf['stake_currency']}.json")
assert filename.is_file()
logmsg = 'Cached leverage tiers are outdated. Will update.'
assert not log_has(logmsg, caplog)
api_mock.fetch_market_leverage_tiers.reset_mock()
exchange.load_leverage_tiers()
assert not log_has(logmsg, caplog)
api_mock.fetch_market_leverage_tiers.call_count == 0
# 2 day passes ...
time_machine.move_to(datetime.now() + timedelta(days=2))
exchange.load_leverage_tiers()
assert log_has(logmsg, caplog)

View File

@@ -1,5 +1,6 @@
from copy import deepcopy
from pathlib import Path
from unittest.mock import MagicMock
import pytest
@@ -81,6 +82,51 @@ def get_patched_freqaimodel(mocker, freqaiconf):
return freqaimodel
def make_data_dictionary(mocker, freqai_conf):
freqai_conf.update({"timerange": "20180110-20180130"})
strategy = get_patched_freqai_strategy(mocker, freqai_conf)
exchange = get_patched_exchange(mocker, freqai_conf)
strategy.dp = DataProvider(freqai_conf, exchange)
strategy.freqai_info = freqai_conf.get("freqai", {})
freqai = strategy.freqai
freqai.live = True
freqai.dk = FreqaiDataKitchen(freqai_conf)
freqai.dk.pair = "ADA/BTC"
timerange = TimeRange.parse_timerange("20180110-20180130")
freqai.dd.load_all_pair_histories(timerange, freqai.dk)
freqai.dd.pair_dict = MagicMock()
data_load_timerange = TimeRange.parse_timerange("20180110-20180130")
new_timerange = TimeRange.parse_timerange("20180120-20180130")
corr_dataframes, base_dataframes = freqai.dd.get_base_and_corr_dataframes(
data_load_timerange, freqai.dk.pair, freqai.dk
)
unfiltered_dataframe = freqai.dk.use_strategy_to_populate_indicators(
strategy, corr_dataframes, base_dataframes, freqai.dk.pair
)
unfiltered_dataframe = freqai.dk.slice_dataframe(new_timerange, unfiltered_dataframe)
freqai.dk.find_features(unfiltered_dataframe)
features_filtered, labels_filtered = freqai.dk.filter_features(
unfiltered_dataframe,
freqai.dk.training_features_list,
freqai.dk.label_list,
training_filter=True,
)
data_dictionary = freqai.dk.make_train_test_datasets(features_filtered, labels_filtered)
data_dictionary = freqai.dk.normalize_data(data_dictionary)
return freqai
def get_freqai_live_analyzed_dataframe(mocker, freqaiconf):
strategy = get_patched_freqai_strategy(mocker, freqaiconf)
exchange = get_patched_exchange(mocker, freqaiconf)

View File

@@ -5,7 +5,8 @@ from pathlib import Path
import pytest
from freqtrade.exceptions import OperationalException
from tests.freqai.conftest import get_patched_data_kitchen
from tests.conftest import log_has_re
from tests.freqai.conftest import get_patched_data_kitchen, make_data_dictionary
@pytest.mark.parametrize(
@@ -66,3 +67,30 @@ def test_check_if_model_expired(mocker, freqai_conf, timestamp, expected):
dk = get_patched_data_kitchen(mocker, freqai_conf)
assert dk.check_if_model_expired(timestamp) == expected
shutil.rmtree(Path(dk.full_path))
def test_use_DBSCAN_to_remove_outliers(mocker, freqai_conf, caplog):
freqai = make_data_dictionary(mocker, freqai_conf)
# freqai_conf['freqai']['feature_parameters'].update({"outlier_protection_percentage": 1})
freqai.dk.use_DBSCAN_to_remove_outliers(predict=False)
assert log_has_re(
"DBSCAN found eps of 2.42.",
caplog,
)
def test_compute_distances(mocker, freqai_conf):
freqai = make_data_dictionary(mocker, freqai_conf)
freqai_conf['freqai']['feature_parameters'].update({"DI_threshold": 1})
avg_mean_dist = freqai.dk.compute_distances()
assert round(avg_mean_dist, 2) == 2.56
def test_use_SVM_to_remove_outliers_and_outlier_protection(mocker, freqai_conf, caplog):
freqai = make_data_dictionary(mocker, freqai_conf)
freqai_conf['freqai']['feature_parameters'].update({"outlier_protection_percentage": 0.1})
freqai.dk.use_SVM_to_remove_outliers(predict=False)
assert log_has_re(
"SVM detected 8.46%",
caplog,
)

View File

@@ -550,6 +550,7 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001)
mocker.patch("freqtrade.exchange.Exchange.get_max_pair_stake_amount", return_value=float('inf'))
mocker.patch("freqtrade.exchange.Exchange.get_max_leverage", return_value=100)
mocker.patch("freqtrade.optimize.backtesting.price_to_precision", lambda p, *args: p)
patch_exchange(mocker)
default_conf_usdt['stake_amount'] = 300
default_conf_usdt['max_open_trades'] = 2
@@ -559,13 +560,13 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
default_conf_usdt['exchange']['pair_whitelist'] = ['.*']
backtesting = Backtesting(default_conf_usdt)
backtesting._set_strategy(backtesting.strategylist[0])
pair = 'UNITTEST/USDT:USDT'
pair = 'ETH/USDT:USDT'
row = [
pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0),
0.001, # Open
0.0012, # High
0.00099, # Low
0.0011, # Close
0.1, # Open
0.12, # High
0.099, # Low
0.11, # Close
1, # enter_long
0, # exit_long
1, # enter_short
@@ -580,8 +581,8 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
return_value=(0.01, 0.01))
# leverage = 5
# ep1(trade.open_rate) = 0.001
# position(trade.amount) = 1500000
# ep1(trade.open_rate) = 0.1
# position(trade.amount) = 15000
# stake_amount = 300 -> wb = 300 / 5 = 60
# mmr = 0.01
# cum_b = 0.01
@@ -591,26 +592,26 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
# Binance, Long
# liquidation_price
# = ((wb + cum_b) - (side_1 * position * ep1)) / ((position * mmr_b) - (side_1 * position))
# = ((300 + 0.01) - (1 * 1500000 * 0.001)) / ((1500000 * 0.01) - (1 * 1500000))
# = ((300 + 0.01) - (1 * 15000 * 0.1)) / ((15000 * 0.01) - (1 * 15000))
# = 0.0008080740740740741
# freqtrade_liquidation_price = liq + (abs(open_rate - liq) * liq_buffer * side_1)
# = 0.0008080740740740741 + ((0.001 - 0.0008080740740740741) * 0.05 * 1)
# = 0.0008176703703703704
# = 0.08080740740740741 + ((0.1 - 0.08080740740740741) * 0.05 * 1)
# = 0.08176703703703704
trade = backtesting._enter_trade(pair, row=row, direction='long')
assert pytest.approx(trade.liquidation_price) == 0.00081767037
assert pytest.approx(trade.liquidation_price) == 0.081767037
# Binance, Short
# liquidation_price
# = ((wb + cum_b) - (side_1 * position * ep1)) / ((position * mmr_b) - (side_1 * position))
# = ((300 + 0.01) - ((-1) * 1500000 * 0.001)) / ((1500000 * 0.01) - ((-1) * 1500000))
# = ((300 + 0.01) - ((-1) * 15000 * 0.1)) / ((15000 * 0.01) - ((-1) * 15000))
# = 0.0011881254125412541
# freqtrade_liquidation_price = liq + (abs(open_rate - liq) * liq_buffer * side_1)
# = 0.0011881254125412541 + (abs(0.001 - 0.0011881254125412541) * 0.05 * -1)
# = 0.0011787191419141915
# = 0.11881254125412541 + (abs(0.1 - 0.11881254125412541) * 0.05 * -1)
# = 0.11787191419141915
trade = backtesting._enter_trade(pair, row=row, direction='short')
assert pytest.approx(trade.liquidation_price) == 0.0011787191
assert pytest.approx(trade.liquidation_price) == 0.11787191
# Stake-amount too high!
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=600.0)

View File

@@ -18,6 +18,8 @@ from tests.conftest import patch_exchange
def test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
mocker.patch('freqtrade.optimize.backtesting.amount_to_contract_precision',
lambda x, *args, **kwargs: round(x, 8))
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001)
mocker.patch("freqtrade.exchange.Exchange.get_max_pair_stake_amount", return_value=float('inf'))
patch_exchange(mocker)

View File

@@ -663,7 +663,7 @@ def test_rpc_stop(mocker, default_conf) -> None:
assert freqtradebot.state == State.STOPPED
def test_rpc_stopbuy(mocker, default_conf) -> None:
def test_rpc_stopentry(mocker, default_conf) -> None:
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
@@ -676,8 +676,8 @@ def test_rpc_stopbuy(mocker, default_conf) -> None:
freqtradebot.state = State.RUNNING
assert freqtradebot.config['max_open_trades'] != 0
result = rpc._rpc_stopbuy()
assert {'status': 'No more buy will occur from now. Run /reload_config to reset.'} == result
result = rpc._rpc_stopentry()
assert {'status': 'No more entries will occur from now. Run /reload_config to reset.'} == result
assert freqtradebot.config['max_open_trades'] == 0

View File

@@ -422,13 +422,20 @@ def test_api_reloadconf(botclient):
assert ftbot.state == State.RELOAD_CONFIG
def test_api_stopbuy(botclient):
def test_api_stopentry(botclient):
ftbot, client = botclient
assert ftbot.config['max_open_trades'] != 0
rc = client_post(client, f"{BASE_URI}/stopbuy")
assert_response(rc)
assert rc.json() == {'status': 'No more buy will occur from now. Run /reload_config to reset.'}
assert rc.json() == {
'status': 'No more entries will occur from now. Run /reload_config to reset.'}
assert ftbot.config['max_open_trades'] == 0
rc = client_post(client, f"{BASE_URI}/stopentry")
assert_response(rc)
assert rc.json() == {
'status': 'No more entries will occur from now. Run /reload_config to reset.'}
assert ftbot.config['max_open_trades'] == 0

View File

@@ -103,7 +103,8 @@ def test_telegram_init(default_conf, mocker, caplog) -> None:
"['stats'], ['daily'], ['weekly'], ['monthly'], "
"['count'], ['locks'], ['unlock', 'delete_locks'], "
"['reload_config', 'reload_conf'], ['show_config', 'show_conf'], "
"['stopbuy'], ['whitelist'], ['blacklist'], ['blacklist_delete', 'bl_delete'], "
"['stopbuy', 'stopentry'], ['whitelist'], ['blacklist'], "
"['blacklist_delete', 'bl_delete'], "
"['logs'], ['edge'], ['health'], ['help'], ['version']"
"]")
@@ -896,10 +897,10 @@ def test_stopbuy_handle(default_conf, update, mocker) -> None:
telegram, freqtradebot, msg_mock = get_telegram_testobject(mocker, default_conf)
assert freqtradebot.config['max_open_trades'] != 0
telegram._stopbuy(update=update, context=MagicMock())
telegram._stopentry(update=update, context=MagicMock())
assert freqtradebot.config['max_open_trades'] == 0
assert msg_mock.call_count == 1
assert 'No more buy will occur from now. Run /reload_config to reset.' \
assert 'No more entries will occur from now. Run /reload_config to reset.' \
in msg_mock.call_args_list[0][0][0]

View File

@@ -12,7 +12,9 @@ from freqtrade.configuration import TimeRange
from freqtrade.data.dataprovider import DataProvider
from freqtrade.data.history import load_data
from freqtrade.enums import ExitCheckTuple, ExitType, SignalDirection
from freqtrade.enums.hyperoptstate import HyperoptState
from freqtrade.exceptions import OperationalException, StrategyError
from freqtrade.optimize.hyperopt_tools import HyperoptStateContainer
from freqtrade.optimize.space import SKDecimal
from freqtrade.persistence import PairLocks, Trade
from freqtrade.resolvers import StrategyResolver
@@ -859,7 +861,9 @@ def test_strategy_safe_wrapper_trade_copy(fee):
def test_hyperopt_parameters():
HyperoptStateContainer.set_state(HyperoptState.INDICATORS)
from skopt.space import Categorical, Integer, Real
with pytest.raises(OperationalException, match=r"Name is determined.*"):
IntParameter(low=0, high=5, default=1, name='hello')
@@ -937,6 +941,12 @@ def test_hyperopt_parameters():
assert list(boolpar.range) == [True, False]
HyperoptStateContainer.set_state(HyperoptState.OPTIMIZE)
assert len(list(intpar.range)) == 1
assert len(list(fltpar.range)) == 1
assert len(list(catpar.range)) == 1
assert len(list(boolpar.range)) == 1
def test_auto_hyperopt_interface(default_conf):
default_conf.update({'strategy': 'HyperoptableStrategyV2'})

View File

@@ -48,6 +48,10 @@ def test_search_all_strategies_with_failed():
assert len([x for x in strategies if x['class'] is not None]) == 9
assert len([x for x in strategies if x['class'] is None]) == 1
directory = Path(__file__).parent / "strats_nonexistingdir"
strategies = StrategyResolver.search_all_objects(directory, enum_failed=True)
assert len(strategies) == 0
def test_load_strategy(default_conf, result):
default_conf.update({'strategy': 'SampleStrategy',

View File

@@ -473,8 +473,6 @@ def test_create_trade_no_signal(default_conf_usdt, fee, mocker) -> None:
freqtrade = FreqtradeBot(default_conf_usdt)
patch_get_signal(freqtrade, enter_long=False, exit_long=False)
Trade.query = MagicMock()
Trade.query.filter = MagicMock()
assert not freqtrade.create_trade('ETH/USDT')

View File

@@ -1689,6 +1689,7 @@ def test_get_open(fee, is_short, use_db):
create_mock_trades(fee, is_short, use_db)
assert len(Trade.get_open_trades()) == 4
assert Trade.get_open_trade_count() == 4
Trade.use_db = True
@@ -1701,6 +1702,7 @@ def test_get_open_lev(fee, use_db):
create_mock_trades_with_leverage(fee, use_db)
assert len(Trade.get_open_trades()) == 5
assert Trade.get_open_trade_count() == 5
Trade.use_db = True
@@ -2892,8 +2894,8 @@ def test_order_to_ccxt(limit_buy_order_open):
(('buy', 100, 9), (200.0, 8.5, 1700.0, 0.0, None, None)),
(('sell', 100, 10), (100.0, 8.5, 850.0, 150.0, 150.0, 0.17647059)),
(('buy', 150, 11), (250.0, 10, 2500.0, 150.0, 150.0, 0.17647059)),
(('sell', 100, 12), (150.0, 10.0, 1500.0, 350.0, 350.0, 0.2)),
(('sell', 150, 14), (150.0, 10.0, 1500.0, 950.0, 950.0, 0.40)),
(('sell', 100, 12), (150.0, 10.0, 1500.0, 350.0, 200.0, 0.2)),
(('sell', 150, 14), (150.0, 10.0, 1500.0, 950.0, 600.0, 0.40)),
],
'end_profit': 950.0,
'end_profit_ratio': 0.283582,
@@ -2958,9 +2960,8 @@ def test_recalc_trade_from_orders_dca(data) -> None:
assert trade.amount == result[0]
assert trade.open_rate == result[1]
assert trade.stake_amount == result[2]
# TODO: enable the below.
assert pytest.approx(trade.realized_profit) == result[3]
# assert pytest.approx(trade.close_profit_abs) == result[4]
assert pytest.approx(trade.close_profit_abs) == result[4]
assert pytest.approx(trade.close_profit) == result[5]
trade.close(price)