Compare commits

..

691 Commits

Author SHA1 Message Date
Matthias
2cf36ca545 Merge pull request #4609 from freqtrade/new_release
New release 2021.3
2021-03-28 11:32:33 +02:00
Matthias
7fb34f7e25 Version bump 2021.3 2021-03-27 11:34:11 +01:00
Matthias
bf0f34c156 Merge branch 'stable' into new_release 2021-03-27 11:33:56 +01:00
Masoud Azizi
39bfe5e1a7 Thee to the 2021-03-26 20:51:14 +01:00
Matthias
8da7d5c009 Merge pull request #4594 from rextea/add_confirm_exit_enter_tade_to_backtesting
Add confirm_trade_exit and confirm_trade_entry to backtesting
2021-03-25 20:26:56 +01:00
Matthias
292ea8c1d0 Update backtesting.py 2021-03-25 09:34:33 +01:00
rextea
0ca95aa0c2 Change rate to acctual close rate 2021-03-25 10:25:25 +02:00
Matthias
ec15610bff Fix isort issue 2021-03-24 19:21:07 +01:00
rextea
d795febf92 Add info to documantation 2021-03-24 18:26:03 +02:00
Matthias
ee82d36bef Merge pull request #4593 from hoeckxer/feat/status_table_telegram_length
Changed the code for status table a bit so that it splits up the trad…
2021-03-24 06:49:54 +01:00
Erwin Hoeckx
2fd510e6e4 Added comment with an example calculation
Signed-off-by: Erwin Hoeckx <hawkeyenl@yahoo.com>
2021-03-23 21:52:46 +01:00
Erwin Hoeckx
65a9763fa5 Fixed an issue when there were exactly 50 trades, it was sending an extra empty table
Signed-off-by: Erwin Hoeckx <hawkeyenl@yahoo.com>
2021-03-23 16:54:38 +01:00
Erwin Hoeckx
c928cd38dc Small bugfix to make sure it shows all the trades
Signed-off-by: Erwin Hoeckx <hawkeyenl@yahoo.com>
2021-03-23 16:45:42 +01:00
Matthias
d5301b4d63 RateLimit should be enabled by default 2021-03-23 10:53:09 +01:00
rextea
f51f4b1817 Add confirm_trade_exit and confirm_trade_entry to backtesting 2021-03-23 10:35:46 +02:00
rextea
dc4ea604dd Add confirm_trade_exit and confirm_trade_entry to backtesting 2021-03-23 10:19:16 +02:00
rextea
eb5d69dcd4 Add confirm_trade_exit and confirm_trade_entry to backtesting 2021-03-23 10:12:08 +02:00
rextea
6856963aef Add confirm_trade_exit and confirm_trade_entry to backtesting 2021-03-23 10:09:41 +02:00
Erwin Hoeckx
4e8999ade3 Changed the code for status table a bit so that it splits up the trades per 50 trades, to make sure it can be sent regardless of number of trades
Signed-off-by: Erwin Hoeckx <hawkeyenl@yahoo.com>
2021-03-22 20:40:11 +01:00
Matthias
7adfa0cfd9 Merge pull request #4592 from freqtrade/dependabot/pip/develop/sqlalchemy-1.4.2
Bump sqlalchemy from 1.3.23 to 1.4.2
2021-03-22 20:00:13 +01:00
Matthias
b7702a1e9f Improve tests to work with new sqlalchemy version 2021-03-22 19:39:06 +01:00
Matthias
e39cff522d Remove duplicate dict keys in test 2021-03-22 17:30:16 +01:00
Matthias
77610b6a6d Merge pull request #4590 from freqtrade/dependabot/pip/develop/urllib3-1.26.4
Bump urllib3 from 1.26.3 to 1.26.4
2021-03-22 06:53:21 +01:00
Matthias
efe1315a17 Merge pull request #4589 from freqtrade/dependabot/pip/develop/ccxt-1.43.89
Bump ccxt from 1.43.27 to 1.43.89
2021-03-22 06:52:38 +01:00
Matthias
d4ca62f7f3 Merge pull request #4591 from freqtrade/dependabot/pip/develop/isort-5.8.0
Bump isort from 5.7.0 to 5.8.0
2021-03-22 06:52:18 +01:00
dependabot[bot]
ea3012e94d Bump sqlalchemy from 1.3.23 to 1.4.2
Bumps [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) from 1.3.23 to 1.4.2.
- [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases)
- [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/master/CHANGES)
- [Commits](https://github.com/sqlalchemy/sqlalchemy/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-22 05:25:35 +00:00
dependabot[bot]
09c7ee9e92 Bump isort from 5.7.0 to 5.8.0
Bumps [isort](https://github.com/pycqa/isort) from 5.7.0 to 5.8.0.
- [Release notes](https://github.com/pycqa/isort/releases)
- [Changelog](https://github.com/PyCQA/isort/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/pycqa/isort/compare/5.7.0...5.8.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-22 05:25:28 +00:00
dependabot[bot]
9612ba34ed Bump urllib3 from 1.26.3 to 1.26.4
Bumps [urllib3](https://github.com/urllib3/urllib3) from 1.26.3 to 1.26.4.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/1.26.3...1.26.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-22 05:25:17 +00:00
dependabot[bot]
ac7a1305cb Bump ccxt from 1.43.27 to 1.43.89
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.43.27 to 1.43.89.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.43.27...1.43.89)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-22 05:25:11 +00:00
Matthias
e315a6a0da assume "last" can miss from a ticker response
closes #4573
2021-03-20 14:58:51 +01:00
Matthias
43d7f9ac67 Add bid_last_balance parameter
to interpolate sell prices

closes #3270
2021-03-20 14:38:26 +01:00
Matthias
f4e71c1f14 get_buy_rate tests should be sensible 2021-03-20 14:02:13 +01:00
Matthias
73876b61b4 Show potential errors when loading markets 2021-03-20 13:34:33 +01:00
Matthias
16a54b3616 Don't require non-mandatory arguments 2021-03-20 13:08:02 +01:00
Matthias
fe7f3d9c37 Add price side validation for market orders 2021-03-20 11:48:39 +01:00
Matthias
066dd72210 add orderbook structure documentation 2021-03-20 08:34:15 +01:00
Matthias
0a9622a065 Merge pull request #4581 from freqtrade/fix/4578
Fix calculation error for min-trade-stake
2021-03-20 08:21:52 +01:00
Matthias
69799532a6 Document usage of open_date_utc
closes #4580
2021-03-20 08:13:56 +01:00
Matthias
7ffe1fd36a Fix calculation error for min-trade-stake 2021-03-20 07:21:22 +01:00
Matthias
fd34d454a8 Merge pull request #4574 from maycon/patch-1
Added slash to fix a broken formatting
2021-03-19 20:32:31 +01:00
Matthias
fb90901bb3 Fix telegram table for both rendered and github markdown 2021-03-19 20:12:12 +01:00
Maycon Maia Vitali
c1f7992270 Added slash to fix a broken formatting
On the command table the pipe(|) broke the formatting.
2021-03-19 10:39:45 -03:00
Matthias
0d5833ed91 Use OperationalException for TimeRange errors 2021-03-19 06:40:04 +01:00
Matthias
c304651249 Merge pull request #4571 from pbrunier/develop
Improvement for timerange parser
2021-03-19 06:36:22 +01:00
Patrick Brunier
4d52732d30 Added a small snippet to give users a descent error message,
when their start date is afer the stop date.
Also updated the tests.
2021-03-18 22:38:54 +01:00
Matthias
84ca9bd2c7 Merge pull request #4543 from brookmiles/fix-math-custom-stoploss-docs
correct math used in examples and clarify some terminology regarding …
2021-03-18 19:32:30 +01:00
Matthias
dd4d1d82d4 Update docs/strategy-advanced.md 2021-03-18 14:19:33 +01:00
Brook Miles
bf14796d4c revert "Trailing stoploss with positive offset" example as stoploss_from_open() wasn't adding value 2021-03-18 21:50:54 +09:00
Matthias
b6e9e74a8b Add link between stoploss_from_open and custom_stop documentation 2021-03-18 06:46:08 +01:00
Brook Miles
983c0ef118 update stoploss_from_open examples to use helper function 2021-03-18 09:47:03 +09:00
Matthias
76ca3c219f extract result-printing from hyperopt class 2021-03-17 20:45:15 +01:00
Matthias
b05de6d468 Move advanced exchange config to exchange page 2021-03-17 19:36:35 +01:00
Matthias
6597055a24 Ensure ccxt tests run without dry-run
closes #4566
2021-03-17 19:36:11 +01:00
Brook Miles
ce1ed76269 complete stoploss_from_open and associated test 2021-03-17 22:44:10 +09:00
Brook Miles
aee2591490 add stoploss_from_open() as a strategy_helper 2021-03-17 17:58:23 +09:00
Matthias
79d4585dad Add check to ensure close_profit_abs is filled on closed trades
Technically, this should not be possible, but #4554 shows it is.

closes #4554
2021-03-16 19:24:03 +01:00
Matthias
dd5873ef24 Merge pull request #4552 from freqtrade/dependabot/pip/develop/ccxt-1.43.27
Bump ccxt from 1.42.66 to 1.43.27
2021-03-15 19:50:43 +01:00
Matthias
09aa678e59 Merge pull request #4549 from freqtrade/dependabot/pip/develop/prompt-toolkit-3.0.17
Bump prompt-toolkit from 3.0.16 to 3.0.17
2021-03-15 11:33:28 +01:00
dependabot[bot]
8f26935259 Bump ccxt from 1.42.66 to 1.43.27
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.42.66 to 1.43.27.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.42.66...1.43.27)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-15 09:26:02 +00:00
Matthias
ecc677ad13 Merge pull request #4550 from freqtrade/dependabot/pip/develop/python-telegram-bot-13.4.1
Bump python-telegram-bot from 13.3 to 13.4.1
2021-03-15 08:38:20 +01:00
Matthias
6ae2774b7a Merge pull request #4548 from freqtrade/dependabot/pip/develop/mkdocs-material-7.0.6
Bump mkdocs-material from 7.0.5 to 7.0.6
2021-03-15 07:19:27 +01:00
Matthias
8a4fd05ded Merge pull request #4551 from freqtrade/fix/slacknotify
Update slack action
2021-03-15 07:19:05 +01:00
Matthias
b4b11c403d Merge pull request #4546 from freqtrade/dependabot/pip/develop/flake8-3.9.0
Bump flake8 from 3.8.4 to 3.9.0
2021-03-15 07:18:53 +01:00
Matthias
b6c29bebb0 Update slack action 2021-03-15 06:56:48 +01:00
dependabot[bot]
a209b0a392 Bump python-telegram-bot from 13.3 to 13.4.1
Bumps [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) from 13.3 to 13.4.1.
- [Release notes](https://github.com/python-telegram-bot/python-telegram-bot/releases)
- [Changelog](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-telegram-bot/python-telegram-bot/compare/v13.3...v13.4.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-15 05:28:18 +00:00
dependabot[bot]
1173d8971a Bump prompt-toolkit from 3.0.16 to 3.0.17
Bumps [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) from 3.0.16 to 3.0.17.
- [Release notes](https://github.com/prompt-toolkit/python-prompt-toolkit/releases)
- [Changelog](https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/CHANGELOG)
- [Commits](https://github.com/prompt-toolkit/python-prompt-toolkit/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-15 05:28:06 +00:00
dependabot[bot]
22c34faca3 Bump mkdocs-material from 7.0.5 to 7.0.6
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 7.0.5 to 7.0.6.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/7.0.5...7.0.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-15 05:28:02 +00:00
dependabot[bot]
09872d8e42 Bump flake8 from 3.8.4 to 3.9.0
Bumps [flake8](https://gitlab.com/pycqa/flake8) from 3.8.4 to 3.9.0.
- [Release notes](https://gitlab.com/pycqa/flake8/tags)
- [Commits](https://gitlab.com/pycqa/flake8/compare/3.8.4...3.9.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-15 05:27:18 +00:00
Matthias
b191663a7e Adapt hyperopt templates to be better aligned
closes #3027
2021-03-14 19:49:46 +01:00
Matthias
0b35c0571f Allow custom fee to be used during dry-run
closes #3696
2021-03-14 19:37:57 +01:00
Brook Miles
e924416431 correct math used in examples and clarify some terminology regarding custom stoploss functions 2021-03-14 22:02:53 +09:00
Matthias
7a63f8cc31 Fix hdf5 support on raspberry 2021-03-14 13:25:08 +01:00
Matthias
b57c150654 Final balance should include forcesold pairs 2021-03-14 09:48:40 +01:00
Matthias
9fb6cfcdad Merge pull request #4540 from jlaw/fix-date-test-utc
fix: Use now() to match timezone of download data
2021-03-14 07:03:29 +01:00
Jackson Law
618bae23a6 fix: Use now() to match timezone of download data 2021-03-13 11:14:36 -08:00
Matthias
cd8d9f2930 Merge pull request #4534 from rokups/patch-1
Provide access to strategy instance from hyperopt class.
2021-03-13 17:14:47 +01:00
Matthias
3b99f04a78 Merge pull request #4535 from freqtrade/fix/backtestperformance
Improve backtest performance after enabling compounding
2021-03-13 16:51:00 +01:00
Matthias
eb4f05eb23 Add documentation for hyperopt.strategy availability 2021-03-13 16:47:12 +01:00
Matthias
3a0739183a Merge pull request #4530 from jlaw/develop
Create event loop manually if uvloop is available
2021-03-13 16:25:16 +01:00
Matthias
6389e86ed6 Add test for uvloop fix 2021-03-13 16:09:07 +01:00
Matthias
0320c8dc92 Improve tests for trades_proxy 2021-03-13 15:51:27 +01:00
Rokas Kupstys
5e872273d1 Provide access to strategy instance from hyperopt class. 2021-03-13 15:13:42 +02:00
Matthias
d1acc8092c Improve backtest performance 2021-03-13 10:17:14 +01:00
Jackson Law
425cd7adba Create event loop manually if uvloop is available
asyncio.get_event_loop() does not call new_event_loop()
if current_thread() != main_thread()
2021-03-12 16:16:03 -08:00
Matthias
441d3fad39 Merge pull request #4513 from freqtrade/fix/4511
Fix stoploss order problem with FTX
2021-03-11 19:39:44 +01:00
Matthias
ef9977fc1e Make stake_amount + stake_currency mandatory for backtesting 2021-03-10 10:43:44 +01:00
Matthias
333ad02605 Fix random test failure 2021-03-10 10:39:38 +01:00
Matthias
0db5c9746f Merge pull request #4454 from freqtrade/backtest_compound_speed
Backtest compound, wallet, ...
2021-03-10 10:07:40 +01:00
Matthias
60f6b998d3 Update logo with smiling one 2021-03-10 09:27:03 +01:00
Matthias
99583bbd0c Fix problem with FTX
where cancelled orders are "cancelled", not "canceled"
2021-03-09 20:21:08 +01:00
Matthias
dd420a22e9 Merge pull request #4508 from Th0masL/fix_order_by
Change order_by from ID to close_date for /trades command
2021-03-09 20:20:04 +01:00
Matthias
a1902f226d Make trade-close sequence clear for mock trades 2021-03-09 19:29:00 +01:00
Th0masL
37e6006169 Fix order_by in trades command 2021-03-08 23:21:56 +02:00
Matthias
4b550dab17 Always reset fake-databases
Otherwise results may stick around for the next strategy
2021-03-08 19:40:29 +01:00
Matthias
61ec7a309b Merge pull request #4501 from freqtrade/dependabot/pip/develop/aiohttp-3.7.4.post0
Bump aiohttp from 3.7.4 to 3.7.4.post0
2021-03-08 17:12:55 +01:00
dependabot[bot]
25c9e89956 Bump aiohttp from 3.7.4 to 3.7.4.post0
Bumps [aiohttp](https://github.com/aio-libs/aiohttp) from 3.7.4 to 3.7.4.post0.
- [Release notes](https://github.com/aio-libs/aiohttp/releases)
- [Changelog](https://github.com/aio-libs/aiohttp/blob/master/CHANGES.rst)
- [Commits](https://github.com/aio-libs/aiohttp/compare/v3.7.4...v3.7.4.post0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 09:15:30 +00:00
Matthias
5e3e1e22e3 Merge pull request #4502 from freqtrade/dependabot/pip/develop/pandas-1.2.3
Bump pandas from 1.2.2 to 1.2.3
2021-03-08 10:12:03 +01:00
dependabot[bot]
7950acf6d4 Bump pandas from 1.2.2 to 1.2.3
Bumps [pandas](https://github.com/pandas-dev/pandas) from 1.2.2 to 1.2.3.
- [Release notes](https://github.com/pandas-dev/pandas/releases)
- [Changelog](https://github.com/pandas-dev/pandas/blob/master/RELEASE.md)
- [Commits](https://github.com/pandas-dev/pandas/compare/v1.2.2...v1.2.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 08:53:20 +00:00
Matthias
7e45af97e6 Merge pull request #4504 from freqtrade/dependabot/pip/develop/mkdocs-material-7.0.5
Bump mkdocs-material from 7.0.3 to 7.0.5
2021-03-08 07:31:06 +01:00
Matthias
bb1f888b4c Merge pull request #4503 from freqtrade/dependabot/pip/develop/arrow-1.0.3
Bump arrow from 1.0.2 to 1.0.3
2021-03-08 07:30:38 +01:00
Matthias
7e897343c8 Merge pull request #4499 from freqtrade/dependabot/pip/develop/coveralls-3.0.1
Bump coveralls from 3.0.0 to 3.0.1
2021-03-08 06:52:08 +01:00
Matthias
6217c4c886 Merge pull request #4500 from freqtrade/dependabot/pip/develop/ccxt-1.42.66
Bump ccxt from 1.42.47 to 1.42.66
2021-03-08 06:51:39 +01:00
dependabot[bot]
a9c114d301 Bump mkdocs-material from 7.0.3 to 7.0.5
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 7.0.3 to 7.0.5.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/7.0.3...7.0.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 05:28:27 +00:00
dependabot[bot]
a2b9236082 Bump arrow from 1.0.2 to 1.0.3
Bumps [arrow](https://github.com/arrow-py/arrow) from 1.0.2 to 1.0.3.
- [Release notes](https://github.com/arrow-py/arrow/releases)
- [Changelog](https://github.com/arrow-py/arrow/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/arrow-py/arrow/compare/1.0.2...1.0.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 05:28:23 +00:00
dependabot[bot]
1f314f7d45 Bump ccxt from 1.42.47 to 1.42.66
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.42.47 to 1.42.66.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.42.47...1.42.66)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 05:28:15 +00:00
dependabot[bot]
46965b1a2c Bump coveralls from 3.0.0 to 3.0.1
Bumps [coveralls](https://github.com/TheKevJames/coveralls-python) from 3.0.0 to 3.0.1.
- [Release notes](https://github.com/TheKevJames/coveralls-python/releases)
- [Changelog](https://github.com/TheKevJames/coveralls-python/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TheKevJames/coveralls-python/compare/3.0.0...3.0.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 05:28:11 +00:00
Matthias
0b81b58d28 Use pandas.values.tolist instead of itertuples
speeds up backtesting
closes #4494
2021-03-07 11:28:54 +01:00
Matthias
02d7dc4780 Increase cache size to be large enough to hold all pairs
closes #4483
2021-03-06 19:55:02 +01:00
Matthias
b515609d73 Merge pull request #4490 from Th0masL/add_trade_id
Add the trade ID to Telegram Buy/Sell/Cancel messages
2021-03-06 15:40:34 +01:00
Th0masL
ad0e60b5b6 Add trade_id to Cancel messages and reduced lines length 2021-03-06 15:07:47 +02:00
Matthias
eed8c94dd9 Merge pull request #4488 from patrick310/patch-1
Add strategy name to HyperOpt results filename
2021-03-06 13:48:12 +01:00
Matthias
28109846d5 Merge pull request #4489 from freqtrade/forcebuy_ordertype
forcebuy ordertype
2021-03-06 13:37:46 +01:00
Th0masL
2472f52874 Add trade_id to tests 2021-03-06 01:07:37 +02:00
Th0masL
03b89e7f78 Add trade_id in Telegram messages 2021-03-06 00:04:12 +02:00
Matthias
a405d578da Introduce forcebuy ordertype to allow specifiying a different ordertype for forcebuy / forcesells 2021-03-05 20:22:04 +01:00
Patrick Weber
4532222010 Fixed line length in HyperOpt for new name
Fixed line length errors and multiple f strings to facilitate strategy being added in the name
2021-03-05 13:16:49 -06:00
Matthias
5196306407 Remove deprecated profit return value 2021-03-05 20:03:49 +01:00
Patrick Weber
345f7404e9 Add strategy name to HyperOpt results filename
This just extends the HyperOpt result filename by adding the strategy name. This allows analysis of HyperOpt results folder with no additional necessary context. An alternative idea would be to expand the result dict, but the additional static copies are non value added.
2021-03-05 12:56:11 -06:00
Matthias
a39e83dbd4 Merge pull request #4482 from raoulbuzziol/develop
added "Median profit" column to hyperopt -> export-csv
2021-03-05 19:37:21 +01:00
Matthias
731ab5d2a7 Fix too long line errors 2021-03-05 19:22:57 +01:00
Matthias
bc05d03126 Make best / worst day absolute 2021-03-05 19:21:09 +01:00
Matthias
8c371ace32 Merge pull request #4478 from JoeSchr/docs/add-custom_info-examples
Documentation: Add examples how to use dataframe with "custom_info"
2021-03-05 07:24:50 +01:00
JoeSchr
dfeafc2204 Update docs/strategy-customization.md
Co-authored-by: Matthias <xmatthias@outlook.com>
2021-03-04 20:05:27 +01:00
JoeSchr
161a4656d5 Update docs/strategy-advanced.md
Co-authored-by: Matthias <xmatthias@outlook.com>
2021-03-04 20:05:21 +01:00
Joe Schr
1304918a29 fix(docs/strategy-advanced/custom_info-storage/example): only add to "custom_info" in backtesting and hyperopt 2021-03-04 20:03:43 +01:00
Joe Schr
900deb663a fix(docs/strategy-advanced/custom_stoploss/example): check if "pair" exists in "custom_info" before requesting 2021-03-04 20:03:43 +01:00
Joe Schr
c56b9cd751 fix(docs/strategy-advanced): add warnings 2021-03-04 20:03:43 +01:00
Joe Schr
a6ef354a5f fix(docs/strategy-advanced): use get_analyzed_dataframe() instead of custom_info.iloc 2021-03-04 20:03:43 +01:00
Joe Schr
22a558e331 fix(docs/strategy-advanced): fix link to custom_info storage 2021-03-04 20:03:42 +01:00
Joe Schr
1a02a146a1 feature(docs/strategy-advanced/custom_info-storage/example): add ATR column calculation 2021-03-04 20:03:42 +01:00
Joe Schr
4064f856d1 fix(docs/strategy-customization): add "hyperopt" to runmode check for custom_info in custom_stoploss example 2021-03-04 20:03:42 +01:00
Joe Schr
b52698197b refactor(docs/strategy-advanced): extract "Storing information" section from strategy-customization.md 2021-03-04 20:03:42 +01:00
Joe Schr
d05acc30fa fix(docs/strategy-customization): remove superflous prints from example code 2021-03-04 20:03:42 +01:00
Joe Schr
32f35fcd90 fix(docs/strategy-customization): "custom_stoploss indicator" example need to check for RUN_MODE 2021-03-04 20:03:42 +01:00
Joe Schr
c5900bbd38 feature(docs/strategy-customization): add example "Custom stoploss using an indicator from dataframe" 2021-03-04 20:03:42 +01:00
Joe Schr
cc4e84bb70 feature(docs/strategy-customization): add example how to store indicator with DatetimeIndex into custom_info 2021-03-04 20:03:42 +01:00
Joe Schr
5cf3194fab chore(docs/strategy-customization): clean up left over trailing whitespaces 2021-03-04 20:03:42 +01:00
Joe Schr
d5993db064 refactor(docs/strategy-customization): change variable name for better readability
`cust_info` -> `custom_info`
2021-03-04 20:03:42 +01:00
raoulus
0968ecc1af added "Median profit" column to hyperopt -> export-csv 2021-03-04 17:27:04 +01:00
Matthias
078b77d41b Fix crash when using unlimited stake and no trades are made 2021-03-02 16:12:22 +01:00
Matthias
0be34291ef Merge pull request #4473 from JoeSchr/backtest_compound_speed
fix: avg_stake_amount should not be `NaN` if df is empty
2021-03-02 13:59:53 +01:00
Joe Schr
55a315be14 fix: avg_stake_amount should not be NaN if df is empty 2021-03-02 13:38:55 +01:00
Matthias
f00c4fc27b Merge pull request #4472 from av1nxsh/develop
Add ping support to rest_client.py
2021-03-02 12:03:02 +01:00
av1nxsh
a85e656e8d rest_client.py
optimised with var 'configstatus'
2021-03-02 16:16:20 +05:30
av1nxsh
218d22ed52 rest_client.py
updated for connection error case
2021-03-02 15:45:16 +05:30
Matthias
6eb253c31e Merge pull request #4469 from freqtrade/rpc/locks
Add RPC methods to remove locks
2021-03-02 10:41:08 +01:00
av1nxsh
95c635091e rest_client.py
fixed operator
2021-03-02 14:57:05 +05:30
av1nxsh
82bf65f696 rest_client.py
flake8 issues
2021-03-02 14:49:33 +05:30
av1nxsh
4fe2e542b4 rest_client.py
removing tab
2021-03-02 14:25:37 +05:30
av1nxsh
7c35d107ab rest_client.py
first
2021-03-02 14:24:00 +05:30
Matthias
4bb6a27745 Don't catch errors that can't happen 2021-03-02 06:59:58 +01:00
Matthias
007ac7abb5 Add telegram pair unlocking 2021-03-01 20:09:40 +01:00
Matthias
6640156ac7 Support deleting locks via API 2021-03-01 19:50:39 +01:00
Matthias
4e51364057 Add warning about sandboxes
closes #4468
2021-03-01 19:12:02 +01:00
Matthias
7dc77d0af6 Merge pull request #4463 from freqtrade/dependabot/pip/develop/mkdocs-material-7.0.3
Bump mkdocs-material from 6.2.8 to 7.0.3
2021-03-01 09:48:08 +01:00
Matthias
64ef7becc7 Update styles to work with new mkdocs version 2021-03-01 09:35:35 +01:00
Matthias
6eef6d41bc Merge pull request #4465 from freqtrade/dependabot/pip/develop/arrow-1.0.2
Bump arrow from 0.17.0 to 1.0.2
2021-03-01 09:30:11 +01:00
Matthias
2083cf6ddf Fix mypy errors introduced by Arrow update 2021-03-01 08:57:57 +01:00
Matthias
0ebefdfeb6 Merge pull request #4464 from freqtrade/dependabot/pip/develop/ccxt-1.42.47
Bump ccxt from 1.42.19 to 1.42.47
2021-03-01 08:19:17 +01:00
Matthias
3d65ba2dcb Add rpc method to delete locks 2021-03-01 07:51:33 +01:00
Matthias
bba9b9e819 Don't use __root__ directly for api response 2021-03-01 07:08:44 +01:00
dependabot[bot]
4537a48988 Bump arrow from 0.17.0 to 1.0.2
Bumps [arrow](https://github.com/arrow-py/arrow) from 0.17.0 to 1.0.2.
- [Release notes](https://github.com/arrow-py/arrow/releases)
- [Changelog](https://github.com/arrow-py/arrow/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/arrow-py/arrow/compare/0.17.0...1.0.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-01 05:32:17 +00:00
dependabot[bot]
d0fd3c289c Bump ccxt from 1.42.19 to 1.42.47
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.42.19 to 1.42.47.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.42.19...1.42.47)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-01 05:32:14 +00:00
dependabot[bot]
00747a3bc3 Bump mkdocs-material from 6.2.8 to 7.0.3
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 6.2.8 to 7.0.3.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/6.2.8...7.0.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-01 05:31:43 +00:00
Matthias
4b689f5b88 Merge pull request #4420 from freqtrade/dependabot/pip/develop/mypy-0.812
Bump mypy from 0.790 to 0.812
2021-02-28 15:30:44 +01:00
Matthias
aba034ff40 Fix mypy problem after mypy 0.800 upgrade 2021-02-28 11:04:30 +01:00
dependabot[bot]
94cab4ed71 Bump mypy from 0.790 to 0.812
Bumps [mypy](https://github.com/python/mypy) from 0.790 to 0.812.
- [Release notes](https://github.com/python/mypy/releases)
- [Commits](https://github.com/python/mypy/compare/v0.790...v0.812)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-28 11:04:30 +01:00
Matthias
54ccbd9370 Merge pull request #4391 from squat0001/develop
Add dust level to balance command in telegram
2021-02-28 10:36:44 +01:00
Matthias
a13dc3cdde Use sensible defaults for balance_dust_level 2021-02-28 09:57:52 +01:00
Matthias
9cb37409fd Explicitly convert starting-balance to float 2021-02-28 09:56:29 +01:00
Florian Reitmeir
0895407811 add balance_dust_level parameter to make telegram less chatty 2021-02-28 08:51:32 +01:00
Matthias
05f057fe72 Stringify favicon path
potentially closes #4459
2021-02-28 08:48:28 +01:00
Matthias
bc0efe5baa Merge pull request #4457 from JoeSchr/patch-4
Fix: custom_stoploss returns typo
2021-02-28 08:36:21 +01:00
JoeSchr
e791ff6042 Fix: custom_stoploss returns typo
Afaik it should return -0.07 for 7% instead of -0.7.

As a side note, really interesting would also be an example for greater than 100% profits. especially when trailing stoploss, like
* Once profit is > 200% - stoploss will be set to 150%.

I assume it could be as simple as
```py
if current_profit > 2:
            return (-1.50 + current_profit)
````
to achieve it

But I'm not quite confident, if the bot can handle stuff smaller than `-1`, since `1` and `-1` seem to have some special meaning and are often used to disable stoploss etc.
2021-02-27 23:28:26 +01:00
Matthias
d9d5617432 UPdate backtesting doc for total profit calc 2021-02-27 20:26:13 +01:00
Matthias
b2e9295d7f Small stylistic fixes 2021-02-27 19:57:42 +01:00
Matthias
6018a05343 Improve backtest documentation 2021-02-27 10:45:22 +01:00
Matthias
324b9dbdff Simplify wallet code 2021-02-27 10:33:25 +01:00
Matthias
f65092459a Fix optimize_reports test 2021-02-27 10:14:25 +01:00
Matthias
fb489c11c9 Improve test-coverage of pairlocks 2021-02-27 10:07:02 +01:00
Matthias
f5bb5f56f1 Update documentation with backtesting compounding possibilities 2021-02-27 09:33:00 +01:00
Matthias
98f3142b30 Improve handling of backtesting params 2021-02-27 09:33:00 +01:00
Matthias
86f9409fd2 fix --stake-amount parameter 2021-02-27 09:33:00 +01:00
Matthias
d3fb473e57 Improve backtesting documentation 2021-02-27 09:33:00 +01:00
Matthias
fc256749af Add test for backtesting _enter_trade 2021-02-27 09:33:00 +01:00
Matthias
60db6ccf45 Add test for subclassing 2021-02-27 09:33:00 +01:00
Matthias
53a57f2c81 Change some types
Fix types of new model object
2021-02-27 09:33:00 +01:00
Matthias
03eb23a4ce 2 levels of Trade models, one with and one without sqlalchemy
Fixes a performance issue when backtesting with sqlalchemy, as that
uses descriptors for all properties.
2021-02-27 09:33:00 +01:00
Matthias
394a6bbf2a Fix some type errors 2021-02-27 09:33:00 +01:00
Matthias
52acacbed5 Check min-trade-stake in backtesting 2021-02-27 09:33:00 +01:00
Matthias
f04f07299c Improve backtesting metrics 2021-02-27 09:33:00 +01:00
Matthias
7913166453 Improve performance by updating wallets only when necessary 2021-02-27 09:33:00 +01:00
Matthias
37d7d2afd5 Wallets should not recalculate close_profit for closed trades 2021-02-27 09:33:00 +01:00
Matthias
f367375e5b ABS drawdown should show wallet high and low values 2021-02-27 09:33:00 +01:00
Matthias
aed23d55c2 Add starting balance to profit cumsum calculation 2021-02-27 09:33:00 +01:00
Matthias
0d2f877e77 Use absolute drawdown calc 2021-02-27 09:32:59 +01:00
Matthias
74fc4bdab5 Shorten debug log 2021-02-27 09:32:59 +01:00
Matthias
72f21fc5ec Add trade-volume metric 2021-02-27 09:32:59 +01:00
Matthias
35e6a9ab3a Backtest-reports should calculate total gains based on starting capital 2021-02-27 09:32:59 +01:00
Matthias
8d61a26382 Allow dynamic stake for backtesting and hyperopt 2021-02-27 09:32:59 +01:00
Matthias
e4abe902fc Enable compounding for backtesting 2021-02-27 09:32:59 +01:00
Matthias
959ff99046 Add Dry-run wallet CLI option 2021-02-27 09:32:59 +01:00
Matthias
0754a7a78f total_open_trades_stake should support no-db mode 2021-02-27 09:32:59 +01:00
Matthias
0faa6f84dc Improve Wallet logging disabling for backtesting 2021-02-27 09:32:59 +01:00
Matthias
20455de2a9 Small enhancements to docs 2021-02-27 09:32:59 +01:00
Matthias
081b9be45c use get_all_locks to get locks for backtest result 2021-02-27 09:32:59 +01:00
Matthias
e32b2097f0 Use timestamp in UTC timezone for ROI comparisons 2021-02-27 09:32:59 +01:00
Matthias
712d503e6c Use sell-reason value in backtesting, not the enum object 2021-02-27 09:32:59 +01:00
Matthias
b5177eadab Extract close method for exchange 2021-02-27 09:32:59 +01:00
Matthias
4ce4eadc23 remove only ccxt objects when hyperopting 2021-02-27 09:32:59 +01:00
Matthias
9361aa1c95 Add wallets to backtesting 2021-02-27 09:32:59 +01:00
Matthias
f0a154692d Wallets should use trade_proxy 2021-02-27 09:32:59 +01:00
Matthias
9968e4e49c Add warning about downloading data from kraken
closes #4449
2021-02-27 08:26:13 +01:00
Matthias
b92fb6d3d0 Merge pull request #4452 from JoeSchr/patch-3
Fix(strategy/interface.py): comment typo
2021-02-27 08:16:50 +01:00
JoeSchr
642e3be7c5 Fix(strategy/interface.py): comment typo
`advice_buy` -> `advise_buy`
2021-02-26 23:17:59 +01:00
Matthias
0bb80d1442 Merge pull request #4446 from Xanders/patch-1
Webhook JSON format
2021-02-26 20:03:07 +01:00
Matthias
7d87c44c35 Merge pull request #4436 from Th0masL/forcesell_type
Allow changing the order_type for forcesell
2021-02-26 19:42:00 +01:00
Xanders
f0391d3761 Better JSON webhook result description 2021-02-26 21:40:45 +03:00
Xanders
efa50be145 Fix blank lines rule at test_rpc_webhook.py 2021-02-26 21:32:41 +03:00
Xanders
7281e794b4 Fix too long line at webhook.py 2021-02-26 21:31:33 +03:00
Matthias
9a926c155d Add forcesell entry to full config 2021-02-26 19:30:42 +01:00
Xanders
984e70d4e8 Add webhook result example to documentation 2021-02-26 21:15:40 +03:00
Xanders
52641aaa31 Add test for webhook JSON format 2021-02-26 18:12:10 +03:00
Xanders
a2cd3ed5ba Add documentation for JSON webhook format 2021-02-26 17:59:38 +03:00
Xanders
fc69240e6d Add JSON-encoded webhooks 2021-02-26 17:46:23 +03:00
Matthias
cc12919ee3 Merge pull request #4445 from seguri/patch-1
Fix #4441
2021-02-26 11:28:50 +01:00
Marco Seguri
51d73a5889 Fix #4441 2021-02-26 11:11:27 +01:00
Matthias
55015c4aa3 Merge pull request #4444 from freqtrade/dependabot/pip/aiohttp-3.7.4
Bump aiohttp from 3.7.3 to 3.7.4
2021-02-26 08:31:11 +01:00
dependabot[bot]
622ff771ec Bump aiohttp from 3.7.3 to 3.7.4
Bumps [aiohttp](https://github.com/aio-libs/aiohttp) from 3.7.3 to 3.7.4.
- [Release notes](https://github.com/aio-libs/aiohttp/releases)
- [Changelog](https://github.com/aio-libs/aiohttp/blob/master/CHANGES.rst)
- [Commits](https://github.com/aio-libs/aiohttp/compare/v3.7.3...v3.7.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-26 07:21:04 +00:00
Matthias
1b3b389109 Remove binanceje, add ftx to config selector
closes #4441
2021-02-26 07:58:15 +01:00
Matthias
c4979fd87f Add note to check configuration settings to docker quickstart
part of #4441
2021-02-26 06:57:51 +01:00
Matthias
d877e3c1df Fix failing CI due to unavailable pairs 2021-02-26 06:51:32 +01:00
Matthias
6d38a2e659 Small enhancements to docs 2021-02-25 19:57:09 +01:00
Matthias
262394e112 Add psutils to support OOM Gracefull shutdown
closes #4436, #4439 #3990
2021-02-25 19:24:30 +01:00
Th0masL
006f31129e Reduced length of the line 2021-02-25 05:23:24 +02:00
Th0masL
117f0064ed Allow changing the order_type for forcesell 2021-02-25 05:02:08 +02:00
Matthias
38b96f071f Merge pull request #4434 from freqtrade/new_release
New release 2020.2
2021-02-24 19:27:43 +01:00
Matthias
1f30c3d7f1 Refresh slack link 2021-02-24 06:46:32 +01:00
Matthias
834f00f580 Refresh slack link 2021-02-24 06:46:07 +01:00
Matthias
aea8f05d10 Version bump 2021.2 2021-02-24 06:39:59 +01:00
Matthias
cae67b02df Merge branch 'stable' into new_release 2021-02-24 06:39:51 +01:00
Matthias
d6d8678fd6 Fix missleading FAQ information 2021-02-24 06:34:10 +01:00
Matthias
133562ba06 Merge pull request #4428 from freqtrade/dependabot/pip/develop/ccxt-1.42.19
Bump ccxt from 1.41.90 to 1.42.19
2021-02-22 22:01:38 +01:00
Matthias
e8794e8b8c Merge pull request #4429 from freqtrade/dependabot/pip/develop/tabulate-0.8.9
Bump tabulate from 0.8.8 to 0.8.9
2021-02-22 21:59:44 +01:00
dependabot[bot]
3612c786b5 Bump tabulate from 0.8.8 to 0.8.9
Bumps [tabulate](https://github.com/astanin/python-tabulate) from 0.8.8 to 0.8.9.
- [Release notes](https://github.com/astanin/python-tabulate/releases)
- [Changelog](https://github.com/astanin/python-tabulate/blob/master/CHANGELOG)
- [Commits](https://github.com/astanin/python-tabulate/compare/v0.8.8...v0.8.9)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 19:06:39 +00:00
dependabot[bot]
a0fa1e84fc Bump ccxt from 1.41.90 to 1.42.19
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.41.90 to 1.42.19.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.41.90...1.42.19)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 19:06:36 +00:00
Matthias
c71ecd3680 Fix wrong pair-content in strategy-analysis notebook and documentation
closes #4399
2021-02-22 20:04:36 +01:00
Matthias
2b5f1ff256 Merge pull request #4426 from freqtrade/fix/4405
Don't fail API calls when live price is not available
2021-02-22 14:09:20 +01:00
Matthias
228e51b60b Fix #4405 2021-02-22 13:34:52 +01:00
Matthias
5e4730b73b Add test confirming #4405 2021-02-22 11:44:39 +01:00
Matthias
62885166a9 Merge pull request #4424 from freqtrade/dependabot/docker/python-3.9.2-slim-buster
Bump python from 3.9.1-slim-buster to 3.9.2-slim-buster
2021-02-22 08:43:54 +01:00
Matthias
21933a55f7 Merge pull request #4423 from freqtrade/dependabot/pip/develop/cryptography-3.4.6
Bump cryptography from 3.4.5 to 3.4.6
2021-02-22 08:23:19 +01:00
Matthias
8a62bfa0e5 armhf image should not be updated to python3.9 2021-02-22 08:20:45 +01:00
Matthias
8ffeafd2c3 Merge pull request #4422 from freqtrade/dependabot/pip/develop/scipy-1.6.1
Bump scipy from 1.6.0 to 1.6.1
2021-02-22 08:19:12 +01:00
Matthias
e34d8cba0e Merge pull request #4421 from freqtrade/dependabot/pip/develop/uvicorn-0.13.4
Bump uvicorn from 0.13.3 to 0.13.4
2021-02-22 08:02:16 +01:00
dependabot[bot]
d8c7e5ce8d Bump python from 3.9.1-slim-buster to 3.9.2-slim-buster
Bumps python from 3.9.1-slim-buster to 3.9.2-slim-buster.

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 05:56:25 +00:00
Matthias
6feabd51a2 Merge pull request #4418 from freqtrade/dependabot/pip/develop/python-telegram-bot-13.3
Bump python-telegram-bot from 13.2 to 13.3
2021-02-22 06:48:25 +01:00
Matthias
d7cc86735b Merge pull request #4417 from freqtrade/dependabot/pip/develop/tabulate-0.8.8
Bump tabulate from 0.8.7 to 0.8.8
2021-02-22 06:47:57 +01:00
dependabot[bot]
85f12f8c28 Bump cryptography from 3.4.5 to 3.4.6
Bumps [cryptography](https://github.com/pyca/cryptography) from 3.4.5 to 3.4.6.
- [Release notes](https://github.com/pyca/cryptography/releases)
- [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pyca/cryptography/compare/3.4.5...3.4.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 05:27:57 +00:00
dependabot[bot]
dea04c6452 Bump scipy from 1.6.0 to 1.6.1
Bumps [scipy](https://github.com/scipy/scipy) from 1.6.0 to 1.6.1.
- [Release notes](https://github.com/scipy/scipy/releases)
- [Commits](https://github.com/scipy/scipy/compare/v1.6.0...v1.6.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 05:27:54 +00:00
dependabot[bot]
932aabd012 Bump uvicorn from 0.13.3 to 0.13.4
Bumps [uvicorn](https://github.com/encode/uvicorn) from 0.13.3 to 0.13.4.
- [Release notes](https://github.com/encode/uvicorn/releases)
- [Changelog](https://github.com/encode/uvicorn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/encode/uvicorn/compare/0.13.3...0.13.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 05:27:51 +00:00
dependabot[bot]
8c398acc09 Bump python-telegram-bot from 13.2 to 13.3
Bumps [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) from 13.2 to 13.3.
- [Release notes](https://github.com/python-telegram-bot/python-telegram-bot/releases)
- [Changelog](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-telegram-bot/python-telegram-bot/compare/v13.2...v13.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 05:27:42 +00:00
dependabot[bot]
ab74c6e771 Bump tabulate from 0.8.7 to 0.8.8
Bumps [tabulate](https://github.com/astanin/python-tabulate) from 0.8.7 to 0.8.8.
- [Release notes](https://github.com/astanin/python-tabulate/releases)
- [Changelog](https://github.com/astanin/python-tabulate/blob/master/CHANGELOG)
- [Commits](https://github.com/astanin/python-tabulate/compare/v0.8.7...v0.8.8)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-22 05:27:41 +00:00
Matthias
95fcb1eb27 Merge pull request #4415 from The-smooth-operator/develop
Fix example in storing-information docs
2021-02-21 19:34:11 +01:00
Alberto del Barrio
188d7aaf8c Fix example in storing-information docs 2021-02-21 18:50:11 +01:00
Matthias
3629892fc3 Stoploss-guard should use the trade_limit or more
fix #4404
2021-02-20 19:38:44 +01:00
Matthias
245e39e523 dry-run should be a bool, not a string 2021-02-20 19:17:26 +01:00
Matthias
4e5f8478b1 Merge pull request #4394 from JoeSchr/develop
fix(doc/plotting): misplaced comma in example code
2021-02-18 17:43:53 +01:00
JoeSchr
c9688f1c89 fix(doc/plotting): misplaced comma in example code 2021-02-18 17:30:29 +01:00
Matthias
2b0d2070d0 Avoid crash with /delete
When a trade is deleted between querying the database and actually
handling the trade.

closes #4326
2021-02-18 12:49:14 +01:00
Matthias
327c23618f Improve documentation for get_analyzed_dataframe 2021-02-18 09:30:35 +01:00
Matthias
b5a9ce2894 Download data in the right format as well ...
closes #4393
2021-02-18 09:26:35 +01:00
Matthias
87dc1d3955 Explicitly push tag and tag_plot images 2021-02-17 20:52:25 +01:00
Matthias
fedbb5c0c4 Remove last flask occurance from setup.py
fixes #4390
2021-02-17 20:47:11 +01:00
Matthias
11b20d6932 Add config to hyperopt_loss_function documentation 2021-02-17 07:04:29 +01:00
Matthias
eff0d46ea1 Merge pull request #4375 from flomerz/pass_processed_data
pass data and config to loss function
2021-02-16 20:06:50 +01:00
Matthias
009a447d8a Adjust documentation for new parameter in loss functions 2021-02-16 19:51:09 +01:00
Florian Merz
3e06cd8b3a pass data and config to loss function 2021-02-16 10:11:33 +01:00
Matthias
a97a5a7ca8 Merge pull request #4372 from freqtrade/dependabot/pip/develop/cryptography-3.4.5
Bump cryptography from 3.3.2 to 3.4.5
2021-02-15 14:24:37 +01:00
dependabot[bot]
bc188907b8 Bump cryptography from 3.3.2 to 3.4.5
Bumps [cryptography](https://github.com/pyca/cryptography) from 3.3.2 to 3.4.5.
- [Release notes](https://github.com/pyca/cryptography/releases)
- [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pyca/cryptography/compare/3.3.2...3.4.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-15 08:46:46 +00:00
Matthias
eab1d298bc Merge pull request #4374 from freqtrade/dependabot/pip/develop/ccxt-1.41.90
Bump ccxt from 1.41.70 to 1.41.90
2021-02-15 09:45:44 +01:00
dependabot[bot]
5f25139348 Bump ccxt from 1.41.70 to 1.41.90
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.41.70 to 1.41.90.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.41.70...1.41.90)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-15 08:18:04 +00:00
Matthias
1a3e7191ed Merge pull request #4116 from squat0001/develop-squat
Develop squat
2021-02-15 07:15:11 +01:00
Matthias
833e2768e6 Merge pull request #4371 from freqtrade/dependabot/pip/develop/prompt-toolkit-3.0.16
Bump prompt-toolkit from 3.0.14 to 3.0.16
2021-02-15 06:59:37 +01:00
Matthias
86fdc3016c Merge pull request #4369 from freqtrade/dependabot/pip/develop/joblib-1.0.1
Bump joblib from 1.0.0 to 1.0.1
2021-02-15 06:46:49 +01:00
Matthias
4503fd0790 Merge pull request #4370 from freqtrade/dependabot/pip/develop/pandas-1.2.2
Bump pandas from 1.2.1 to 1.2.2
2021-02-15 06:45:29 +01:00
dependabot[bot]
dbef5425c5 Bump prompt-toolkit from 3.0.14 to 3.0.16
Bumps [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) from 3.0.14 to 3.0.16.
- [Release notes](https://github.com/prompt-toolkit/python-prompt-toolkit/releases)
- [Changelog](https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/CHANGELOG)
- [Commits](https://github.com/prompt-toolkit/python-prompt-toolkit/compare/3.0.14...3.0.16)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-15 05:27:12 +00:00
dependabot[bot]
d08572ea0d Bump pandas from 1.2.1 to 1.2.2
Bumps [pandas](https://github.com/pandas-dev/pandas) from 1.2.1 to 1.2.2.
- [Release notes](https://github.com/pandas-dev/pandas/releases)
- [Changelog](https://github.com/pandas-dev/pandas/blob/master/RELEASE.md)
- [Commits](https://github.com/pandas-dev/pandas/compare/v1.2.1...v1.2.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-15 05:27:05 +00:00
dependabot[bot]
44cb206688 Bump joblib from 1.0.0 to 1.0.1
Bumps [joblib](https://github.com/joblib/joblib) from 1.0.0 to 1.0.1.
- [Release notes](https://github.com/joblib/joblib/releases)
- [Changelog](https://github.com/joblib/joblib/blob/master/CHANGES.rst)
- [Commits](https://github.com/joblib/joblib/compare/1.0.0...1.0.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-15 05:27:01 +00:00
Matthias
1a166f639d Add test for calcuate_csum 2021-02-14 19:44:13 +01:00
Florian Reitmeir
5c263c7ffd add backtesting results abs profit min/abs profit max, to get a better view if a strategy has a enough money to succeed 2021-02-14 19:41:12 +01:00
Matthias
f82dd55153 Merge pull request #4367 from freqtrade/fix/4181
ohlcv_candle_limit per timeframe
2021-02-14 19:32:05 +01:00
Matthias
ee74bc1f52 timeframe is mandatory, no need to use .get() 2021-02-14 11:01:12 +01:00
Matthias
ffca09bbcb Test ohlcv_candle_limit explicitly 2021-02-14 10:38:49 +01:00
Matthias
da89838b5c Set bittrex limits as returned by the exchange
closes #4181
2021-02-14 10:32:55 +01:00
Matthias
5622bb3247 Make candle_limit optionally timeframe dependent 2021-02-14 10:29:45 +01:00
Matthias
7ecf8f8b80 Cleanup candle_limit usage 2021-02-14 10:08:05 +01:00
Matthias
10a11bda34 Document bitvavo as community tested
closes #4360
2021-02-14 09:42:25 +01:00
Matthias
6f77ec063e Fix cookieError on python<3.8
Only occurs in combination with api-server enabled,
due to some hot-fixing starlette does.
Since we load starlette at a later point, we need to replicate
starlette's behaviour for now, so sameSite cookies don't create a
problem.

closes #4356
2021-02-14 07:22:08 +01:00
Matthias
73d91275c4 Reset sell_order_status if a new sell-order is placed
closes #4365
2021-02-14 07:11:07 +01:00
Matthias
4b5f4aa1c1 Merge pull request #4361 from freqtrade/format_currencies
Format currencies
2021-02-13 19:23:23 +01:00
Matthias
d4c8be915c Use fstring where possible 2021-02-13 16:11:49 +01:00
Matthias
e7acee7904 Improve coin value output by rounding coin specific 2021-02-13 16:05:56 +01:00
Matthias
072abde9b7 Introduce round_coin_value to simplify coin rounding 2021-02-13 16:05:35 +01:00
Matthias
dd23f6bcbc Fix type for getting pairs 2021-02-11 20:29:31 +01:00
Matthias
843fb204e9 Fix problem with inf values returned from dataframe for api methods 2021-02-11 20:21:31 +01:00
Matthias
aa79574c0c Position-size should NEVER be over available_capital
Part of #4353
2021-02-11 17:09:31 +01:00
Matthias
3110d2dbb1 Add small test cases 2021-02-09 20:09:10 +01:00
Matthias
86fa75b286 Pin version of cryptography 2021-02-09 06:55:36 +01:00
Matthias
7ee149da5d Improve plotting errorhandling
closes #4327
2021-02-08 20:08:32 +01:00
Matthias
427d762746 Improve tests for cancel_order to be more realistic 2021-02-08 19:37:24 +01:00
Matthias
c5ab3a80a5 Check if order is a dict before parsing
closes #4331
2021-02-08 19:35:22 +01:00
Matthias
de727645ab FIx random test failure if certain files exist 2021-02-08 19:21:33 +01:00
Matthias
afaac92685 Merge pull request #4337 from freqtrade/dependabot/pip/develop/python-telegram-bot-13.2
Bump python-telegram-bot from 13.1 to 13.2
2021-02-08 09:46:10 +01:00
Matthias
48e203f6a4 Merge pull request #4338 from freqtrade/dependabot/pip/develop/ccxt-1.41.70
Bump ccxt from 1.41.62 to 1.41.70
2021-02-08 09:45:49 +01:00
Matthias
f999366bf5 Merge pull request #4333 from freqtrade/dependabot/pip/develop/py-find-1st-1.1.5
Bump py-find-1st from 1.1.4 to 1.1.5
2021-02-08 09:45:20 +01:00
dependabot[bot]
c412f8df62 Bump python-telegram-bot from 13.1 to 13.2
Bumps [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) from 13.1 to 13.2.
- [Release notes](https://github.com/python-telegram-bot/python-telegram-bot/releases)
- [Changelog](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-telegram-bot/python-telegram-bot/compare/v13.1...v13.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-08 08:28:11 +00:00
dependabot[bot]
12168cbf01 Bump ccxt from 1.41.62 to 1.41.70
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.41.62 to 1.41.70.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.41.62...1.41.70)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-08 08:26:18 +00:00
Matthias
0850145b3d Merge pull request #4334 from freqtrade/dependabot/pip/develop/numpy-1.20.1
Bump numpy from 1.20.0 to 1.20.1
2021-02-08 08:22:30 +01:00
Matthias
9821d3a554 Merge pull request #4335 from freqtrade/dependabot/pip/develop/sqlalchemy-1.3.23
Bump sqlalchemy from 1.3.22 to 1.3.23
2021-02-08 08:21:46 +01:00
Matthias
d681565756 Merge pull request #4336 from freqtrade/dependabot/pip/develop/mkdocs-material-6.2.8
Bump mkdocs-material from 6.2.7 to 6.2.8
2021-02-08 08:21:22 +01:00
dependabot[bot]
22d447b3f5 Bump mkdocs-material from 6.2.7 to 6.2.8
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 6.2.7 to 6.2.8.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/6.2.7...6.2.8)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-08 05:27:46 +00:00
dependabot[bot]
676cd7bb55 Bump sqlalchemy from 1.3.22 to 1.3.23
Bumps [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) from 1.3.22 to 1.3.23.
- [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases)
- [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/master/CHANGES)
- [Commits](https://github.com/sqlalchemy/sqlalchemy/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-08 05:27:45 +00:00
dependabot[bot]
dd7f9181c5 Bump numpy from 1.20.0 to 1.20.1
Bumps [numpy](https://github.com/numpy/numpy) from 1.20.0 to 1.20.1.
- [Release notes](https://github.com/numpy/numpy/releases)
- [Changelog](https://github.com/numpy/numpy/blob/master/doc/HOWTO_RELEASE.rst.txt)
- [Commits](https://github.com/numpy/numpy/compare/v1.20.0...v1.20.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-08 05:27:44 +00:00
dependabot[bot]
d1bb46bed0 Bump py-find-1st from 1.1.4 to 1.1.5
Bumps [py-find-1st](https://github.com/roebel/py_find_1st) from 1.1.4 to 1.1.5.
- [Release notes](https://github.com/roebel/py_find_1st/releases)
- [Commits](https://github.com/roebel/py_find_1st/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-08 05:27:42 +00:00
Matthias
f6cdc6d9a2 Merge pull request #4325 from freqtrade/refresh_order_skip
Refresh order skip
2021-02-07 08:23:22 +01:00
Matthias
4cb67f140a Merge pull request #4323 from eselskas/patch-2
Fix sample strategy documentation link
2021-02-06 20:17:20 +01:00
Edvinas Selskas
694f55c0a5 Use suggested link 2021-02-06 14:43:50 +00:00
Matthias
d5cf837c0f Parse regular cancel_order call to update orders table 2021-02-06 09:23:10 +01:00
Matthias
729e773353 Merge pull request #4319 from JoeSchr/patch-2
Update data-download.md
2021-02-06 09:11:49 +01:00
Edvinas Selskas
bc8fda8d63 Update sample_strategy.py
Fix test
2021-02-06 03:13:53 +00:00
Edvinas Selskas
0a43988f3f Fix sample strategy documentation link
Noticed that the current link is dead. I think this would be the most appropriate link in this case.
2021-02-06 03:02:37 +00:00
Matthias
aec22c5c3d introduce skip_open_order_update parameter
skips startup-open-order-update
closes #4128
2021-02-05 20:17:53 +01:00
Matthias
86a97988c0 Improve wording 2021-02-05 20:09:13 +01:00
Matthias
0806202d47 ccxt version bump to 1.41.62 2021-02-05 20:02:55 +01:00
Matthias
2c71b3b118 Merge pull request #4309 from freqtrade/extract_stake_amount
Move get_trade_stake_amount to wallets
2021-02-05 19:47:30 +01:00
Matthias
545a94f360 Merge pull request #4321 from JoeSchr/fix/lint-binance-example-config
chore(lint): lint binance example config
2021-02-05 14:58:24 +01:00
Joe Schr
a816fb1245 chore(lint): lint binance example config 2021-02-05 12:43:19 +01:00
Matthias
1310a7b547 Fix bug with wrong conversion for BTCST/BTC
This can happen if a pair starts with the stake-currency

closes #4307
2021-02-04 19:58:44 +01:00
Matthias
17e1cfbd43 Merge pull request #4313 from raoulbuzziol/develop
setting resize_keyboard=True for slightly smaller Telegram buttons
2021-02-04 19:42:45 +01:00
JoeSchr
428d2af312 add sudo to chown
that was the whole point d'oh
2021-02-04 19:39:25 +01:00
JoeSchr
5165357f40 Update data-download.md
Fix wrong path
Add section about fixing wrong docker permission, if user_data is created by docker, it's permission are set to `root`
2021-02-04 19:36:04 +01:00
Matthias
19e43e2e9d Merge pull request #4314 from JoeSchr/patch-1
Update README.md
2021-02-04 17:34:23 +01:00
JoeSchr
5cd8745997 Update README.md
Typo playing -> paying
2021-02-04 16:26:03 +01:00
raoulus
99b2214d1f setting resize_keyboard=True for slightly smaller Telegram buttons 2021-02-04 15:27:18 +01:00
Matthias
e8e5acc2e2 Fix import in strategy template 2021-02-03 20:15:08 +01:00
Matthias
024849d844 Merge pull request #4285 from freqtrade/ui_deploy
Deploy FreqUI into webserver
2021-02-03 20:09:31 +01:00
Matthias
b8cb39462c Move get_trade_stake_amount to wallets
this way it can be easier used by other functions
2021-02-03 20:00:33 +01:00
Matthias
6c87c49871 Merge pull request #4306 from The-smooth-operator/docs
Fix documentation links pointing to pairlists
2021-02-03 19:30:20 +01:00
Alberto del Barrio
f36c61e32f Fix documentation links pointing to pairlists 2021-02-03 18:12:48 +01:00
Matthias
caa3e1a7fa Merge pull request #4301 from freqtrade/doc_reorg
Doc reorg
2021-02-03 12:02:05 +01:00
Matthias
de72734076 Merge pull request #4302 from mobrine1/patch-1
#4289 printing json output
2021-02-03 10:13:44 +01:00
mobrine1
06b56544a8 printing json by default now 2021-02-03 03:27:54 -05:00
mobrine1
56569690d9 Update rest_client.py 2021-02-02 15:59:48 -05:00
mobrine1
12bcbf4374 #4289 printing json output
Adding --json flag to print json output
2021-02-02 15:40:33 -05:00
Matthias
cd41d11b85 Merge pull request #4300 from freqtrade/extract_get_min_stake_amount
Extract min stake amount from bot to exchange class
2021-02-02 20:28:35 +01:00
Matthias
43986d3f73 Move Pricing to subpage 2021-02-02 20:26:01 +01:00
Matthias
b41078cc46 Don't include plugin documentation in Configuration page 2021-02-02 20:23:30 +01:00
Matthias
dabe456d65 Improve wording of configuration doc
remove unneeded sections
2021-02-02 20:20:34 +01:00
Matthias
3e3c9e99c7 Move command references to their respective subpages 2021-02-02 20:03:28 +01:00
Matthias
f0532f28cf Small doc-reorg adding "advanced topics" as main header 2021-02-02 20:03:01 +01:00
Matthias
cfd0bb8964 Extract min stake amount from bot to exchange class 2021-02-02 19:47:21 +01:00
Matthias
fa8156b321 Merge pull request #4282 from pan-long/patch-1
Fix a bug when compare sell_profit_offset
2021-02-02 08:22:38 +01:00
Matthias
3d9b4034e6 Use already calculated current_profit for sell_profit_offset comparison 2021-02-02 08:06:19 +01:00
Matthias
a69fde39e5 Merge pull request #4296 from freqtrade/fix/pairlistbug
Fix disappearing pairs pairlist bug
2021-02-01 20:02:50 +01:00
Matthias
a9f1c871dd Add path loading snippet to derived strategies
closes #4279
2021-02-01 19:48:29 +01:00
Matthias
52acf9aaf6 Fix "disappearing pairs" bug
closes #4277
2021-02-01 19:40:31 +01:00
Matthias
130a9b4db3 Add test to call verify_pairlist multiple times 2021-02-01 19:39:55 +01:00
Matthias
55c9489eb2 Downgrade RPI docker-image to 3.7
otherwise piwheels.org does not work at the moment
2021-02-01 15:11:04 +01:00
Matthias
cd5c58fd37 Properly patch exchange for plot_profit test 2021-02-01 12:58:18 +01:00
Matthias
b33534b8f5 Merge pull request #4290 from freqtrade/dependabot/pip/develop/urllib3-1.26.3
Bump urllib3 from 1.26.2 to 1.26.3
2021-02-01 11:01:45 +01:00
Matthias
4facf662de Fix random test-failure caused by un-clean hyperopt shutdown
pytest --random-order-seed=415781
2021-02-01 11:00:55 +01:00
Matthias
fd5468f9cc Merge pull request #4292 from freqtrade/dependabot/pip/develop/pymdown-extensions-8.1.1
Bump pymdown-extensions from 8.1 to 8.1.1
2021-02-01 10:52:47 +01:00
dependabot[bot]
ccdac3d4c3 Bump urllib3 from 1.26.2 to 1.26.3
Bumps [urllib3](https://github.com/urllib3/urllib3) from 1.26.2 to 1.26.3.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/1.26.3/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/1.26.2...1.26.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 08:50:24 +00:00
dependabot[bot]
7fcf0d5231 Bump pymdown-extensions from 8.1 to 8.1.1
Bumps [pymdown-extensions](https://github.com/facelessuser/pymdown-extensions) from 8.1 to 8.1.1.
- [Release notes](https://github.com/facelessuser/pymdown-extensions/releases)
- [Commits](https://github.com/facelessuser/pymdown-extensions/compare/8.1...8.1.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 08:45:31 +00:00
Matthias
dc55c79e41 Merge pull request #4286 from freqtrade/dataload_valueerror
Fix valueerror in case of empty array files
2021-02-01 07:52:05 +01:00
Matthias
ed2ae65ffb Merge pull request #4293 from freqtrade/dependabot/pip/develop/jinja2-2.11.3
Bump jinja2 from 2.11.2 to 2.11.3
2021-02-01 07:48:22 +01:00
Matthias
8e1f3a5196 Merge pull request #4291 from freqtrade/dependabot/pip/develop/pytest-6.2.2
Bump pytest from 6.2.1 to 6.2.2
2021-02-01 07:47:40 +01:00
Matthias
382cd9eaaf Merge pull request #4295 from freqtrade/dependabot/pip/develop/mkdocs-material-6.2.7
Bump mkdocs-material from 6.2.5 to 6.2.7
2021-02-01 07:47:23 +01:00
Matthias
8cf8ef98c4 Merge pull request #4294 from freqtrade/dependabot/pip/develop/ccxt-1.41.35
Bump ccxt from 1.40.99 to 1.41.35
2021-02-01 07:47:06 +01:00
dependabot[bot]
2a5e0920ec Bump mkdocs-material from 6.2.5 to 6.2.7
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 6.2.5 to 6.2.7.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/6.2.5...6.2.7)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 05:42:08 +00:00
dependabot[bot]
aa7120f27c Bump ccxt from 1.40.99 to 1.41.35
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.40.99 to 1.41.35.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.40.99...1.41.35)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 05:42:06 +00:00
dependabot[bot]
ed1d4f0568 Bump jinja2 from 2.11.2 to 2.11.3
Bumps [jinja2](https://github.com/pallets/jinja) from 2.11.2 to 2.11.3.
- [Release notes](https://github.com/pallets/jinja/releases)
- [Changelog](https://github.com/pallets/jinja/blob/master/CHANGES.rst)
- [Commits](https://github.com/pallets/jinja/compare/2.11.2...2.11.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 05:42:05 +00:00
dependabot[bot]
76312d722a Bump pytest from 6.2.1 to 6.2.2
Bumps [pytest](https://github.com/pytest-dev/pytest) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/6.2.1...6.2.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 05:41:53 +00:00
Matthias
2c80388b40 Fix valueerror in case of empty array files 2021-02-01 06:28:49 +01:00
Matthias
06e2bc94c3 Deploy to subdirectory 2021-01-31 16:01:00 +01:00
Matthias
e4a085027b Add test for UI methods 2021-01-31 15:27:00 +01:00
Matthias
28be71806f Install html file as well 2021-01-31 15:13:51 +01:00
Matthias
a87a885ccd Don't use Path object to return fileresponses 2021-01-31 14:54:58 +01:00
Matthias
7b3d99819f Fix bug with not cleaning UI folder 2021-01-31 14:50:54 +01:00
Matthias
944d674eeb Store freqUI version and read it again 2021-01-31 14:50:54 +01:00
Matthias
2af1d2d639 Extract last FreqUI version from api response 2021-01-31 14:50:54 +01:00
Matthias
1df0aa8751 Add ui installation to docker container builds 2021-01-31 14:50:54 +01:00
Matthias
35c2e2556e Document FreqUI usage 2021-01-31 14:50:54 +01:00
Matthias
e928d2991d Add fallback file 2021-01-31 14:50:54 +01:00
Matthias
f05f2c45e8 Allow deleting of UI only 2021-01-31 14:50:54 +01:00
Matthias
ddc99553bd Add test case for get_ui_download_url 2021-01-31 14:50:54 +01:00
Matthias
a1a35115ad Extract get_ui_download_url 2021-01-31 14:50:54 +01:00
Matthias
87ed2d7502 Write some tests for UI Downloading 2021-01-31 14:50:54 +01:00
Matthias
a47616eed4 Add UI installation subcommand 2021-01-31 14:50:54 +01:00
Matthias
27970b424d Add webUI serving to api-server 2021-01-31 14:50:54 +01:00
Matthias
79087ba166 Fix intermitted test failure 2021-01-31 14:50:39 +01:00
Matthias
f288ed1f36 Merge pull request #4284 from freqtrade/windows_ci_error
Version bump numpy 1.20.0
2021-01-31 13:59:36 +01:00
Matthias
5724371a4f Fix types for numpy 1.20.0 upgrade 2021-01-31 11:21:23 +01:00
Matthias
92721db583 Version bump numpy to 1.20.0 2021-01-31 10:51:21 +01:00
Matthias
bc586fe73b Try fix CI 2021-01-31 10:29:43 +01:00
Pan Long
4cc93151c5 Fix a bug when compare sell_profit_offset
It should be comparing the ratio instead of absolut profit.

Also updated the comment.
2021-01-31 12:14:09 +08:00
Matthias
16dad8b6d4 Allow custom_stoploss to cooperate with stoploss on exchange 2021-01-30 20:11:18 +01:00
Matthias
30e5c01cb1 Improve formatting of custom_stoploss docs 2021-01-30 19:59:14 +01:00
Matthias
afdb39d78f Merge pull request #4280 from andre-ac/develop
Fixed virtualenv link
2021-01-30 19:20:13 +01:00
andre-ac
6b63129eb0 Fixed virtualenv link 2021-01-30 15:36:59 +00:00
Matthias
406682c3bb Fix random api failure in slow cases 2021-01-30 10:20:40 +01:00
Matthias
b68ed458b8 Merge pull request #4067 from freqtrade/dependabot/docker/python-3.9.1-slim-buster
Bump python from 3.8.6-slim-buster to 3.9.1-slim-buster
2021-01-30 10:13:32 +01:00
Matthias
5d18289821 Fix name in issue template 2021-01-30 07:17:25 +01:00
Matthias
375f551e5d Merge pull request #4218 from sobeit2020/develop
Conda - installation process : adding and explaining
2021-01-29 20:01:07 +01:00
Matthias
1e6194fa30 Improve wording, fix hirerchial hierarchy 2021-01-29 19:46:45 +01:00
Matthias
d8353bc90e Merge branch 'develop' into pr/sobeit2020/4218 2021-01-29 19:11:19 +01:00
Matthias
ea0ffbae73 use profit_ratio in calculate_cum_profit 2021-01-29 19:06:57 +01:00
Matthias
ad9efd3ac5 Merge pull request #4275 from freqtrade/markets_ref
Cache markets in the exchange object
2021-01-29 16:57:57 +01:00
sobeit2020
b12d0b110e Update installation.md 2021-01-28 23:09:39 +00:00
Matthias
5cdd9dd445 Cache markets in the exchange object 2021-01-28 19:47:32 +01:00
dependabot[bot]
4bb2a00f03 Bump python from 3.8.6-slim-buster to 3.9.1-slim-buster
Bumps python from 3.8.6-slim-buster to 3.9.1-slim-buster.

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-27 18:12:56 +00:00
Matthias
65459086a3 Merge pull request #4268 from freqtrade/backtest_trade_object
Backtest trade object
2021-01-27 19:10:21 +01:00
Matthias
766c786d90 Merge pull request #4273 from freqtrade/new_release
New release 2021.1
2021-01-27 19:02:52 +01:00
sobeit2020
d1d77f56df Update installation.md 2021-01-27 13:38:59 +00:00
sobeit2020
a414d5d75a Update installation.md 2021-01-27 13:25:16 +00:00
sobeit2020
ec2cf7f979 Update installation.md 2021-01-27 13:23:53 +00:00
sobeit2020
5da8a3078b Update installation.md 2021-01-27 13:04:04 +00:00
Matthias
eac98dbbd6 Version bump to 2021.1 2021-01-27 07:29:40 +01:00
Matthias
a9b4d6de33 Check for existance of ask key in ticker
closes #4267
2021-01-26 17:18:55 +01:00
Matthias
4d7f3e570b Add test for spreadfilter division exception 2021-01-26 17:18:51 +01:00
Matthias
5ab8cc56a4 Update docs to also work for postgres 2021-01-26 08:13:43 +01:00
Matthias
9005cd25b8 Merge pull request #4256 from thopd88/patch-2
Fix operator does not exist: boolean = integer
2021-01-26 07:21:39 +01:00
Tho Pham (Alex)
8f529f48da Update freqtrade/freqtradebot.py use is_open.is_(True)
Co-authored-by: Matthias <xmatthias@outlook.com>
2021-01-26 07:38:25 +07:00
sobeit2020
188010329c Update installation.md 2021-01-25 21:22:43 +00:00
sobeit2020
bcc7adb186 Update installation.md 2021-01-25 21:18:38 +00:00
sobeit2020
d848242379 Update installation.md 2021-01-25 21:12:48 +00:00
sobeit2020
39cef2dbe0 Update environment.yml 2021-01-25 20:45:35 +00:00
sobeit2020
4a28fab8a1 Update installation.md 2021-01-25 20:41:55 +00:00
Matthias
91b6c02947 Update download-data --dl-trades sample command 2021-01-25 20:57:05 +01:00
sobeit2020
65e0ba60dc Update installation.md 2021-01-25 19:51:01 +00:00
Matthias
13ad6dd461 Fix documentation 2021-01-25 19:56:40 +01:00
Matthias
c659150d9f Also print trade_duration in seconds to json 2021-01-25 19:42:34 +01:00
Matthias
3a83492999 Merge pull request #4265 from freqtrade/dependabot/pip/develop/ccxt-1.40.99
Bump ccxt from 1.40.74 to 1.40.99
2021-01-25 10:11:56 +01:00
dependabot[bot]
f98bd40955 Bump ccxt from 1.40.74 to 1.40.99
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.40.74 to 1.40.99.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.40.74...1.40.99)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 08:24:17 +00:00
Matthias
6fc165c133 Merge pull request #4264 from freqtrade/dependabot/pip/develop/scikit-learn-0.24.1
Bump scikit-learn from 0.24.0 to 0.24.1
2021-01-25 08:23:57 +01:00
Matthias
d10e00b61b Merge pull request #4262 from freqtrade/dependabot/pip/develop/prompt-toolkit-3.0.14
Bump prompt-toolkit from 3.0.10 to 3.0.14
2021-01-25 08:23:30 +01:00
Matthias
c0df15af29 Merge pull request #4257 from freqtrade/dependabot/pip/develop/cachetools-4.2.1
Bump cachetools from 4.2.0 to 4.2.1
2021-01-25 08:22:46 +01:00
Matthias
9b8148356e Merge pull request #4261 from freqtrade/dependabot/pip/develop/pandas-1.2.1
Bump pandas from 1.2.0 to 1.2.1
2021-01-25 08:22:12 +01:00
Matthias
04058b1a33 Merge pull request #4258 from freqtrade/dependabot/pip/develop/blosc-1.10.2
Bump blosc from 1.10.1 to 1.10.2
2021-01-25 08:04:27 +01:00
Matthias
1314e75bc6 Merge pull request #4259 from freqtrade/dependabot/pip/develop/pytest-cov-2.11.1
Bump pytest-cov from 2.10.1 to 2.11.1
2021-01-25 08:03:24 +01:00
dependabot[bot]
cb749b578d Bump scikit-learn from 0.24.0 to 0.24.1
Bumps [scikit-learn](https://github.com/scikit-learn/scikit-learn) from 0.24.0 to 0.24.1.
- [Release notes](https://github.com/scikit-learn/scikit-learn/releases)
- [Commits](https://github.com/scikit-learn/scikit-learn/compare/0.24.0...0.24.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:37:51 +00:00
dependabot[bot]
fb99cf1459 Bump prompt-toolkit from 3.0.10 to 3.0.14
Bumps [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) from 3.0.10 to 3.0.14.
- [Release notes](https://github.com/prompt-toolkit/python-prompt-toolkit/releases)
- [Changelog](https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/CHANGELOG)
- [Commits](https://github.com/prompt-toolkit/python-prompt-toolkit/compare/3.0.10...3.0.14)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:37:50 +00:00
dependabot[bot]
d4e9037e6e Bump pandas from 1.2.0 to 1.2.1
Bumps [pandas](https://github.com/pandas-dev/pandas) from 1.2.0 to 1.2.1.
- [Release notes](https://github.com/pandas-dev/pandas/releases)
- [Changelog](https://github.com/pandas-dev/pandas/blob/master/RELEASE.md)
- [Commits](https://github.com/pandas-dev/pandas/compare/v1.2.0...v1.2.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:37:49 +00:00
dependabot[bot]
afdcd2c0af Bump pytest-cov from 2.10.1 to 2.11.1
Bumps [pytest-cov](https://github.com/pytest-dev/pytest-cov) from 2.10.1 to 2.11.1.
- [Release notes](https://github.com/pytest-dev/pytest-cov/releases)
- [Changelog](https://github.com/pytest-dev/pytest-cov/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest-cov/compare/v2.10.1...v2.11.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:37:42 +00:00
dependabot[bot]
9422062cbd Bump blosc from 1.10.1 to 1.10.2
Bumps [blosc](https://github.com/blosc/python-blosc) from 1.10.1 to 1.10.2.
- [Release notes](https://github.com/blosc/python-blosc/releases)
- [Changelog](https://github.com/Blosc/python-blosc/blob/master/RELEASE_NOTES.rst)
- [Commits](https://github.com/blosc/python-blosc/compare/v1.10.1...v1.10.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:37:25 +00:00
dependabot[bot]
b976baae3f Bump cachetools from 4.2.0 to 4.2.1
Bumps [cachetools](https://github.com/tkem/cachetools) from 4.2.0 to 4.2.1.
- [Release notes](https://github.com/tkem/cachetools/releases)
- [Changelog](https://github.com/tkem/cachetools/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/tkem/cachetools/compare/v4.2.0...v4.2.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:37:16 +00:00
Tho Pham (Alex)
c22cccb55b Fix operator does not exist: boolean = integer 2021-01-25 12:24:47 +07:00
sobeit2020
2226f6781f Update installation.md 2021-01-24 21:31:36 +00:00
Matthias
62e43539c9 Limit max_open_trades to maximum available pairs
closes #4008
2021-01-24 19:59:54 +01:00
Matthias
789a980a30 Fix tests for new export format 2021-01-24 19:42:32 +01:00
sobeit2020
2c2a33b2e8 updated environemnt.ylm 2021-01-24 17:06:40 +00:00
sobeit2020
9af89786ba update installation.md
ma
2021-01-24 17:03:56 +00:00
Matthias
deb8432d33 Streamline trade to dataframe conversion 2021-01-24 08:58:41 +01:00
Matthias
8ee264bc59 Don't use profit_percent for backtesting results anymore 2021-01-24 08:58:41 +01:00
Matthias
48977493bb Backtesting does not need to convert to BacktestResult object 2021-01-24 08:58:41 +01:00
Matthias
3b51545d23 Add trade_duration to to_json 2021-01-24 08:58:41 +01:00
Matthias
9a3c425cf4 Update slack link 2021-01-24 08:53:05 +01:00
Matthias
16f9675356 Fix whitelist expansion problem 2021-01-23 20:40:27 +01:00
Matthias
37acaa685b Merge pull request #4249 from freqtrade/config_rename
Config rename
2021-01-23 09:20:42 +01:00
Matthias
31e0b09643 Rename config.json.example
it's really the config dedicated to bittrex,
so the name should reflect this in beeing config_bittrex.json.example
2021-01-22 19:18:34 +01:00
Matthias
371b374ea6 Remove unused config setup from setup.sh 2021-01-22 19:12:34 +01:00
Matthias
bec9b580b0 sell_profit_offset should be documented in the strategy override section 2021-01-22 17:38:55 +01:00
Matthias
e94e2dd383 Remove docker config without compose 2021-01-22 17:32:57 +01:00
Matthias
c42241986e further investigate random test failure 2021-01-21 19:20:38 +01:00
Matthias
c998577d4a Merge pull request #4244 from dannoso/patch-1
Fixed quickstart link in docs
2021-01-21 19:12:47 +01:00
Davide
fd379d36ac Fixed quickstart link in docs 2021-01-21 12:27:22 +01:00
Matthias
5c0f98b518 Blacklist Poloniex - as ccxt does not provide a fetch_order endpoint 2021-01-20 19:31:17 +01:00
Matthias
06cae1b60c Merge pull request #4241 from tijmenvandenbrink/develop
Small improvement to MaxDrawDown protection
2021-01-20 14:16:08 +01:00
Matthias
5f5f75e147 Improve wording in protections documentation 2021-01-20 13:57:53 +01:00
Tijmen van den Brink
992d6b8018 Small improvement to MaxDrawDown protection 2021-01-20 09:24:30 +01:00
Matthias
7c80eeea95 Add use_custom_stoploss to optimize_report 2021-01-19 22:51:12 +01:00
Matthias
86b3306a3b Small doc refactoring 2021-01-19 22:07:10 +01:00
Matthias
7c99e6f0e6 Avoid random test failure 2021-01-19 20:49:28 +01:00
Matthias
20591b539a Merge pull request #4228 from baartch/develop
Extending the Telegram Bot command /status with the possibility to query specific trade_ids
2021-01-19 20:08:49 +01:00
Matthias
cd8d4da466 Add test for /status <tradeids> functionality 2021-01-19 19:45:13 +01:00
Andreas Brunner
a68a546dd9 _rpc_trade_status argument datatype optimizations 2021-01-18 15:26:53 +01:00
Matthias
c785bce7e6 Merge pull request #4234 from freqtrade/dependabot/pip/develop/pyjwt-2.0.1
Bump pyjwt from 2.0.0 to 2.0.1
2021-01-18 09:20:16 +01:00
Matthias
d05cbe239a Merge pull request #4231 from freqtrade/dependabot/pip/develop/coveralls-3.0.0
Bump coveralls from 2.2.0 to 3.0.0
2021-01-18 08:59:05 +01:00
Matthias
792c8503f9 Merge pull request #4233 from freqtrade/dependabot/pip/develop/mkdocs-material-6.2.5
Bump mkdocs-material from 6.2.4 to 6.2.5
2021-01-18 08:48:44 +01:00
Matthias
10104927c9 Fix devcontainer
closes #4230
2021-01-18 07:46:19 +00:00
Matthias
611dbdc522 Merge pull request #4235 from freqtrade/dependabot/pip/develop/ccxt-1.40.74
Bump ccxt from 1.40.30 to 1.40.74
2021-01-18 07:31:34 +01:00
Matthias
3386ca9999 Merge pull request #4232 from freqtrade/dependabot/pip/develop/plotly-4.14.3
Bump plotly from 4.14.1 to 4.14.3
2021-01-18 07:29:41 +01:00
dependabot[bot]
994b4013ad Bump ccxt from 1.40.30 to 1.40.74
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.40.30 to 1.40.74.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.40.30...1.40.74)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-18 05:38:06 +00:00
dependabot[bot]
8b5f8937cc Bump pyjwt from 2.0.0 to 2.0.1
Bumps [pyjwt](https://github.com/jpadilla/pyjwt) from 2.0.0 to 2.0.1.
- [Release notes](https://github.com/jpadilla/pyjwt/releases)
- [Changelog](https://github.com/jpadilla/pyjwt/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/jpadilla/pyjwt/compare/2.0.0...2.0.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-18 05:37:48 +00:00
dependabot[bot]
7f8dbce367 Bump mkdocs-material from 6.2.4 to 6.2.5
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 6.2.4 to 6.2.5.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/6.2.4...6.2.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-18 05:37:45 +00:00
dependabot[bot]
6a8e495102 Bump plotly from 4.14.1 to 4.14.3
Bumps [plotly](https://github.com/plotly/plotly.py) from 4.14.1 to 4.14.3.
- [Release notes](https://github.com/plotly/plotly.py/releases)
- [Changelog](https://github.com/plotly/plotly.py/blob/master/CHANGELOG.md)
- [Commits](https://github.com/plotly/plotly.py/compare/v4.14.1...v4.14.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-18 05:37:37 +00:00
dependabot[bot]
296a6bd43c Bump coveralls from 2.2.0 to 3.0.0
Bumps [coveralls](https://github.com/coveralls-clients/coveralls-python) from 2.2.0 to 3.0.0.
- [Release notes](https://github.com/coveralls-clients/coveralls-python/releases)
- [Changelog](https://github.com/TheKevJames/coveralls-python/blob/master/CHANGELOG.md)
- [Commits](https://github.com/coveralls-clients/coveralls-python/compare/2.2.0...3.0.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-18 05:37:29 +00:00
Andreas Brunner
eb95d970e9 flake8 beautify 2021-01-17 21:26:55 +01:00
Andreas Brunner
d21eff0d52 fix, if an non existing trade_id is provided 2021-01-17 21:21:31 +01:00
Andreas Brunner
3ea33d1737 updating doc and help with new /status argument 2021-01-17 21:15:17 +01:00
Andreas Brunner
6d40814dbf extend status bot command to query specific trades 2021-01-17 20:39:35 +01:00
Matthias
a8bae3a381 Don't update trade fees for dry-run orders 2021-01-17 20:31:27 +01:00
Matthias
389db2fe7d Enhance wording of docker quickstart 2021-01-17 19:11:00 +01:00
Matthias
3a2bac4ae3 Merge pull request #4223 from freqtrade/bot_name
Add bot_name setting
2021-01-17 15:23:41 +01:00
sobeit2020
172a629c58 Update installation.md 2021-01-16 22:41:37 +00:00
sobeit2020
f9dd74585e Update installation.md 2021-01-16 22:39:11 +00:00
sobeit2020
73206a9194 Update installation.md 2021-01-16 22:35:42 +00:00
sobeit2020
63be27f671 Update installation.md 2021-01-16 22:28:23 +00:00
sobeit2020
9ad0817105 Update installation.md 2021-01-16 22:27:25 +00:00
sobeit2020
a271c9e98e Update installation.md 2021-01-16 22:24:22 +00:00
Matthias
53c208197d Add bot_name setting
allows naming the bot to simply differentiate when running different
bots.
2021-01-16 16:19:49 +01:00
Matthias
572f5f9186 Fix fstring syntax error 2021-01-16 10:05:47 +01:00
Matthias
9f338ba6ed Debug random test failure in CI 2021-01-16 10:01:31 +01:00
Matthias
3fefb6f1c8 Merge pull request #4215 from freqtrade/refactor/backtest
Small backtest refactor, introduce calling `bot_loop_start` in backtesting
2021-01-16 09:32:19 +01:00
Matthias
d74376726a api-server should fully support max_open_trades=-1 2021-01-15 20:47:12 +01:00
Matthias
baef8b4f79 Merge pull request #4197 from nas-/develop
Added support for regex in whitelist
2021-01-15 07:34:49 +01:00
Matthias
bf5868c96d Add testcase for nonexisting pairs on whitelist 2021-01-15 07:10:17 +01:00
nas-
f72d53351c Added ability to keep invalid pairs while expanding expand_pairlist 2021-01-15 06:37:57 +01:00
sobeit2020
ce5ba1bb6e Adding Conda installation process 2021-01-15 00:14:11 +00:00
Matthias
0b65fe6afe Capture backtest start / end time 2021-01-14 19:09:25 +01:00
Matthias
9147106259 call bot_loop_start() in backtesting to allow setup-code to run 2021-01-14 19:09:25 +01:00
Matthias
baa1142afa Use preprocessed to get min/max date in hyperopt 2021-01-14 19:09:21 +01:00
Matthias
9d4cdcad10 Extract backtesting of one strategy 2021-01-14 19:04:42 +01:00
Matthias
6d1fba1409 Remove unnecessary log output tests 2021-01-14 19:04:42 +01:00
Matthias
f3de0dd3eb Fix support for protections in hyperopt
closes #4208
2021-01-14 06:53:40 +01:00
Matthias
d289fe44cb Merge pull request #4205 from tejeshreddy/docs-edge
fix: edge doc typos [done]
2021-01-13 16:43:43 +01:00
tejeshreddy
950c5c0113 fix: edge doc typos 2021-01-13 16:50:38 +05:30
Matthias
adb3fb123e Fix typo 2021-01-12 19:35:02 +01:00
Matthias
47a06c6213 Fix enable/reenable of swagger UI endpoint 2021-01-12 19:28:22 +01:00
Matthias
ac43591c44 Fix failing api when max_open_trades is unlimited 2021-01-12 19:24:37 +01:00
Matthias
60ea32e398 Improve wording 2021-01-12 19:05:25 +01:00
Matthias
6007d5182a Merge pull request #4147 from hoeckxer/ignore_expired_candle
Ignoring candles that have expired within timeframe
2021-01-12 19:04:16 +01:00
hoeckxer
1f6a71fdd9 Reformat code on new version 2021-01-12 08:24:11 +01:00
Matthias
951c6ac1d4 Merge pull request #4193 from freqtrade/sell_profit_offset
Sell profit offset
2021-01-12 07:58:07 +01:00
hoeckxer
71f45021b9 Removed redundant statement 2021-01-12 07:35:30 +01:00
hoeckxer
e328182bd7 Changed workings so it only needs to timing-parameter, instead of also requiring a boolean value 2021-01-12 07:30:39 +01:00
nas-
4d7ffa8c81 Added suppoort for regex in whitelist 2021-01-12 01:13:58 +01:00
Matthias
b062b836cc Add test for sell_profit_offset 2021-01-11 19:42:44 +01:00
Matthias
63a579dbab Add sell_profit_offset parameter
Allows defining positive offsets before enabling the sell signal
2021-01-11 19:30:25 +01:00
Matthias
dbc25f00ac Switch full config from bittrex to binance
bittrex no longer supports volumepairlist.

closes #4192
2021-01-11 19:12:03 +01:00
Matthias
0c6c5162e8 Merge pull request #4189 from freqtrade/fix/4183
Include stoploss_on_exchange in stoploss_guard
2021-01-11 08:14:59 +01:00
Matthias
689c19620c Merge pull request #4188 from freqtrade/dependabot/pip/develop/pytest-mock-3.5.1
Bump pytest-mock from 3.5.0 to 3.5.1
2021-01-11 07:57:19 +01:00
Matthias
f159c46438 Include stoploss_on_exchange in stoploss_guard
fix #4183
2021-01-11 07:55:01 +01:00
Matthias
bc0550358f Merge pull request #4186 from freqtrade/dependabot/pip/develop/prompt-toolkit-3.0.10
Bump prompt-toolkit from 3.0.9 to 3.0.10
2021-01-11 07:36:29 +01:00
Matthias
d78fd3fa8f Merge pull request #4185 from freqtrade/dependabot/pip/develop/mkdocs-material-6.2.4
Bump mkdocs-material from 6.2.3 to 6.2.4
2021-01-11 07:34:48 +01:00
Matthias
6c29964bcc Merge pull request #4187 from freqtrade/dependabot/pip/develop/ccxt-1.40.30
Bump ccxt from 1.40.25 to 1.40.30
2021-01-11 07:33:55 +01:00
dependabot[bot]
59efc5f083 Bump pytest-mock from 3.5.0 to 3.5.1
Bumps [pytest-mock](https://github.com/pytest-dev/pytest-mock) from 3.5.0 to 3.5.1.
- [Release notes](https://github.com/pytest-dev/pytest-mock/releases)
- [Changelog](https://github.com/pytest-dev/pytest-mock/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest-mock/compare/v3.5.0...v3.5.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-11 05:38:47 +00:00
dependabot[bot]
f1809286cf Bump ccxt from 1.40.25 to 1.40.30
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.40.25 to 1.40.30.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.40.25...1.40.30)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-11 05:38:47 +00:00
dependabot[bot]
a34753fcb1 Bump prompt-toolkit from 3.0.9 to 3.0.10
Bumps [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) from 3.0.9 to 3.0.10.
- [Release notes](https://github.com/prompt-toolkit/python-prompt-toolkit/releases)
- [Changelog](https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/CHANGELOG)
- [Commits](https://github.com/prompt-toolkit/python-prompt-toolkit/compare/3.0.9...3.0.10)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-11 05:38:45 +00:00
dependabot[bot]
ddecf3ef98 Bump mkdocs-material from 6.2.3 to 6.2.4
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 6.2.3 to 6.2.4.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/docs/changelog.md)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/6.2.3...6.2.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-11 05:38:34 +00:00
Matthias
5102dfd6df Merge pull request #4144 from freqtrade/improve_informativepair
Improve merge_informative_pairs to properly merge correct timeframes
2021-01-09 10:15:59 +01:00
Matthias
61d225a575 Merge pull request #4170 from freqtrade/dependabot/pip/develop/pyjwt-2.0.0
Bump pyjwt from 1.7.1 to 2.0.0
2021-01-08 19:48:04 +01:00
Matthias
8631a54514 Fix test due to pyjwt2.0 2021-01-08 19:34:01 +01:00
Matthias
5f17dd06a5 Merge pull request #4173 from freqtrade/fix/4161
Fix #4161 - by not using the problematic method for windows
2021-01-08 19:22:48 +01:00
Matthias
47f391e43e Merge pull request #4164 from freqtrade/ci_macos_39
Run CI for mac on 3.9
2021-01-08 19:22:15 +01:00
Matthias
378a252ad1 Fix #4161 - by not using the problematic method for windows 2021-01-08 13:46:43 +01:00
Matthias
cc428d7e36 Merge pull request #4171 from freqtrade/dependabot/pip/develop/numpy-1.19.5
Bump numpy from 1.19.4 to 1.19.5
2021-01-08 13:44:09 +01:00
dependabot[bot]
c8df3c4730 Bump pyjwt from 1.7.1 to 2.0.0
Bumps [pyjwt](https://github.com/jpadilla/pyjwt) from 1.7.1 to 2.0.0.
- [Release notes](https://github.com/jpadilla/pyjwt/releases)
- [Changelog](https://github.com/jpadilla/pyjwt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jpadilla/pyjwt/compare/1.7.1...2.0.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 07:48:31 +00:00
Matthias
de26867ad2 Merge pull request #4166 from freqtrade/dependabot/pip/develop/pytest-mock-3.5.0
Bump pytest-mock from 3.4.0 to 3.5.0
2021-01-08 08:48:14 +01:00
dependabot[bot]
4d2c59b7ec Bump numpy from 1.19.4 to 1.19.5
Bumps [numpy](https://github.com/numpy/numpy) from 1.19.4 to 1.19.5.
- [Release notes](https://github.com/numpy/numpy/releases)
- [Changelog](https://github.com/numpy/numpy/blob/master/doc/HOWTO_RELEASE.rst.txt)
- [Commits](https://github.com/numpy/numpy/compare/v1.19.4...v1.19.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 07:47:47 +00:00
Matthias
eb9d137d5b Merge pull request #4167 from freqtrade/dependabot/pip/develop/prompt-toolkit-3.0.9
Bump prompt-toolkit from 3.0.8 to 3.0.9
2021-01-08 08:47:32 +01:00
Matthias
ee6d340aa7 Merge pull request #4169 from freqtrade/dependabot/pip/develop/ccxt-1.40.25
Bump ccxt from 1.40.14 to 1.40.25
2021-01-08 08:47:12 +01:00
Matthias
3bc59d427c Merge pull request #4168 from freqtrade/dependabot/pip/develop/uvicorn-0.13.3
Bump uvicorn from 0.13.2 to 0.13.3
2021-01-08 08:46:42 +01:00
dependabot[bot]
3cf506fa5d Bump ccxt from 1.40.14 to 1.40.25
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.40.14 to 1.40.25.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.40.14...1.40.25)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 07:16:49 +00:00
dependabot[bot]
784630e2f2 Bump uvicorn from 0.13.2 to 0.13.3
Bumps [uvicorn](https://github.com/encode/uvicorn) from 0.13.2 to 0.13.3.
- [Release notes](https://github.com/encode/uvicorn/releases)
- [Changelog](https://github.com/encode/uvicorn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/encode/uvicorn/compare/0.13.2...0.13.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 07:16:49 +00:00
dependabot[bot]
f3319e1382 Bump prompt-toolkit from 3.0.8 to 3.0.9
Bumps [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) from 3.0.8 to 3.0.9.
- [Release notes](https://github.com/prompt-toolkit/python-prompt-toolkit/releases)
- [Changelog](https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/CHANGELOG)
- [Commits](https://github.com/prompt-toolkit/python-prompt-toolkit/commits/3.0.9)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 07:16:48 +00:00
dependabot[bot]
bd5f46e4c2 Bump pytest-mock from 3.4.0 to 3.5.0
Bumps [pytest-mock](https://github.com/pytest-dev/pytest-mock) from 3.4.0 to 3.5.0.
- [Release notes](https://github.com/pytest-dev/pytest-mock/releases)
- [Changelog](https://github.com/pytest-dev/pytest-mock/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest-mock/compare/v3.4.0...v3.5.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 07:16:36 +00:00
Matthias
2e7faa782c Add documentation section for macOS installation error on 3.999999999 2021-01-08 06:51:37 +01:00
Matthias
3a9583403b Merge pull request #4165 from freqtrade/trades_dl
Trades dl fix faulty behaviour
2021-01-08 06:22:13 +01:00
Matthias
4f126bea35 Change trades-test2 to better test correct behaviour 2021-01-07 20:06:26 +01:00
Matthias
bf182dc01e Fix wrong key usage in trade_history_timebased 2021-01-07 20:03:34 +01:00
Matthias
124cb5c5bf Add cblosc brew dependency 2021-01-07 19:36:50 +01:00
Matthias
54ab61d18a Install hdf5 via brew 2021-01-07 19:27:35 +01:00
Matthias
9e66417e85 Run CI for mac on 3.9 2021-01-07 19:21:42 +01:00
Matthias
b43ef474ad Fix expired candle implementation
Improve and simplify test by passing the current time to the function
2021-01-07 07:51:49 +01:00
Matthias
7a628432a8 Merge pull request #4159 from freqtrade/protections/strategy
Allow protections to be set in the strategy
2021-01-07 06:39:34 +01:00
Matthias
c9e477214f Allow protections to be set in the strategy 2021-01-06 16:37:09 +01:00
Matthias
6ca2b2d52d Merge pull request #4158 from freqtrade/fix/rpc_history_bug
Fix bug in RPC history mode when no data is found
2021-01-06 16:03:03 +01:00
Matthias
e69dac2704 Fix bug in RPC history mode when no data is found 2021-01-06 15:38:46 +01:00
Matthias
a9ca72c1b8 Fix typo in documentation 2021-01-06 11:04:14 +01:00
Matthias
dfe9247c65 Merge pull request #4155 from freqtrade/fix_dry_open_order_update
Don't update open orders in dry-run mode
2021-01-06 10:52:39 +01:00
Matthias
91f8667881 DOn't update open orders in dry-run mode 2021-01-06 09:57:36 +01:00
Matthias
3d57a108d8 Merge pull request #4150 from hoeckxer/protection_documentation_clarification
Protections - clarification in documentation
2021-01-06 09:55:43 +01:00
Matthias
a906093153 FIx doc wording for all guards 2021-01-06 09:45:21 +01:00
hoeckxer
f7b055a58c Attempt to improve wording
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-06 09:26:03 +01:00
hoeckxer
95732e8991 Clarification in documentation
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-05 21:03:23 +01:00
hoeckxer
c0f170fdb9 Merge branch 'develop' into ignore_expired_candle 2021-01-05 21:00:08 +01:00
hoeckxer
5c34140a19 Adjusted documentation to reflect sub-key configuration 2021-01-05 20:59:31 +01:00
hoeckxer
65d91a3a58 isort fix 2021-01-05 15:36:34 +01:00
hoeckxer
573de1cf08 Fixed flake8 warnings 2021-01-05 15:30:29 +01:00
hoeckxer
67d84e7514 Merge branch 'ignore_expired_candle' of github.com:hoeckxer/freqtrade into ignore_expired_candle 2021-01-05 14:49:46 +01:00
hoeckxer
e3f3f36298 Changes based on review comments 2021-01-05 14:49:35 +01:00
Erwin Hoeckx
eaaaddac86 Update docs/configuration.md
Co-authored-by: Matthias <xmatthias@outlook.com>
2021-01-05 11:10:00 +01:00
Matthias
c010cdf894 Merge pull request #4138 from freqtrade/fastapi
use Fastapi instead of flask for API operations
2021-01-05 10:07:19 +01:00
hoeckxer
c9ed2137bb Simplified return statements
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-05 09:07:46 +01:00
Erwin Hoeckx
67306d943a Update interface.py
Simplified return value, thereby including the situation where the time simply hasn't expired yet
2021-01-05 07:33:34 +01:00
Erwin Hoeckx
9a93a0876a Update interface.py
Adjusted comment
2021-01-05 07:32:07 +01:00
hoeckxer
844df96ec7 Making changes so the build checks are satisified (imports & flake8)
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-05 07:06:53 +01:00
hoeckxer
614a996597 First commit about ignoring expired candle
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-04 20:49:24 +01:00
Matthias
cce4d7e42c Merge pull request #4145 from hoeckxer/custom_stoploss_doc_addition
Added an example with a positive offset for a custom stoploss
2021-01-04 19:19:53 +01:00
hoeckxer
1cf6e2c957 Changed documentation based on review comments
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-04 14:37:22 +01:00
hoeckxer
0704cfb05b Added an example with a positive offset for a custom stoploss
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2021-01-04 14:14:52 +01:00
Matthias
07bc0c3fce Improve merge_informative_pairs to properly merge correct timeframes
explanation in #4073, closes #4073
2021-01-04 13:49:38 +01:00
Matthias
d1804dee6b Add note about python-dev dependency 2021-01-04 09:40:17 +01:00
Matthias
9e84dd9274 Merge pull request #4141 from freqtrade/dependabot/pip/develop/scipy-1.6.0
Bump scipy from 1.5.4 to 1.6.0
2021-01-04 09:30:57 +01:00
Matthias
a7e3f9ef70 Merge pull request #4142 from freqtrade/dependabot/pip/develop/isort-5.7.0
Bump isort from 5.6.4 to 5.7.0
2021-01-04 09:27:04 +01:00
Matthias
a33f4fd9ca Merge pull request #4143 from freqtrade/dependabot/pip/develop/ccxt-1.40.14
Bump ccxt from 1.39.79 to 1.40.14
2021-01-04 08:30:42 +01:00
dependabot[bot]
9e435fba0b Bump ccxt from 1.39.79 to 1.40.14
Bumps [ccxt](https://github.com/ccxt/ccxt) from 1.39.79 to 1.40.14.
- [Release notes](https://github.com/ccxt/ccxt/releases)
- [Changelog](https://github.com/ccxt/ccxt/blob/master/doc/exchanges-by-country.rst)
- [Commits](https://github.com/ccxt/ccxt/compare/1.39.79...1.40.14)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-04 05:39:14 +00:00
dependabot[bot]
7d06e61461 Bump scipy from 1.5.4 to 1.6.0
Bumps [scipy](https://github.com/scipy/scipy) from 1.5.4 to 1.6.0.
- [Release notes](https://github.com/scipy/scipy/releases)
- [Commits](https://github.com/scipy/scipy/compare/v1.5.4...v1.6.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-04 05:38:57 +00:00
dependabot[bot]
66391b80ae Bump isort from 5.6.4 to 5.7.0
Bumps [isort](https://github.com/pycqa/isort) from 5.6.4 to 5.7.0.
- [Release notes](https://github.com/pycqa/isort/releases)
- [Changelog](https://github.com/PyCQA/isort/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/pycqa/isort/compare/5.6.4...5.7.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-04 05:38:57 +00:00
Matthias
5ca2cd3a1e Change defaults to log only errors 2021-01-03 07:18:41 +01:00
Matthias
634d6f3898 Change logging to stderr 2021-01-03 07:15:45 +01:00
Matthias
26c3463403 Stake-amount supports unlimited, too 2021-01-03 06:49:10 +01:00
Matthias
cff50f9f66 Add response-model for show_config 2021-01-03 06:49:10 +01:00
Matthias
ca0bb7bbb8 Don't require RPC for strategy 2021-01-03 06:49:07 +01:00
Matthias
e6176d43f3 Optional RPC dependency 2021-01-03 06:49:07 +01:00
Matthias
3dc37dd79d Add types for deps 2021-01-03 06:49:07 +01:00
Matthias
336dd1a29c Rename api_models to api_schemas 2021-01-03 06:49:07 +01:00
Matthias
84ced92002 Fix mock-tests missing some fields 2021-01-03 06:49:07 +01:00
Matthias
29f4dd1dcd Enhance some response models 2021-01-03 06:49:07 +01:00
Matthias
718f2b24d2 Don't use relative imports 2021-01-03 06:49:07 +01:00
Matthias
b2ab553a31 Rename api_server2 module to apiserver 2021-01-03 06:49:04 +01:00
Matthias
eb20f6e7d0 Align auth token to flask version to prevent user-logout 2021-01-03 06:49:04 +01:00
Matthias
346542e5cd Remove flask dependency 2021-01-03 06:49:04 +01:00
Matthias
68d148e72d Allow configuration of openAPI interface 2021-01-03 06:49:04 +01:00
Matthias
1717121f10 Properly use JWT secret key 2021-01-03 06:49:04 +01:00
Matthias
790f833653 Some more tests around api_auth 2021-01-03 06:49:04 +01:00
Matthias
29ce323649 Fix wrong hyperoptlosstest 2021-01-03 06:49:04 +01:00
Matthias
776ce57f55 Remove api_server 2021-01-03 06:49:04 +01:00
Matthias
54a50b1fb4 Fix some tests 2021-01-03 06:49:04 +01:00
Matthias
9f873305eb Improve response models 2021-01-03 06:49:04 +01:00
Matthias
9350f505bc Implement missing methods 2021-01-03 06:49:04 +01:00
Matthias
e23898d17b Improve some tests 2021-01-03 06:49:04 +01:00
Matthias
9ee1d88355 Implement more endpoints 2021-01-03 06:49:04 +01:00
Matthias
73a29e6d74 Improve tests, implement more fastapi methods 2021-01-03 06:49:04 +01:00
Matthias
a18d66e108 Add more endpoints to fastapi 2021-01-03 06:49:04 +01:00
Matthias
f37ea4ba24 Fix some initial tests towards fastAPI 2021-01-03 06:49:04 +01:00
Matthias
4b86700a0f Implement more endpoints 2021-01-03 06:48:56 +01:00
Matthias
5e4c4cae06 Fix auth providers 2021-01-03 06:48:53 +01:00
Matthias
86d0700884 Move models to apimodels 2021-01-03 06:46:25 +01:00
Matthias
6594278509 Reorder endpoints 2021-01-03 06:46:25 +01:00
Matthias
eac74a9dec Implement auth in fastapi 2021-01-03 06:46:25 +01:00
Matthias
619b855d5f Add version endpoint 2021-01-03 06:46:25 +01:00
Matthias
a862f19f82 Allow retrieval of rpc and config via dependencies 2021-01-03 06:46:25 +01:00
Matthias
1e38fec61b Initial fastapi implementation (Ping working) 2021-01-03 06:46:25 +01:00
Matthias
31829d5250 Merge pull request #4134 from hoeckxer/documentation_imports_custom_stoploss
Added imports to documentation for clarification when using custom st…
2021-01-02 09:23:43 +01:00
Matthias
11f36fbaee Fix all custom stoploss samples 2021-01-02 09:14:31 +01:00
Erwin Hoeckx
67ced6a53c Update docs/strategy-advanced.md
Co-authored-by: Matthias <xmatthias@outlook.com>
2021-01-01 20:49:04 +01:00
hoeckxer
e5840abaf9 Added imports to documentation for clarification when using custom stoploss
Signed-off-by: hoeckxer <hawkeyenl@yahoo.com>
2020-12-31 21:05:47 +01:00
Matthias
885da85fce Merge branch 'stable' into develop 2020-12-31 10:39:20 +01:00
Matthias
9e3224ccc0 Merge pull request #4089 from freqtrade/feat/stoploss_custom
introduce custom stoploss
2020-12-31 10:33:33 +01:00
Matthias
12de29dd3e Merge pull request #4133 from freqtrade/dynamic_pairlist
Wildcard based blacklist
2020-12-31 10:02:30 +01:00
Matthias
512e163355 change docstring to better reflect what the method is for 2020-12-31 09:48:49 +01:00
Matthias
bd7600ff06 Small visual changes 2020-12-31 09:43:24 +01:00
Matthias
04624aae40 Add documentation for wildcard-blacklist 2020-12-30 12:30:50 +01:00
Matthias
0affacd39a Support invalid regex blacklist from config 2020-12-30 10:14:22 +01:00
Matthias
9feabe707f Fix RPC methods to allow wildcards (and validate wildcards) 2020-12-30 09:57:31 +01:00
Matthias
704cf14383 Add expand_pairlist method 2020-12-30 09:55:44 +01:00
Matthias
2fdda8e448 plot-profit should fail gracefully if no trade is within the selected timerange
closes #4119
2020-12-30 08:30:41 +01:00
Matthias
b8899b39ec Show advanced plot-config section again
closes #4132
2020-12-30 06:29:59 +01:00
Matthias
9d7e0514ff Merge pull request #4131 from freqtrade/fix/krakenbalance
Fix/krakenbalance
2020-12-30 06:23:25 +01:00
Matthias
b607740dd1 Fix kraken balance bug if open buy orders exist 2020-12-29 20:06:37 +01:00
Matthias
238e9aabb1 Add test showing wrong behaviour 2020-12-29 20:05:07 +01:00
Matthias
dcc7d559ee Reinstate header partials 2020-12-28 14:08:57 +01:00
Matthias
ecea6c9526 Move jquery to the bottom 2020-12-28 14:02:30 +01:00
Matthias
accc59aa1b Reinstate jquery 2020-12-28 13:49:08 +01:00
Matthias
003552d78c Remove custom header section from docs 2020-12-28 10:19:24 +01:00
Matthias
d4e42987e2 Merge pull request #4126 from freqtrade/dependabot/pip/develop/pandas-1.2.0
Bump pandas from 1.1.5 to 1.2.0
2020-12-28 10:09:05 +01:00
Matthias
fe8898c7f8 Merge pull request #4124 from freqtrade/dependabot/pip/develop/scikit-learn-0.24.0
Bump scikit-learn from 0.23.2 to 0.24.0
2020-12-28 09:54:29 +01:00
Matthias
0d4cf32086 Slightly adapt to pandas incompatibility 2020-12-28 09:50:48 +01:00
dependabot[bot]
30087697e0 Bump pandas from 1.1.5 to 1.2.0
Bumps [pandas](https://github.com/pandas-dev/pandas) from 1.1.5 to 1.2.0.
- [Release notes](https://github.com/pandas-dev/pandas/releases)
- [Changelog](https://github.com/pandas-dev/pandas/blob/master/RELEASE.md)
- [Commits](https://github.com/pandas-dev/pandas/compare/v1.1.5...v1.2.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-28 08:21:17 +00:00
dependabot[bot]
092ebf845d Bump scikit-learn from 0.23.2 to 0.24.0
Bumps [scikit-learn](https://github.com/scikit-learn/scikit-learn) from 0.23.2 to 0.24.0.
- [Release notes](https://github.com/scikit-learn/scikit-learn/releases)
- [Commits](https://github.com/scikit-learn/scikit-learn/compare/0.23.2...0.24.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-28 05:37:16 +00:00
Matthias
fc0d14c1b5 Improve documentation 2020-12-20 19:14:18 +01:00
Matthias
676dd0d664 Improve documentation 2020-12-20 11:22:15 +01:00
Matthias
9d5961e224 Rename method to custom_stoploss 2020-12-20 11:17:50 +01:00
Matthias
277342f167 Rename flag to "use_custom_stoposs" 2020-12-20 11:12:22 +01:00
Matthias
8574751a07 Add stoploss_value to strategy template 2020-12-20 10:49:22 +01:00
Matthias
f8639fe938 Add more tests for custom_loss 2020-12-19 20:36:19 +01:00
Matthias
5f8610b28f Add explicit test for stop_loss_reached 2020-12-19 20:08:03 +01:00
Matthias
22d64553c9 Rename test file 2020-12-19 18:00:44 +01:00
Matthias
ea4238e860 cleanup some tests 2020-12-19 17:59:49 +01:00
Matthias
11e2915621 Fix documentation problem 2020-12-19 17:44:39 +01:00
Matthias
6892c08e9b Improve docstring 2020-12-19 13:18:06 +01:00
Matthias
b2c1098316 more docs for dynamic stoploss method 2020-12-19 12:03:18 +01:00
Matthias
f7b54c2415 Allow and document time-based custom stoploss
closes #3206
2020-12-19 11:46:49 +01:00
Matthias
f235ab8cf4 Fix some typos in docs 2020-12-19 11:39:21 +01:00
Matthias
18795844d8 Add initial set of custom stoploss documentation 2020-12-19 11:37:20 +01:00
Matthias
a414b57d54 Experiment with custom stoploss interface 2020-12-18 06:56:56 +01:00
Matthias
8f6aefb591 Extract stoploss assignment 2020-12-18 06:56:56 +01:00
Matthias
768a24c375 Add stoplossvalue interface 2020-12-18 06:56:56 +01:00
178 changed files with 6821 additions and 3967 deletions

View File

@@ -3,13 +3,15 @@ FROM freqtradeorg/freqtrade:develop
# Install dependencies # Install dependencies
COPY requirements-dev.txt /freqtrade/ COPY requirements-dev.txt /freqtrade/
RUN apt-get update \ RUN apt-get update \
&& apt-get -y install git sudo vim \ && apt-get -y install git mercurial sudo vim \
&& apt-get clean \ && apt-get clean \
&& pip install autopep8 -r docs/requirements-docs.txt -r requirements-dev.txt --no-cache-dir \ && pip install autopep8 -r docs/requirements-docs.txt -r requirements-dev.txt --no-cache-dir \
&& useradd -u 1000 -U -m ftuser \ && useradd -u 1000 -U -m ftuser \
&& mkdir -p /home/ftuser/.vscode-server /home/ftuser/.vscode-server-insiders /home/ftuser/commandhistory \ && mkdir -p /home/ftuser/.vscode-server /home/ftuser/.vscode-server-insiders /home/ftuser/commandhistory \
&& echo "export PROMPT_COMMAND='history -a'" >> /home/ftuser/.bashrc \ && echo "export PROMPT_COMMAND='history -a'" >> /home/ftuser/.bashrc \
&& echo "export HISTFILE=~/commandhistory/.bash_history" >> /home/ftuser/.bashrc \ && echo "export HISTFILE=~/commandhistory/.bash_history" >> /home/ftuser/.bashrc \
&& mv /root/.local /home/ftuser/.local/ \
&& chown ftuser:ftuser -R /home/ftuser/.local/ \
&& chown ftuser: -R /home/ftuser/ && chown ftuser: -R /home/ftuser/
USER ftuser USER ftuser

View File

@@ -1,5 +1,5 @@
--- ---
name: BQuestion name: Question
about: Ask a question you could not find an answer in the docs about: Ask a question you could not find an answer in the docs
title: '' title: ''
labels: "Question" labels: "Question"

View File

@@ -79,13 +79,13 @@ jobs:
- name: Backtesting - name: Backtesting
run: | run: |
cp config.json.example config.json cp config_bittrex.json.example config.json
freqtrade create-userdir --userdir user_data freqtrade create-userdir --userdir user_data
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
- name: Hyperopt - name: Hyperopt
run: | run: |
cp config.json.example config.json cp config_bittrex.json.example config.json
freqtrade create-userdir --userdir user_data freqtrade create-userdir --userdir user_data
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
@@ -102,7 +102,7 @@ jobs:
mypy freqtrade scripts mypy freqtrade scripts
- name: Slack Notification - name: Slack Notification
uses: homoluctus/slatify@v1.8.0 uses: lazy-actions/slatify@v3.0.0
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
with: with:
type: ${{ job.status }} type: ${{ job.status }}
@@ -117,7 +117,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ macos-latest ] os: [ macos-latest ]
python-version: [3.7, 3.8] python-version: [3.7, 3.8, 3.9]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@@ -146,8 +146,9 @@ jobs:
run: | run: |
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd .. cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
- name: Installation - *nix - name: Installation - macOS
run: | run: |
brew install hdf5 c-blosc
python -m pip install --upgrade pip python -m pip install --upgrade pip
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
export TA_LIBRARY_PATH=${HOME}/dependencies/lib export TA_LIBRARY_PATH=${HOME}/dependencies/lib
@@ -170,13 +171,13 @@ jobs:
- name: Backtesting - name: Backtesting
run: | run: |
cp config.json.example config.json cp config_bittrex.json.example config.json
freqtrade create-userdir --userdir user_data freqtrade create-userdir --userdir user_data
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
- name: Hyperopt - name: Hyperopt
run: | run: |
cp config.json.example config.json cp config_bittrex.json.example config.json
freqtrade create-userdir --userdir user_data freqtrade create-userdir --userdir user_data
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
@@ -193,7 +194,7 @@ jobs:
mypy freqtrade scripts mypy freqtrade scripts
- name: Slack Notification - name: Slack Notification
uses: homoluctus/slatify@v1.8.0 uses: lazy-actions/slatify@v3.0.0
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
with: with:
type: ${{ job.status }} type: ${{ job.status }}
@@ -237,13 +238,13 @@ jobs:
- name: Backtesting - name: Backtesting
run: | run: |
cp config.json.example config.json cp config_bittrex.json.example config.json
freqtrade create-userdir --userdir user_data freqtrade create-userdir --userdir user_data
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
- name: Hyperopt - name: Hyperopt
run: | run: |
cp config.json.example config.json cp config_bittrex.json.example config.json
freqtrade create-userdir --userdir user_data freqtrade create-userdir --userdir user_data
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
@@ -256,7 +257,7 @@ jobs:
mypy freqtrade scripts mypy freqtrade scripts
- name: Slack Notification - name: Slack Notification
uses: homoluctus/slatify@v1.8.0 uses: lazy-actions/slatify@v3.0.0
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
with: with:
type: ${{ job.status }} type: ${{ job.status }}
@@ -287,7 +288,7 @@ jobs:
mkdocs build mkdocs build
- name: Slack Notification - name: Slack Notification
uses: homoluctus/slatify@v1.8.0 uses: lazy-actions/slatify@v3.0.0
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
with: with:
type: ${{ job.status }} type: ${{ job.status }}
@@ -310,7 +311,7 @@ jobs:
runs-on: ubuntu-20.04 runs-on: ubuntu-20.04
steps: steps:
- name: Slack Notification - name: Slack Notification
uses: homoluctus/slatify@v1.8.0 uses: lazy-actions/slatify@v3.0.0
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
with: with:
type: ${{ job.status }} type: ${{ job.status }}
@@ -397,7 +398,7 @@ jobs:
- name: Slack Notification - name: Slack Notification
uses: homoluctus/slatify@v1.8.0 uses: lazy-actions/slatify@v3.0.0
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
with: with:
type: ${{ job.status }} type: ${{ job.status }}

1
.gitignore vendored
View File

@@ -8,6 +8,7 @@ user_data/*
user_data/notebooks/* user_data/notebooks/*
freqtrade-plot.html freqtrade-plot.html
freqtrade-profit-plot.html freqtrade-profit-plot.html
freqtrade/rpc/api_server/ui/*
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/

View File

@@ -26,12 +26,12 @@ jobs:
# - coveralls || true # - coveralls || true
name: pytest name: pytest
- script: - script:
- cp config.json.example config.json - cp config_bittrex.json.example config.json
- freqtrade create-userdir --userdir user_data - freqtrade create-userdir --userdir user_data
- freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy - freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
name: backtest name: backtest
- script: - script:
- cp config.json.example config.json - cp config_bittrex.json.example config.json
- freqtrade create-userdir --userdir user_data - freqtrade create-userdir --userdir user_data
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily - freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily
name: hyperopt name: hyperopt

View File

@@ -12,7 +12,7 @@ Few pointers for contributions:
- New features need to contain unit tests, must conform to PEP8 (max-line-length = 100) and should be documented with the introduction PR. - New features need to contain unit tests, must conform to PEP8 (max-line-length = 100) and should be documented with the introduction PR.
- PR's can be declared as `[WIP]` - which signify Work in Progress Pull Requests (which are not finished). - PR's can be declared as `[WIP]` - which signify Work in Progress Pull Requests (which are not finished).
If you are unsure, discuss the feature on our [discord server](https://discord.gg/MA9v74M), on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA) or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR. If you are unsure, discuss the feature on our [discord server](https://discord.gg/MA9v74M), on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw) or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
## Getting started ## Getting started

View File

@@ -1,4 +1,4 @@
FROM python:3.8.6-slim-buster as base FROM python:3.9.2-slim-buster as base
# Setup env # Setup env
ENV LANG C.UTF-8 ENV LANG C.UTF-8
@@ -40,7 +40,9 @@ COPY --from=python-deps /root/.local /root/.local
# Install and execute # Install and execute
COPY . /freqtrade/ COPY . /freqtrade/
RUN pip install -e . --no-cache-dir \ RUN pip install -e . --no-cache-dir \
&& mkdir /freqtrade/user_data/ && mkdir /freqtrade/user_data/ \
&& freqtrade install-ui
ENTRYPOINT ["freqtrade"] ENTRYPOINT ["freqtrade"]
# Default to trade mode # Default to trade mode
CMD [ "trade" ] CMD [ "trade" ]

View File

@@ -41,7 +41,11 @@ COPY --from=python-deps /root/.local /root/.local
# Install and execute # Install and execute
COPY . /freqtrade/ COPY . /freqtrade/
RUN pip install -e . --no-cache-dir RUN apt-get install -y libhdf5-serial-dev \
&& apt-get clean \
&& pip install -e . --no-cache-dir \
&& freqtrade install-ui
ENTRYPOINT ["freqtrade"] ENTRYPOINT ["freqtrade"]
# Default to trade mode # Default to trade mode
CMD [ "trade" ] CMD [ "trade" ]

View File

@@ -1,5 +1,6 @@
include LICENSE include LICENSE
include README.md include README.md
include config.json.example
recursive-include freqtrade *.py recursive-include freqtrade *.py
recursive-include freqtrade/templates/ *.j2 *.ipynb recursive-include freqtrade/templates/ *.j2 *.ipynb
include freqtrade/rpc/api_server/ui/fallback_file.html
include freqtrade/rpc/api_server/ui/favicon.ico

View File

@@ -22,12 +22,21 @@ expect.
We strongly recommend you to have coding and Python knowledge. Do not We strongly recommend you to have coding and Python knowledge. Do not
hesitate to read the source code and understand the mechanism of this bot. hesitate to read the source code and understand the mechanism of this bot.
## Exchange marketplaces supported ## Supported Exchange marketplaces
Please read the [exchange specific notes](docs/exchanges.md) to learn about eventual, special configurations needed for each exchange.
- [X] [Bittrex](https://bittrex.com/) - [X] [Bittrex](https://bittrex.com/)
- [X] [Binance](https://www.binance.com/) ([*Note for binance users](docs/exchanges.md#blacklists)) - [X] [Binance](https://www.binance.com/) ([*Note for binance users](docs/exchanges.md#blacklists))
- [X] [Kraken](https://kraken.com/) - [X] [Kraken](https://kraken.com/)
- [ ] [113 others to tests](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_ - [X] [FTX](https://ftx.com)
- [ ] [potentially many others](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
### Community tested
Exchanges confirmed working by the community:
- [X] [Bitvavo](https://bitvavo.com/)
## Documentation ## Documentation
@@ -39,7 +48,7 @@ Please find the complete documentation on our [website](https://www.freqtrade.io
- [x] **Based on Python 3.7+**: For botting on any operating system - Windows, macOS and Linux. - [x] **Based on Python 3.7+**: For botting on any operating system - Windows, macOS and Linux.
- [x] **Persistence**: Persistence is achieved through sqlite. - [x] **Persistence**: Persistence is achieved through sqlite.
- [x] **Dry-run**: Run the bot without playing money. - [x] **Dry-run**: Run the bot without paying money.
- [x] **Backtesting**: Run a simulation of your buy/sell strategy. - [x] **Backtesting**: Run a simulation of your buy/sell strategy.
- [x] **Strategy Optimization by machine learning**: Use machine learning to optimize your buy/sell strategy parameters with real exchange data. - [x] **Strategy Optimization by machine learning**: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
- [x] **Edge position sizing** Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. [Learn more](https://www.freqtrade.io/en/latest/edge/). - [x] **Edge position sizing** Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. [Learn more](https://www.freqtrade.io/en/latest/edge/).
@@ -113,7 +122,7 @@ Telegram is not mandatory. However, this is a great way to control your bot. Mor
- `/start`: Starts the trader. - `/start`: Starts the trader.
- `/stop`: Stops the trader. - `/stop`: Stops the trader.
- `/stopbuy`: Stop entering new trades. - `/stopbuy`: Stop entering new trades.
- `/status [table]`: Lists all open trades. - `/status <trade_id>|[table]`: Lists all or specific open trades.
- `/profit`: Lists cumulative profit from all finished trades - `/profit`: Lists cumulative profit from all finished trades
- `/forcesell <trade_id>|all`: Instantly sells the given trade (Ignoring `minimum_roi`). - `/forcesell <trade_id>|all`: Instantly sells the given trade (Ignoring `minimum_roi`).
- `/performance`: Show performance of each finished trade grouped by pair - `/performance`: Show performance of each finished trade grouped by pair
@@ -138,7 +147,7 @@ For any questions not covered by the documentation or for further information ab
Please check out our [discord server](https://discord.gg/MA9v74M). Please check out our [discord server](https://discord.gg/MA9v74M).
You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA). You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw).
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue) ### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
@@ -169,7 +178,7 @@ to understand the requirements before sending your pull-requests.
Coding is not a necessity to contribute - maybe start with improving our documentation? Coding is not a necessity to contribute - maybe start with improving our documentation?
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase. Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [discord](https://discord.gg/MA9v74M) or [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it. **Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [discord](https://discord.gg/MA9v74M) or [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it.
**Important:** Always create your PR against the `develop` branch, not `stable`. **Important:** Always create your PR against the `develop` branch, not `stable`.
@@ -191,5 +200,5 @@ To run this bot we recommend you a cloud instance with a minimum of:
- [pip](https://pip.pypa.io/en/stable/installing/) - [pip](https://pip.pypa.io/en/stable/installing/)
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html) - [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
- [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended) - [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended)
- [Docker](https://www.docker.com/products/docker) (Recommended) - [Docker](https://www.docker.com/products/docker) (Recommended)

View File

@@ -30,7 +30,7 @@ if [ $? -ne 0 ]; then
fi fi
# Run backtest # Run backtest
docker run --rm -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy DefaultStrategy docker run --rm -v $(pwd)/config_bittrex.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy DefaultStrategy
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo "failed running backtest" echo "failed running backtest"
@@ -51,6 +51,8 @@ fi
docker images docker images
docker push ${IMAGE_NAME} docker push ${IMAGE_NAME}
docker push ${IMAGE_NAME}:$TAG_PLOT
docker push ${IMAGE_NAME}:$TAG
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo "failed pushing repo" echo "failed pushing repo"
return 1 return 1

View File

@@ -12,15 +12,15 @@
"sell": 30 "sell": 30
}, },
"bid_strategy": { "bid_strategy": {
"use_order_book": false,
"ask_last_balance": 0.0, "ask_last_balance": 0.0,
"use_order_book": false,
"order_book_top": 1, "order_book_top": 1,
"check_depth_of_market": { "check_depth_of_market": {
"enabled": false, "enabled": false,
"bids_to_ask_delta": 1 "bids_to_ask_delta": 1
} }
}, },
"ask_strategy":{ "ask_strategy": {
"use_order_book": false, "use_order_book": false,
"order_book_min": 1, "order_book_min": 1,
"order_book_max": 1, "order_book_max": 1,
@@ -84,12 +84,13 @@
"enabled": false, "enabled": false,
"listen_ip_address": "127.0.0.1", "listen_ip_address": "127.0.0.1",
"listen_port": 8080, "listen_port": 8080,
"verbosity": "info", "verbosity": "error",
"jwt_secret_key": "somethingrandom", "jwt_secret_key": "somethingrandom",
"CORS_origins": [], "CORS_origins": [],
"username": "", "username": "freqtrader",
"password": "" "password": "SuperSecurePassword"
}, },
"bot_name": "freqtrade",
"initial_state": "running", "initial_state": "running",
"forcebuy_enable": false, "forcebuy_enable": false,
"internals": { "internals": {

View File

@@ -41,13 +41,13 @@
"ETH/BTC", "ETH/BTC",
"LTC/BTC", "LTC/BTC",
"ETC/BTC", "ETC/BTC",
"DASH/BTC", "RVN/BTC",
"ZEC/BTC", "CRO/BTC",
"XLM/BTC", "XLM/BTC",
"XRP/BTC", "XRP/BTC",
"TRX/BTC", "TRX/BTC",
"ADA/BTC", "ADA/BTC",
"XMR/BTC" "DOT/BTC"
], ],
"pair_blacklist": [ "pair_blacklist": [
"DOGE/BTC" "DOGE/BTC"
@@ -79,12 +79,13 @@
"enabled": false, "enabled": false,
"listen_ip_address": "127.0.0.1", "listen_ip_address": "127.0.0.1",
"listen_port": 8080, "listen_port": 8080,
"verbosity": "info", "verbosity": "error",
"jwt_secret_key": "somethingrandom", "jwt_secret_key": "somethingrandom",
"CORS_origins": [], "CORS_origins": [],
"username": "", "username": "freqtrader",
"password": "" "password": "SuperSecurePassword"
}, },
"bot_name": "freqtrade",
"initial_state": "running", "initial_state": "running",
"forcebuy_enable": false, "forcebuy_enable": false,
"internals": { "internals": {

View File

@@ -42,12 +42,15 @@
"order_book_max": 1, "order_book_max": 1,
"use_sell_signal": true, "use_sell_signal": true,
"sell_profit_only": false, "sell_profit_only": false,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": false "ignore_roi_if_buy_signal": false
}, },
"order_types": { "order_types": {
"buy": "limit", "buy": "limit",
"sell": "limit", "sell": "limit",
"emergencysell": "market", "emergencysell": "market",
"forcesell": "market",
"forcebuy": "market",
"stoploss": "market", "stoploss": "market",
"stoploss_on_exchange": false, "stoploss_on_exchange": false,
"stoploss_on_exchange_interval": 60 "stoploss_on_exchange_interval": 60
@@ -103,28 +106,33 @@
} }
], ],
"exchange": { "exchange": {
"name": "bittrex", "name": "binance",
"sandbox": false, "sandbox": false,
"key": "your_exchange_key", "key": "your_exchange_key",
"secret": "your_exchange_secret", "secret": "your_exchange_secret",
"password": "", "password": "",
"ccxt_config": {"enableRateLimit": true}, "ccxt_config": {"enableRateLimit": true},
"ccxt_async_config": { "ccxt_async_config": {
"enableRateLimit": false, "enableRateLimit": true,
"rateLimit": 500, "rateLimit": 500,
"aiohttp_trust_env": false "aiohttp_trust_env": false
}, },
"pair_whitelist": [ "pair_whitelist": [
"ALGO/BTC",
"ATOM/BTC",
"BAT/BTC",
"BCH/BTC",
"BRD/BTC",
"EOS/BTC",
"ETH/BTC", "ETH/BTC",
"IOTA/BTC",
"LINK/BTC",
"LTC/BTC", "LTC/BTC",
"ETC/BTC", "NEO/BTC",
"DASH/BTC", "NXS/BTC",
"ZEC/BTC", "XMR/BTC",
"XLM/BTC", "XRP/BTC",
"NXT/BTC", "XTZ/BTC"
"TRX/BTC",
"ADA/BTC",
"XMR/BTC"
], ],
"pair_blacklist": [ "pair_blacklist": [
"DOGE/BTC" "DOGE/BTC"
@@ -147,7 +155,7 @@
"remove_pumps": false "remove_pumps": false
}, },
"telegram": { "telegram": {
"enabled": true, "enabled": false,
"token": "your_telegram_token", "token": "your_telegram_token",
"chat_id": "your_telegram_chat_id", "chat_id": "your_telegram_chat_id",
"notification_settings": { "notification_settings": {
@@ -164,12 +172,14 @@
"enabled": false, "enabled": false,
"listen_ip_address": "127.0.0.1", "listen_ip_address": "127.0.0.1",
"listen_port": 8080, "listen_port": 8080,
"verbosity": "info", "verbosity": "error",
"enable_openapi": false,
"jwt_secret_key": "somethingrandom", "jwt_secret_key": "somethingrandom",
"CORS_origins": [], "CORS_origins": [],
"username": "freqtrader", "username": "freqtrader",
"password": "SuperSecurePassword" "password": "SuperSecurePassword"
}, },
"bot_name": "freqtrade",
"db_url": "sqlite:///tradesv3.sqlite", "db_url": "sqlite:///tradesv3.sqlite",
"initial_state": "running", "initial_state": "running",
"forcebuy_enable": false, "forcebuy_enable": false,

View File

@@ -89,12 +89,13 @@
"enabled": false, "enabled": false,
"listen_ip_address": "127.0.0.1", "listen_ip_address": "127.0.0.1",
"listen_port": 8080, "listen_port": 8080,
"verbosity": "info", "verbosity": "error",
"jwt_secret_key": "somethingrandom", "jwt_secret_key": "somethingrandom",
"CORS_origins": [], "CORS_origins": [],
"username": "", "username": "freqtrader",
"password": "" "password": "SuperSecurePassword"
}, },
"bot_name": "freqtrade",
"initial_state": "running", "initial_state": "running",
"forcebuy_enable": false, "forcebuy_enable": false,
"internals": { "internals": {

View File

@@ -14,6 +14,11 @@ services:
container_name: freqtrade container_name: freqtrade
volumes: volumes:
- "./user_data:/freqtrade/user_data" - "./user_data:/freqtrade/user_data"
# Expose api on port 8080 (localhost only)
# Please read the https://www.freqtrade.io/en/latest/rest-api/ documentation
# before enabling this.
# ports:
# - "127.0.0.1:8080:8080"
# Default command used when running `docker compose up` # Default command used when running `docker compose up`
command: > command: >
trade trade

View File

@@ -6,7 +6,7 @@ class.
## Derived hyperopt classes ## Derived hyperopt classes
Custom hyperop classes can be derived in the same way [it can be done for strategies](strategy-customization.md#derived-strategies). Custom hyperopt classes can be derived in the same way [it can be done for strategies](strategy-customization.md#derived-strategies).
Applying to hyperoptimization, as an example, you may override how dimensions are defined in your optimization hyperspace: Applying to hyperoptimization, as an example, you may override how dimensions are defined in your optimization hyperspace:
@@ -32,6 +32,51 @@ or
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ... $ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...
``` ```
## Sharing methods with your strategy
Hyperopt classes provide access to the Strategy via the `strategy` class attribute.
This can be a great way to reduce code duplication if used correctly, but will also complicate usage for inexperienced users.
``` python
from pandas import DataFrame
from freqtrade.strategy.interface import IStrategy
import freqtrade.vendor.qtpylib.indicators as qtpylib
class MyAwesomeStrategy(IStrategy):
buy_params = {
'rsi-value': 30,
'adx-value': 35,
}
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return self.buy_strategy_generator(self.buy_params, dataframe, metadata)
@staticmethod
def buy_strategy_generator(params, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
qtpylib.crossed_above(dataframe['rsi'], params['rsi-value']) &
dataframe['adx'] > params['adx-value']) &
dataframe['volume'] > 0
)
, 'buy'] = 1
return dataframe
class MyAwesomeHyperOpt(IHyperOpt):
...
@staticmethod
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
"""
Define the buy strategy parameters to be used by Hyperopt.
"""
def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
# Call strategy's buy strategy generator
return self.StrategyClass.buy_strategy_generator(params, dataframe, metadata)
return populate_buy_trend
```
## Creating and using a custom loss function ## Creating and using a custom loss function
To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class. To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
@@ -40,6 +85,11 @@ For the sample below, you then need to add the command line parameter `--hyperop
A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in [userdata/hyperopts](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_loss.py). A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in [userdata/hyperopts](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_loss.py).
``` python ``` python
from datetime import datetime
from typing import Dict
from pandas import DataFrame
from freqtrade.optimize.hyperopt import IHyperOptLoss from freqtrade.optimize.hyperopt import IHyperOptLoss
TARGET_TRADES = 600 TARGET_TRADES = 600
@@ -54,6 +104,7 @@ class SuperDuperHyperOptLoss(IHyperOptLoss):
@staticmethod @staticmethod
def hyperopt_loss_function(results: DataFrame, trade_count: int, def hyperopt_loss_function(results: DataFrame, trade_count: int,
min_date: datetime, max_date: datetime, min_date: datetime, max_date: datetime,
config: Dict, processed: Dict[str, DataFrame],
*args, **kwargs) -> float: *args, **kwargs) -> float:
""" """
Objective function, returns smaller number for better results Objective function, returns smaller number for better results
@@ -63,7 +114,7 @@ class SuperDuperHyperOptLoss(IHyperOptLoss):
* 0.25: Avoiding trade loss * 0.25: Avoiding trade loss
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
""" """
total_profit = results['profit_percent'].sum() total_profit = results['profit_ratio'].sum()
trade_duration = results['trade_duration'].mean() trade_duration = results['trade_duration'].mean()
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8) trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
@@ -77,10 +128,12 @@ Currently, the arguments are:
* `results`: DataFrame containing the result * `results`: DataFrame containing the result
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`): The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
`pair, profit_percent, profit_abs, open_date, open_rate, open_fee, close_date, close_rate, close_fee, amount, trade_duration, open_at_end, sell_reason` `pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, sell_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs`
* `trade_count`: Amount of trades (identical to `len(results)`) * `trade_count`: Amount of trades (identical to `len(results)`)
* `min_date`: Start date of the hyperopting TimeFrame * `min_date`: Start date of the timerange used
* `min_date`: End date of the hyperopting TimeFrame * `min_date`: End date of the timerange used
* `config`: Config object used (Note: Not all strategy-related parameters will be updated here if they are part of a hyperopt space).
* `processed`: Dict of Dataframes with the pair as keys containing the data used for backtesting.
This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you. This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.

View File

@@ -5,11 +5,97 @@ This page explains how to validate your strategy performance by using Backtestin
Backtesting requires historic data to be available. Backtesting requires historic data to be available.
To learn how to get data for the pairs and exchange you're interested in, head over to the [Data Downloading](data-download.md) section of the documentation. To learn how to get data for the pairs and exchange you're interested in, head over to the [Data Downloading](data-download.md) section of the documentation.
## Backtesting command reference
```
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
[-d PATH] [--userdir PATH] [-s NAME]
[--strategy-path PATH] [-i TIMEFRAME]
[--timerange TIMERANGE]
[--data-format-ohlcv {json,jsongz,hdf5}]
[--max-open-trades INT]
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
[--eps] [--dmmp] [--enable-protections]
[--dry-run-wallet DRY_RUN_WALLET]
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
[--export EXPORT] [--export-filename PATH]
optional arguments:
-h, --help show this help message and exit
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
`1d`).
--timerange TIMERANGE
Specify what timerange of data to use.
--data-format-ohlcv {json,jsongz,hdf5}
Storage format for downloaded candle (OHLCV) data.
(default: `None`).
--max-open-trades INT
Override the value of the `max_open_trades`
configuration setting.
--stake-amount STAKE_AMOUNT
Override the value of the `stake_amount` configuration
setting.
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
entry and exit).
--eps, --enable-position-stacking
Allow buying the same pair multiple times (position
stacking).
--dmmp, --disable-max-market-positions
Disable applying `max_open_trades` during backtest
(same as setting `max_open_trades` to a very high
number).
--enable-protections, --enableprotections
Enable protections for backtesting.Will slow
backtesting down by a considerable amount, but will
include configured protections
--dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET
Starting balance, used for backtesting / hyperopt and
dry-runs.
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
Provide a space-separated list of strategies to
backtest. Please note that ticker-interval needs to be
set either in config or via command line. When using
this together with `--export trades`, the strategy-
name is injected into the filename (so `backtest-
data.json` becomes `backtest-data-
DefaultStrategy.json`
--export EXPORT Export backtest results, argument are: trades.
Example: `--export=trades`
--export-filename PATH
Save backtest results to the file with this filename.
Requires `--export` to be set as well. Example:
`--export-filename=user_data/backtest_results/backtest
_today.json`
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
--logfile FILE Log to the file specified. Special values are:
'syslog', 'journald'. See the documentation for more
details.
-V, --version show program's version number and exit
-c PATH, --config PATH
Specify configuration file (default:
`userdir/config.json` or `config.json` whichever
exists). Multiple --config options may be used. Can be
set to `-` to read config from stdin.
-d PATH, --datadir PATH
Path to directory with historical backtesting data.
--userdir PATH, --user-data-dir PATH
Path to userdata directory.
Strategy arguments:
-s NAME, --strategy NAME
Specify strategy class name which will be used by the
bot.
--strategy-path PATH Specify additional strategy lookup path.
```
## Test your strategy with Backtesting ## Test your strategy with Backtesting
Now you have good Buy and Sell strategies and some historic data, you want to test it against Now you have good Buy and Sell strategies and some historic data, you want to test it against
real data. This is what we call real data. This is what we call [backtesting](https://en.wikipedia.org/wiki/Backtesting).
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHCLV) data from `user_data/data/<exchange>` by default. Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHCLV) data from `user_data/data/<exchange>` by default.
If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using `freqtrade download-data`. If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using `freqtrade download-data`.
@@ -17,45 +103,65 @@ For details on downloading, please refer to the [Data Downloading](data-download
The result of backtesting will confirm if your bot has better odds of making a profit than a loss. The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
All profit calculations include fees, and freqtrade will use the exchange's default fees for the calculation.
!!! Warning "Using dynamic pairlists for backtesting" !!! Warning "Using dynamic pairlists for backtesting"
Using dynamic pairlists is possible, however it relies on the current market conditions - which will not reflect the historic status of the pairlist. Using dynamic pairlists is possible, however it relies on the current market conditions - which will not reflect the historic status of the pairlist.
Also, when using pairlists other than StaticPairlist, reproducability of backtesting-results cannot be guaranteed. Also, when using pairlists other than StaticPairlist, reproducability of backtesting-results cannot be guaranteed.
Please read the [pairlists documentation](configuration.md#pairlists) for more information. Please read the [pairlists documentation](plugins.md#pairlists) for more information.
To achieve reproducible results, best generate a pairlist via the [`test-pairlist`](utils.md#test-pairlist) command and use that as static pairlist. To achieve reproducible results, best generate a pairlist via the [`test-pairlist`](utils.md#test-pairlist) command and use that as static pairlist.
### Run a backtesting against the currencies listed in your config file ### Starting balance
#### With 5 min candle (OHLCV) data (per default) Backtesting will require a starting balance, which can be provided as `--dry-run-wallet <balance>` or `--starting-balance <balance>` command line argument, or via `dry_run_wallet` configuration setting.
This amount must be higher than `stake_amount`, otherwise the bot will not be able to simulate any trade.
### Dynamic stake amount
Backtesting supports [dynamic stake amount](configuration.md#dynamic-stake-amount) by configuring `stake_amount` as `"unlimited"`, which will split the starting balance into `max_open_trades` pieces.
Profits from early trades will result in subsequent higher stake amounts, resulting in compounding of profits over the backtesting period.
### Example backtesting commands
With 5 min candle (OHLCV) data (per default)
```bash ```bash
freqtrade backtesting freqtrade backtesting --strategy AwesomeStrategy
``` ```
#### With 1 min candle (OHLCV) data Where `--strategy AwesomeStrategy` / `-s AwesomeStrategy` refers to the class name of the strategy, which is within a python file in the `user_data/strategies` directory.
---
With 1 min candle (OHLCV) data
```bash ```bash
freqtrade backtesting --timeframe 1m freqtrade backtesting --strategy AwesomeStrategy --timeframe 1m
``` ```
#### Using a different on-disk historical candle (OHLCV) data source ---
Providing a custom starting balance of 1000 (in stake currency)
```bash
freqtrade backtesting --strategy AwesomeStrategy --dry-run-wallet 1000
```
---
Using a different on-disk historical candle (OHLCV) data source
Assume you downloaded the history data from the Bittrex exchange and kept it in the `user_data/data/bittrex-20180101` directory. Assume you downloaded the history data from the Bittrex exchange and kept it in the `user_data/data/bittrex-20180101` directory.
You can then use this data for backtesting as follows: You can then use this data for backtesting as follows:
```bash ```bash
freqtrade --datadir user_data/data/bittrex-20180101 backtesting freqtrade backtesting --strategy AwesomeStrategy --datadir user_data/data/bittrex-20180101
``` ```
#### With a (custom) strategy file ---
```bash Comparing multiple Strategies
freqtrade backtesting -s SampleStrategy
```
Where `-s SampleStrategy` refers to the class name within the strategy file `sample_strategy.py` found in the `freqtrade/user_data/strategies` directory.
#### Comparing multiple Strategies
```bash ```bash
freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m
@@ -63,23 +169,29 @@ freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timefram
Where `SampleStrategy1` and `AwesomeStrategy` refer to class names of strategies. Where `SampleStrategy1` and `AwesomeStrategy` refer to class names of strategies.
#### Exporting trades to file ---
Exporting trades to file
```bash ```bash
freqtrade backtesting --export trades --config config.json --strategy SampleStrategy freqtrade backtesting --strategy backtesting --export trades --config config.json
``` ```
The exported trades can be used for [further analysis](#further-backtest-result-analysis), or can be used by the plotting script `plot_dataframe.py` in the scripts directory. The exported trades can be used for [further analysis](#further-backtest-result-analysis), or can be used by the plotting script `plot_dataframe.py` in the scripts directory.
#### Exporting trades to file specifying a custom filename ---
Exporting trades to file specifying a custom filename
```bash ```bash
freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json freqtrade backtesting --strategy backtesting --export trades --export-filename=backtest_samplestrategy.json
``` ```
Please also read about the [strategy startup period](strategy-customization.md#strategy-startup-period). Please also read about the [strategy startup period](strategy-customization.md#strategy-startup-period).
#### Supplying custom fee value ---
Supplying custom fee value
Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt. Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt.
To account for this in backtesting, you can use the `--fee` command line option to supply this value to backtesting. To account for this in backtesting, you can use the `--fee` command line option to supply this value to backtesting.
@@ -94,26 +206,26 @@ freqtrade backtesting --fee 0.001
!!! Note !!! Note
Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info. Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info.
#### Running backtest with smaller testset by using timerange ---
Use the `--timerange` argument to change how much of the testset you want to use. Running backtest with smaller test-set by using timerange
Use the `--timerange` argument to change how much of the test-set you want to use.
For example, running backtesting with the `--timerange=20190501-` option will use all available data starting with May 1st, 2019 from your inputdata. For example, running backtesting with the `--timerange=20190501-` option will use all available data starting with May 1st, 2019 from your input data.
```bash ```bash
freqtrade backtesting --timerange=20190501- freqtrade backtesting --timerange=20190501-
``` ```
You can also specify particular dates or a range span indexed by start and stop. You can also specify particular date ranges.
The full timerange specification: The full timerange specification:
- Use tickframes till 2018/01/31: `--timerange=-20180131` - Use data until 2018/01/31: `--timerange=-20180131`
- Use tickframes since 2018/01/31: `--timerange=20180131-` - Use data since 2018/01/31: `--timerange=20180131-`
- Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301` - Use data since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
- Use tickframes between POSIX timestamps 1527595200 1527618600: - Use data between POSIX / epoch timestamps 1527595200 1527618600: `--timerange=1527595200-1527618600`
`--timerange=1527595200-1527618600`
## Understand the backtesting result ## Understand the backtesting result
@@ -165,19 +277,30 @@ A backtesting result will look like that:
| Max open trades | 3 | | Max open trades | 3 |
| | | | | |
| Total trades | 429 | | Total trades | 429 |
| Total Profit % | 152.41% | | Starting balance | 0.01000000 BTC |
| Final balance | 0.01762792 BTC |
| Absolute profit | 0.00762792 BTC |
| Total profit % | 76.2% |
| Trades per day | 3.575 | | Trades per day | 3.575 |
| Avg. stake amount | 0.001 BTC |
| Total trade volume | 0.429 BTC |
| | | | | |
| Best Pair | LSK/BTC 26.26% | | Best Pair | LSK/BTC 26.26% |
| Worst Pair | ZEC/BTC -10.18% | | Worst Pair | ZEC/BTC -10.18% |
| Best Trade | LSK/BTC 4.25% | | Best Trade | LSK/BTC 4.25% |
| Worst Trade | ZEC/BTC -10.25% | | Worst Trade | ZEC/BTC -10.25% |
| Best day | 25.27% | | Best day | 0.00076 BTC |
| Worst day | -30.67% | | Worst day | -0.00036 BTC |
| Days win/draw/lose | 12 / 82 / 25 |
| Avg. Duration Winners | 4:23:00 | | Avg. Duration Winners | 4:23:00 |
| Avg. Duration Loser | 6:55:00 | | Avg. Duration Loser | 6:55:00 |
| | | | | |
| Max Drawdown | 50.63% | | Min balance | 0.00945123 BTC |
| Max balance | 0.01846651 BTC |
| Drawdown | 50.63% |
| Drawdown | 0.0015 BTC |
| Drawdown high | 0.0013 BTC |
| Drawdown low | -0.0002 BTC |
| Drawdown Start | 2019-02-15 14:10:00 | | Drawdown Start | 2019-02-15 14:10:00 |
| Drawdown End | 2019-04-11 18:15:00 | | Drawdown End | 2019-04-11 18:15:00 |
| Market change | -5.88% | | Market change | -5.88% |
@@ -198,9 +321,9 @@ here:
The bot has made `429` trades for an average duration of `4:12:00`, with a performance of `76.20%` (profit), that means it has The bot has made `429` trades for an average duration of `4:12:00`, with a performance of `76.20%` (profit), that means it has
earned a total of `0.00762792 BTC` starting with a capital of 0.01 BTC. earned a total of `0.00762792 BTC` starting with a capital of 0.01 BTC.
The column `avg profit %` shows the average profit for all trades made while the column `cum profit %` sums up all the profits/losses. The column `Avg Profit %` shows the average profit for all trades made while the column `Cum Profit %` sums up all the profits/losses.
The column `tot profit %` shows instead the total profit % in relation to allocated capital (`max_open_trades * stake_amount`). The column `Tot Profit %` shows instead the total profit % in relation to the starting balance.
In the above results we have `max_open_trades=2` and `stake_amount=0.005` in config so `tot_profit %` will be `(76.20/100) * (0.005 * 2) =~ 0.00762792 BTC`. In the above results, we have a starting balance of 0.01 BTC and an absolute profit of 0.00762792 BTC - so the `Tot Profit %` will be `(0.00762792 / 0.01) * 100 ~= 76.2%`.
Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the `minimal_roi` and `stop_loss` you have set. Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the `minimal_roi` and `stop_loss` you have set.
@@ -241,19 +364,30 @@ It contains some useful key metrics about performance of your strategy on backte
| Max open trades | 3 | | Max open trades | 3 |
| | | | | |
| Total trades | 429 | | Total trades | 429 |
| Total Profit % | 152.41% | | Starting balance | 0.01000000 BTC |
| Final balance | 0.01762792 BTC |
| Absolute profit | 0.00762792 BTC |
| Total profit % | 76.2% |
| Trades per day | 3.575 | | Trades per day | 3.575 |
| Avg. stake amount | 0.001 BTC |
| Total trade volume | 0.429 BTC |
| | | | | |
| Best Pair | LSK/BTC 26.26% | | Best Pair | LSK/BTC 26.26% |
| Worst Pair | ZEC/BTC -10.18% | | Worst Pair | ZEC/BTC -10.18% |
| Best Trade | LSK/BTC 4.25% | | Best Trade | LSK/BTC 4.25% |
| Worst Trade | ZEC/BTC -10.25% | | Worst Trade | ZEC/BTC -10.25% |
| Best day | 25.27% | | Best day | 0.00076 BTC |
| Worst day | -30.67% | | Worst day | -0.00036 BTC |
| Days win/draw/lose | 12 / 82 / 25 |
| Avg. Duration Winners | 4:23:00 | | Avg. Duration Winners | 4:23:00 |
| Avg. Duration Loser | 6:55:00 | | Avg. Duration Loser | 6:55:00 |
| | | | | |
| Max Drawdown | 50.63% | | Min balance | 0.00945123 BTC |
| Max balance | 0.01846651 BTC |
| Drawdown | 50.63% |
| Drawdown | 0.0015 BTC |
| Drawdown high | 0.0013 BTC |
| Drawdown low | -0.0002 BTC |
| Drawdown Start | 2019-02-15 14:10:00 | | Drawdown Start | 2019-02-15 14:10:00 |
| Drawdown End | 2019-04-11 18:15:00 | | Drawdown End | 2019-04-11 18:15:00 |
| Market change | -5.88% | | Market change | -5.88% |
@@ -262,15 +396,23 @@ It contains some useful key metrics about performance of your strategy on backte
``` ```
- `Backtesting from` / `Backtesting to`: Backtesting range (usually defined with the `--timerange` option). - `Backtesting from` / `Backtesting to`: Backtesting range (usually defined with the `--timerange` option).
- `Max open trades`: Setting of `max_open_trades` (or `--max-open-trades`) - to clearly see settings for this. - `Max open trades`: Setting of `max_open_trades` (or `--max-open-trades`) - or number of pairs in the pairlist (whatever is lower).
- `Total trades`: Identical to the total trades of the backtest output table. - `Total trades`: Identical to the total trades of the backtest output table.
- `Total Profit %`: Total profit per stake amount. Aligned to the TOTAL column of the first table. - `Starting balance`: Start balance - as given by dry-run-wallet (config or command line).
- `Final balance`: Final balance - starting balance + absolute profit.
- `Absolute profit`: Profit made in stake currency.
- `Total profit %`: Total profit. Aligned to the `TOTAL` row's `Tot Profit %` from the first table. Calculated as `(End capital Starting capital) / Starting capital`.
- `Trades per day`: Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy). - `Trades per day`: Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy).
- `Avg. stake amount`: Average stake amount, either `stake_amount` or the average when using dynamic stake amount.
- `Total trade volume`: Volume generated on the exchange to reach the above profit.
- `Best Pair` / `Worst Pair`: Best and worst performing pair, and it's corresponding `Cum Profit %`. - `Best Pair` / `Worst Pair`: Best and worst performing pair, and it's corresponding `Cum Profit %`.
- `Best Trade` / `Worst Trade`: Biggest winning trade and biggest losing trade - `Best Trade` / `Worst Trade`: Biggest single winning trade and biggest single losing trade.
- `Best day` / `Worst day`: Best and worst day based on daily profit. - `Best day` / `Worst day`: Best and worst day based on daily profit.
- `Days win/draw/lose`: Winning / Losing days (draws are usually days without closed trade).
- `Avg. Duration Winners` / `Avg. Duration Loser`: Average durations for winning and losing trades. - `Avg. Duration Winners` / `Avg. Duration Loser`: Average durations for winning and losing trades.
- `Max Drawdown`: Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced). - `Min balance` / `Max balance`: Lowest and Highest Wallet balance during the backtest period.
- `Drawdown`: Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced).
- `Drawdown high` / `Drawdown low`: Profit at the beginning and end of the largest drawdown period. A negative low value means initial capital lost.
- `Drawdown Start` / `Drawdown End`: Start and end datetime for this largest drawdown (can also be visualized via the `plot-dataframe` sub-command). - `Drawdown Start` / `Drawdown End`: Start and end datetime for this largest drawdown (can also be visualized via the `plot-dataframe` sub-command).
- `Market change`: Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the "close" column. - `Market change`: Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the "close" column.
@@ -335,6 +477,5 @@ Detailed output for all strategies one after the other will be available, so mak
## Next step ## Next step
Great, your strategy is profitable. What if the bot can give your the Great, your strategy is profitable. What if the bot can give your the optimal parameters to use for your strategy?
optimal parameters to use for your strategy?
Your next step is to learn [how to find optimal parameters with Hyperopt](hyperopt.md) Your next step is to learn [how to find optimal parameters with Hyperopt](hyperopt.md)

View File

@@ -4,13 +4,14 @@ This page provides you some basic concepts on how Freqtrade works and operates.
## Freqtrade terminology ## Freqtrade terminology
* Trade: Open position. * **Strategy**: Your trading strategy, telling the bot what to do.
* Open Order: Order which is currently placed on the exchange, and is not yet complete. * **Trade**: Open position.
* Pair: Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT). * **Open Order**: Order which is currently placed on the exchange, and is not yet complete.
* Timeframe: Candle length to use (e.g. `"5m"`, `"1h"`, ...). * **Pair**: Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT).
* Indicators: Technical indicators (SMA, EMA, RSI, ...). * **Timeframe**: Candle length to use (e.g. `"5m"`, `"1h"`, ...).
* Limit order: Limit orders which execute at the defined limit price or better. * **Indicators**: Technical indicators (SMA, EMA, RSI, ...).
* Market order: Guaranteed to fill, may move price depending on the order size. * **Limit order**: Limit orders which execute at the defined limit price or better.
* **Market order**: Guaranteed to fill, may move price depending on the order size.
## Fee handling ## Fee handling
@@ -49,8 +50,10 @@ This loop will be repeated again and again until the bot is stopped.
[backtesting](backtesting.md) or [hyperopt](hyperopt.md) do only part of the above logic, since most of the trading operations are fully simulated. [backtesting](backtesting.md) or [hyperopt](hyperopt.md) do only part of the above logic, since most of the trading operations are fully simulated.
* Load historic data for configured pairlist. * Load historic data for configured pairlist.
* Calculate indicators (calls `populate_indicators()`). * Calls `bot_loop_start()` once.
* Calls `populate_buy_trend()` and `populate_sell_trend()` * Calculate indicators (calls `populate_indicators()` once per pair).
* Calculate buy / sell signals (calls `populate_buy_trend()` and `populate_sell_trend()` once per pair)
* Confirm trade buy / sell (calls `confirm_trade_entry()` and `confirm_trade_exit()` if implemented in the strategy)
* Loops per candle simulating entry and exit points. * Loops per candle simulating entry and exit points.
* Generate backtest report output * Generate backtest report output

View File

@@ -56,6 +56,7 @@ optional arguments:
usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH]
[--db-url PATH] [--sd-notify] [--dry-run] [--db-url PATH] [--sd-notify] [--dry-run]
[--dry-run-wallet DRY_RUN_WALLET]
optional arguments: optional arguments:
-h, --help show this help message and exit -h, --help show this help message and exit
@@ -66,6 +67,9 @@ optional arguments:
--sd-notify Notify systemd service manager. --sd-notify Notify systemd service manager.
--dry-run Enforce dry-run for trading (removes Exchange secrets --dry-run Enforce dry-run for trading (removes Exchange secrets
and simulates trades). and simulates trades).
--dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET
Starting balance, used for backtesting / hyperopt and
dry-runs.
Common arguments: Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages). -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
@@ -205,258 +209,6 @@ in production mode. Example command:
freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite
``` ```
## Backtesting commands
Backtesting also uses the config specified via `-c/--config`.
```
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
[-d PATH] [--userdir PATH] [-s NAME]
[--strategy-path PATH] [-i TIMEFRAME]
[--timerange TIMERANGE]
[--data-format-ohlcv {json,jsongz,hdf5}]
[--max-open-trades INT]
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
[--eps] [--dmmp] [--enable-protections]
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
[--export EXPORT] [--export-filename PATH]
optional arguments:
-h, --help show this help message and exit
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
`1d`).
--timerange TIMERANGE
Specify what timerange of data to use.
--data-format-ohlcv {json,jsongz,hdf5}
Storage format for downloaded candle (OHLCV) data.
(default: `None`).
--max-open-trades INT
Override the value of the `max_open_trades`
configuration setting.
--stake-amount STAKE_AMOUNT
Override the value of the `stake_amount` configuration
setting.
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
entry and exit).
--eps, --enable-position-stacking
Allow buying the same pair multiple times (position
stacking).
--dmmp, --disable-max-market-positions
Disable applying `max_open_trades` during backtest
(same as setting `max_open_trades` to a very high
number).
--enable-protections, --enableprotections
Enable protections for backtesting.Will slow
backtesting down by a considerable amount, but will
include configured protections
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
Provide a space-separated list of strategies to
backtest. Please note that ticker-interval needs to be
set either in config or via command line. When using
this together with `--export trades`, the strategy-
name is injected into the filename (so `backtest-
data.json` becomes `backtest-data-
DefaultStrategy.json`
--export EXPORT Export backtest results, argument are: trades.
Example: `--export=trades`
--export-filename PATH
Save backtest results to the file with this filename.
Requires `--export` to be set as well. Example:
`--export-filename=user_data/backtest_results/backtest
_today.json`
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
--logfile FILE Log to the file specified. Special values are:
'syslog', 'journald'. See the documentation for more
details.
-V, --version show program's version number and exit
-c PATH, --config PATH
Specify configuration file (default:
`userdir/config.json` or `config.json` whichever
exists). Multiple --config options may be used. Can be
set to `-` to read config from stdin.
-d PATH, --datadir PATH
Path to directory with historical backtesting data.
--userdir PATH, --user-data-dir PATH
Path to userdata directory.
Strategy arguments:
-s NAME, --strategy NAME
Specify strategy class name which will be used by the
bot.
--strategy-path PATH Specify additional strategy lookup path.
```
### Getting historic data for backtesting
The first time your run Backtesting, you will need to download some historic data first.
This can be accomplished by using `freqtrade download-data`.
Check the corresponding [Data Downloading](data-download.md) section for more details
## Hyperopt commands
To optimize your strategy, you can use hyperopt parameter hyperoptimization
to find optimal parameter values for your strategy.
```
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH]
[-i TIMEFRAME] [--timerange TIMERANGE]
[--data-format-ohlcv {json,jsongz,hdf5}]
[--max-open-trades INT]
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
[--dmmp] [--enable-protections] [-e INT]
[--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
[--print-all] [--no-color] [--print-json] [-j JOBS]
[--random-state INT] [--min-trades INT]
[--hyperopt-loss NAME]
optional arguments:
-h, --help show this help message and exit
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
`1d`).
--timerange TIMERANGE
Specify what timerange of data to use.
--data-format-ohlcv {json,jsongz,hdf5}
Storage format for downloaded candle (OHLCV) data.
(default: `None`).
--max-open-trades INT
Override the value of the `max_open_trades`
configuration setting.
--stake-amount STAKE_AMOUNT
Override the value of the `stake_amount` configuration
setting.
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
entry and exit).
--hyperopt NAME Specify hyperopt class name which will be used by the
bot.
--hyperopt-path PATH Specify additional lookup path for Hyperopt and
Hyperopt Loss functions.
--eps, --enable-position-stacking
Allow buying the same pair multiple times (position
stacking).
--dmmp, --disable-max-market-positions
Disable applying `max_open_trades` during backtest
(same as setting `max_open_trades` to a very high
number).
--enable-protections, --enableprotections
Enable protections for backtesting.Will slow
backtesting down by a considerable amount, but will
include configured protections
-e INT, --epochs INT Specify number of epochs (default: 100).
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
Specify which parameters to hyperopt. Space-separated
list.
--print-all Print all results, not only the best ones.
--no-color Disable colorization of hyperopt results. May be
useful if you are redirecting output to a file.
--print-json Print output in JSON format.
-j JOBS, --job-workers JOBS
The number of concurrently running jobs for
hyperoptimization (hyperopt worker processes). If -1
(default), all CPUs are used, for -2, all CPUs but one
are used, etc. If 1 is given, no parallel computing
code is used at all.
--random-state INT Set random state to some positive integer for
reproducible hyperopt results.
--min-trades INT Set minimal desired number of trades for evaluations
in the hyperopt optimization path (default: 1).
--hyperopt-loss NAME Specify the class name of the hyperopt loss function
class (IHyperOptLoss). Different functions can
generate completely different results, since the
target for optimization is different. Built-in
Hyperopt-loss-functions are:
ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss,
SharpeHyperOptLoss, SharpeHyperOptLossDaily,
SortinoHyperOptLoss, SortinoHyperOptLossDaily
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
--logfile FILE Log to the file specified. Special values are:
'syslog', 'journald'. See the documentation for more
details.
-V, --version show program's version number and exit
-c PATH, --config PATH
Specify configuration file (default:
`userdir/config.json` or `config.json` whichever
exists). Multiple --config options may be used. Can be
set to `-` to read config from stdin.
-d PATH, --datadir PATH
Path to directory with historical backtesting data.
--userdir PATH, --user-data-dir PATH
Path to userdata directory.
Strategy arguments:
-s NAME, --strategy NAME
Specify strategy class name which will be used by the
bot.
--strategy-path PATH Specify additional strategy lookup path.
```
## Edge commands
To know your trade expectancy and winrate against historical data, you can use Edge.
```
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH]
[-i TIMEFRAME] [--timerange TIMERANGE]
[--max-open-trades INT] [--stake-amount STAKE_AMOUNT]
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
optional arguments:
-h, --help show this help message and exit
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
`1d`).
--timerange TIMERANGE
Specify what timerange of data to use.
--max-open-trades INT
Override the value of the `max_open_trades`
configuration setting.
--stake-amount STAKE_AMOUNT
Override the value of the `stake_amount` configuration
setting.
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
entry and exit).
--stoplosses STOPLOSS_RANGE
Defines a range of stoploss values against which edge
will assess the strategy. The format is "min,max,step"
(without any space). Example:
`--stoplosses=-0.01,-0.1,-0.001`
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
--logfile FILE Log to the file specified. Special values are:
'syslog', 'journald'. See the documentation for more
details.
-V, --version show program's version number and exit
-c PATH, --config PATH
Specify configuration file (default:
`userdir/config.json` or `config.json` whichever
exists). Multiple --config options may be used. Can be
set to `-` to read config from stdin.
-d PATH, --datadir PATH
Path to directory with historical backtesting data.
--userdir PATH, --user-data-dir PATH
Path to userdata directory.
Strategy arguments:
-s NAME, --strategy NAME
Specify strategy class name which will be used by the
bot.
--strategy-path PATH Specify additional strategy lookup path.
```
To understand edge and how to read the results, please read the [edge documentation](edge.md).
## Next step ## Next step
The optimal strategy of the bot will change with time depending of the market trends. The next step is to The optimal strategy of the bot will change with time depending of the market trends. The next step is to

View File

@@ -16,8 +16,7 @@ In some advanced use cases, multiple configuration files can be specified and us
If you used the [Quick start](installation.md/#quick-start) method for installing If you used the [Quick start](installation.md/#quick-start) method for installing
the bot, the installation script should have already created the default configuration file (`config.json`) for you. the bot, the installation script should have already created the default configuration file (`config.json`) for you.
If default configuration file is not created we recommend you to copy and use the `config.json.example` as a template If default configuration file is not created we recommend you to use `freqtrade new-config --config config.json` to generate a basic configuration file.
for your bot configuration.
The Freqtrade configuration file is to be written in the JSON format. The Freqtrade configuration file is to be written in the JSON format.
@@ -41,8 +40,8 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| Parameter | Description | | Parameter | Description |
|------------|-------------| |------------|-------------|
| `max_open_trades` | **Required.** Number of open trades your bot is allowed to have. Only one open trade per pair is possible, so the length of your pairlist is another limitation which can apply. If -1 then it is ignored (i.e. potentially unlimited open trades, limited by the pairlist). [More information below](#configuring-amount-per-trade).<br> **Datatype:** Positive integer or -1. | `max_open_trades` | **Required.** Number of open trades your bot is allowed to have. Only one open trade per pair is possible, so the length of your pairlist is another limitation which can apply. If -1 then it is ignored (i.e. potentially unlimited open trades, limited by the pairlist). [More information below](#configuring-amount-per-trade).<br> **Datatype:** Positive integer or -1.
| `stake_currency` | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String | `stake_currency` | **Required.** Crypto-currency used for trading. <br> **Datatype:** String
| `stake_amount` | **Required.** Amount of crypto-currency your bot will use for each trade. Set it to `"unlimited"` to allow the bot to use all available balance. [More information below](#configuring-amount-per-trade). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Positive float or `"unlimited"`. | `stake_amount` | **Required.** Amount of crypto-currency your bot will use for each trade. Set it to `"unlimited"` to allow the bot to use all available balance. [More information below](#configuring-amount-per-trade). <br> **Datatype:** Positive float or `"unlimited"`.
| `tradable_balance_ratio` | Ratio of the total account balance the bot is allowed to trade. [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.99` 99%).*<br> **Datatype:** Positive float between `0.1` and `1.0`. | `tradable_balance_ratio` | Ratio of the total account balance the bot is allowed to trade. [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.99` 99%).*<br> **Datatype:** Positive float between `0.1` and `1.0`.
| `amend_last_stake_amount` | Use reduced last stake amount if necessary. [More information below](#configuring-amount-per-trade). <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `amend_last_stake_amount` | Use reduced last stake amount if necessary. [More information below](#configuring-amount-per-trade). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `last_stake_amount_min_ratio` | Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if `amend_last_stake_amount` is set to `true`). [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.5`.* <br> **Datatype:** Float (as ratio) | `last_stake_amount_min_ratio` | Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if `amend_last_stake_amount` is set to `true`). [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.5`.* <br> **Datatype:** Float (as ratio)
@@ -50,7 +49,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `timeframe` | The timeframe (former ticker interval) to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String | `timeframe` | The timeframe (former ticker interval) to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String
| `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> **Datatype:** String | `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> **Datatype:** String
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> **Datatype:** Boolean | `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float | `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
| `cancel_open_orders_on_exit` | Cancel open orders when the `/stop` RPC command is issued, `Ctrl+C` is pressed or the bot dies unexpectedly. When set to `true`, this allows you to use `/stop` to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `cancel_open_orders_on_exit` | Cancel open orders when the `/stop` RPC command is issued, `Ctrl+C` is pressed or the bot dies unexpectedly. When set to `true`, this allows you to use `/stop` to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict | `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
@@ -59,21 +58,25 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-custom-positive-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float | `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-custom-positive-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> **Datatype:** Float | `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> **Datatype:** Float
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `fee` | Fee used during backtesting / dry-runs. Should normally not be configured, which has freqtrade fall back to the exchange default fee. Set as ratio (e.g. 0.001 = 0.1%). Fee is applied twice for each trade, once when buying, once when selling. <br> **Datatype:** Float (as ratio)
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer | `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer | `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
| `bid_strategy.price_side` | Select the side of the spread the bot should look at to get the buy rate. [More information below](#buy-price-side).<br> *Defaults to `bid`.* <br> **Datatype:** String (either `ask` or `bid`). | `bid_strategy.price_side` | Select the side of the spread the bot should look at to get the buy rate. [More information below](#buy-price-side).<br> *Defaults to `bid`.* <br> **Datatype:** String (either `ask` or `bid`).
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#buy-price-without-orderbook-enabled). | `bid_strategy.ask_last_balance` | **Required.** Interpolate the bidding price. More information [below](#buy-price-without-orderbook-enabled).
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean | `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean
| `bid_strategy.order_book_top` | Bot will use the top N rate in Order Book Bids to buy. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in [Order Book Bids](#buy-price-with-orderbook-enabled). <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer | `bid_strategy.order_book_top` | Bot will use the top N rate in Order Book Bids to buy. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in [Order Book Bids](#buy-price-with-orderbook-enabled). <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
| `bid_strategy. check_depth_of_market.enabled` | Do not buy if the difference of buy orders and sell orders is met in Order Book. [Check market depth](#check-depth-of-market). <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `bid_strategy. check_depth_of_market.enabled` | Do not buy if the difference of buy orders and sell orders is met in Order Book. [Check market depth](#check-depth-of-market). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. [Check market depth](#check-depth-of-market) <br> *Defaults to `0`.* <br> **Datatype:** Float (as ratio) | `bid_strategy. check_depth_of_market.bids_to_ask_delta` | The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. [Check market depth](#check-depth-of-market) <br> *Defaults to `0`.* <br> **Datatype:** Float (as ratio)
| `ask_strategy.price_side` | Select the side of the spread the bot should look at to get the sell rate. [More information below](#sell-price-side).<br> *Defaults to `ask`.* <br> **Datatype:** String (either `ask` or `bid`). | `ask_strategy.price_side` | Select the side of the spread the bot should look at to get the sell rate. [More information below](#sell-price-side).<br> *Defaults to `ask`.* <br> **Datatype:** String (either `ask` or `bid`).
| `ask_strategy.bid_last_balance` | Interpolate the selling price. More information [below](#sell-price-without-orderbook-enabled).
| `ask_strategy.use_order_book` | Enable selling of open trades using [Order Book Asks](#sell-price-with-orderbook-enabled). <br> **Datatype:** Boolean | `ask_strategy.use_order_book` | Enable selling of open trades using [Order Book Asks](#sell-price-with-orderbook-enabled). <br> **Datatype:** Boolean
| `ask_strategy.order_book_min` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer | `ask_strategy.order_book_min` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
| `ask_strategy.order_book_max` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer | `ask_strategy.order_book_max` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
| `ask_strategy.use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean | `ask_strategy.use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
| `ask_strategy.sell_profit_only` | Wait until the bot makes a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `ask_strategy.sell_profit_only` | Wait until the bot reaches `ask_strategy.sell_profit_offset` before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `ask_strategy.sell_profit_offset` | Sell-signal is only active above this value. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
| `ask_strategy.ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean | `ask_strategy.ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `ask_strategy.ignore_buying_expired_candle_after` | Specifies the number of seconds until a buy signal is no longer used. <br> **Datatype:** Integer
| `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict | `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict
| `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict | `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> **Datatype:** String | `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> **Datatype:** String
@@ -81,20 +84,22 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String | `exchange.key` | API key to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
| `exchange.secret` | API secret to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String | `exchange.secret` | API secret to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
| `exchange.password` | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String | `exchange.password` | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
| `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Not used by VolumePairList (see [below](#pairlists-and-pairlist-handlers)). <br> **Datatype:** List | `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Supports regex pairs as `.*/BTC`. Not used by VolumePairList. [More information](plugins.md#pairlists-and-pairlist-handlers). <br> **Datatype:** List
| `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting (see [below](#pairlists-and-pairlist-handlers)). <br> **Datatype:** List | `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting. [More information](plugins.md#pairlists-and-pairlist-handlers). <br> **Datatype:** List
| `exchange.ccxt_config` | Additional CCXT parameters passed to both ccxt instances (sync and async). This is usually the correct place for ccxt configurations. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict | `exchange.ccxt_config` | Additional CCXT parameters passed to both ccxt instances (sync and async). This is usually the correct place for ccxt configurations. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
| `exchange.ccxt_sync_config` | Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict | `exchange.ccxt_sync_config` | Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict | `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> **Datatype:** Positive Integer | `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> **Datatype:** Positive Integer
| `exchange.skip_pair_validation` | Skip pairlist validation on startup.<br>*Defaults to `false`<br> **Datatype:** Boolean | `exchange.skip_pair_validation` | Skip pairlist validation on startup.<br>*Defaults to `false`<br> **Datatype:** Boolean
| `exchange.skip_open_order_update` | Skips open order updates on startup should the exchange cause problems. Only relevant in live conditions.<br>*Defaults to `false`<br> **Datatype:** Boolean
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation. | `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> **Datatype:** Boolean | `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
| `pairlists` | Define one or more pairlists to be used. [More information below](#pairlists-and-pairlist-handlers). <br>*Defaults to `StaticPairList`.* <br> **Datatype:** List of Dicts | `pairlists` | Define one or more pairlists to be used. [More information](plugins.md#pairlists-and-pairlist-handlers). <br>*Defaults to `StaticPairList`.* <br> **Datatype:** List of Dicts
| `protections` | Define one or more protections to be used. [More information below](#protections). <br> **Datatype:** List of Dicts | `protections` | Define one or more protections to be used. [More information](plugins.md#protections). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** List of Dicts
| `telegram.enabled` | Enable the usage of Telegram. <br> **Datatype:** Boolean | `telegram.enabled` | Enable the usage of Telegram. <br> **Datatype:** Boolean
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String | `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String | `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
| `telegram.balance_dust_level` | Dust-level (in stake currency) - currencies with a balance below this will not be shown by `/balance`. <br> **Datatype:** float
| `webhook.enabled` | Enable usage of Webhook notifications <br> **Datatype:** Boolean | `webhook.enabled` | Enable usage of Webhook notifications <br> **Datatype:** Boolean
| `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String | `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
| `webhook.webhookbuy` | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String | `webhook.webhookbuy` | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
@@ -108,13 +113,14 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `api_server.verbosity` | Logging verbosity. `info` will print all RPC Calls, while "error" will only display errors. <br>**Datatype:** Enum, either `info` or `error`. Defaults to `info`. | `api_server.verbosity` | Logging verbosity. `info` will print all RPC Calls, while "error" will only display errors. <br>**Datatype:** Enum, either `info` or `error`. Defaults to `info`.
| `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String | `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
| `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String | `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
| `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.<br> *Defaults to `freqtrade`*<br> **Datatype:** String
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite:///tradesv3.dryrun.sqlite` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> **Datatype:** String, SQLAlchemy connect string | `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite:///tradesv3.dryrun.sqlite` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> **Datatype:** String, SQLAlchemy connect string
| `initial_state` | Defines the initial application state. More information below. <br>*Defaults to `stopped`.* <br> **Datatype:** Enum, either `stopped` or `running` | `initial_state` | Defines the initial application state. If set to stopped, then the bot has to be explicitly started via `/start` RPC command. <br>*Defaults to `stopped`.* <br> **Datatype:** Enum, either `stopped` or `running`
| `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> **Datatype:** Boolean | `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> **Datatype:** Boolean
| `disable_dataframe_checks` | Disable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. [Strategy Override](#parameters-in-the-strategy).<br> *Defaults to `False`*. <br> **Datatype:** Boolean | `disable_dataframe_checks` | Disable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. [Strategy Override](#parameters-in-the-strategy).<br> *Defaults to `False`*. <br> **Datatype:** Boolean
| `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> **Datatype:** ClassName | `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> **Datatype:** ClassName
| `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> **Datatype:** String | `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> **Datatype:** String
| `internals.process_throttle_secs` | Set the process throttle. Value in second. <br>*Defaults to `5` seconds.* <br> **Datatype:** Positive Integer | `internals.process_throttle_secs` | Set the process throttle, or minimum loop duration for one bot iteration loop. Value in second. <br>*Defaults to `5` seconds.* <br> **Datatype:** Positive Integer
| `internals.heartbeat_interval` | Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. <br>*Defaults to `60` seconds.* <br> **Datatype:** Positive Integer or 0 | `internals.heartbeat_interval` | Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. <br>*Defaults to `60` seconds.* <br> **Datatype:** Positive Integer or 0
| `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> **Datatype:** Boolean | `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> **Datatype:** Boolean
| `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> **Datatype:** String | `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> **Datatype:** String
@@ -134,21 +140,40 @@ Values set in the configuration file always overwrite values set in the strategy
* `trailing_stop_positive` * `trailing_stop_positive`
* `trailing_stop_positive_offset` * `trailing_stop_positive_offset`
* `trailing_only_offset_is_reached` * `trailing_only_offset_is_reached`
* `use_custom_stoploss`
* `process_only_new_candles` * `process_only_new_candles`
* `order_types` * `order_types`
* `order_time_in_force` * `order_time_in_force`
* `stake_currency`
* `stake_amount`
* `unfilledtimeout` * `unfilledtimeout`
* `disable_dataframe_checks` * `disable_dataframe_checks`
* `protections`
* `use_sell_signal` (ask_strategy) * `use_sell_signal` (ask_strategy)
* `sell_profit_only` (ask_strategy) * `sell_profit_only` (ask_strategy)
* `sell_profit_offset` (ask_strategy)
* `ignore_roi_if_buy_signal` (ask_strategy) * `ignore_roi_if_buy_signal` (ask_strategy)
* `ignore_buying_expired_candle_after` (ask_strategy)
### Configuring amount per trade ### Configuring amount per trade
There are several methods to configure how much of the stake currency the bot will use to enter a trade. All methods respect the [available balance configuration](#available-balance) as explained below. There are several methods to configure how much of the stake currency the bot will use to enter a trade. All methods respect the [available balance configuration](#available-balance) as explained below.
#### Minimum trade stake
The minimum stake amount will depend by exchange and pair, and is usually listed in the exchange support pages.
Assuming the minimum tradable amount for XRP/USD is 20 XRP (given by the exchange), and the price is 0.4$.
The minimum stake amount to buy this pair is therefore `20 * 0.6 ~= 12`.
This exchange has also a limit on USD - where all orders must be > 10$ - which however does not apply in this case.
To guarantee safe execution, freqtrade will not allow buying with a stake-amount of 10.1$, instead, it'll make sure that there's enough space to place a stoploss below the pair (+ an offset, defined by `amount_reserve_percent`, which defaults to 5%).
With a stoploss of 10% - we'd therefore end up with a value of ~13.8$ (`12 * (1 + 0.05 + 0.1)`).
To limit this calculation in case of large stoploss values, the calculated minimum stake-limit will never be more than 50% above the real limit.
!!! Warning
Since the limits on exchanges are usually stable and are not updated often, some pairs can show pretty high minimum limits, simply because the price increased a lot since the last limit adjustment by the exchange.
#### Available balance #### Available balance
By default, the bot assumes that the `complete amount - 1%` is at it's disposal, and when using [dynamic stake amount](#dynamic-stake-amount), it will split the complete balance into `max_open_trades` buckets per trade. By default, the bot assumes that the `complete amount - 1%` is at it's disposal, and when using [dynamic stake amount](#dynamic-stake-amount), it will split the complete balance into `max_open_trades` buckets per trade.
@@ -211,11 +236,14 @@ To allow the bot to trade all the available `stake_currency` in your account (mi
"tradable_balance_ratio": 0.99, "tradable_balance_ratio": 0.99,
``` ```
!!! Note !!! Tip "Compounding profits"
This configuration will allow increasing / decreasing stakes depending on the performance of the bot (lower stake if bot is loosing, higher stakes if the bot has a winning record, since higher balances are available). This configuration will allow increasing / decreasing stakes depending on the performance of the bot (lower stake if bot is loosing, higher stakes if the bot has a winning record, since higher balances are available), and will result in profit compounding.
!!! Note "When using Dry-Run Mode" !!! Note "When using Dry-Run Mode"
When using `"stake_amount" : "unlimited",` in combination with Dry-Run, the balance will be simulated starting with a stake of `dry_run_wallet` which will evolve over time. It is therefore important to set `dry_run_wallet` to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency. When using `"stake_amount" : "unlimited",` in combination with Dry-Run, Backtesting or Hyperopt, the balance will be simulated starting with a stake of `dry_run_wallet` which will evolve over time.
It is therefore important to set `dry_run_wallet` to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency.
--8<-- "includes/pricing.md"
### Understand minimal_roi ### Understand minimal_roi
@@ -240,41 +268,35 @@ If it is not set in either Strategy or Configuration, a default of 1000% `{"0":
!!! Note "Special case to forcesell after a specific time" !!! Note "Special case to forcesell after a specific time"
A special case presents using `"<N>": -1` as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell. A special case presents using `"<N>": -1` as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.
### Understand stoploss
Go to the [stoploss documentation](stoploss.md) for more details.
### Understand trailing stoploss
Go to the [trailing stoploss Documentation](stoploss.md#trailing-stop-loss) for details on trailing stoploss.
### Understand initial_state
The `initial_state` configuration parameter is an optional field that defines the initial application state.
Possible values are `running` or `stopped`. (default=`running`)
If the value is `stopped` the bot has to be started with `/start` first.
### Understand forcebuy_enable ### Understand forcebuy_enable
The `forcebuy_enable` configuration parameter enables the usage of forcebuy commands via Telegram. The `forcebuy_enable` configuration parameter enables the usage of forcebuy commands via Telegram and REST API.
This is disabled for security reasons by default, and will show a warning message on startup if enabled. For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled.
For example, you can send `/forcebuy ETH/BTC` Telegram command when this feature if enabled to the bot, For example, you can send `/forcebuy ETH/BTC` to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
who then buys the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
This can be dangerous with some strategies, so use with care. This can be dangerous with some strategies, so use with care.
See [the telegram documentation](telegram-usage.md) for details on usage. See [the telegram documentation](telegram-usage.md) for details on usage.
### Understand process_throttle_secs ### Ignoring expired candles
The `process_throttle_secs` configuration parameter is an optional field that defines in seconds how long the bot should wait When working with larger timeframes (for example 1h or more) and using a low `max_open_trades` value, the last candle can be processed as soon as a trade slot becomes available. When processing the last candle, this can lead to a situation where it may not be desirable to use the buy signal on that candle. For example, when using a condition in your strategy where you use a cross-over, that point may have passed too long ago for you to start a trade on it.
before asking the strategy if we should buy or a sell an asset. After each wait period, the strategy is asked again for
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or In these situations, you can enable the functionality to ignore candles that are beyond a specified period by setting `ask_strategy.ignore_buying_expired_candle_after` to a positive number, indicating the number of seconds after which the buy signal becomes expired.
the static list of pairs) if we should buy.
For example, if your strategy is using a 1h timeframe, and you only want to buy within the first 5 minutes when a new candle comes in, you can add the following configuration to your strategy:
``` json
"ask_strategy":{
"ignore_buying_expired_candle_after": 300,
"price_side": "bid",
// ...
},
```
### Understand order_types ### Understand order_types
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`, `emergencysell`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds. The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`, `emergencysell`, `forcesell`, `forcebuy`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
This allows to buy using limit orders, sell using This allows to buy using limit orders, sell using
limit-orders, and create stoplosses using market orders. It also allows to set the limit-orders, and create stoplosses using market orders. It also allows to set the
@@ -286,7 +308,7 @@ the buy order is fulfilled.
If this is configured, the following 4 values (`buy`, `sell`, `stoploss` and If this is configured, the following 4 values (`buy`, `sell`, `stoploss` and
`stoploss_on_exchange`) need to be present, otherwise the bot will fail to start. `stoploss_on_exchange`) need to be present, otherwise the bot will fail to start.
For information on (`emergencysell`,`stoploss_on_exchange`,`stoploss_on_exchange_interval`,`stoploss_on_exchange_limit_ratio`) please see stop loss documentation [stop loss on exchange](stoploss.md) For information on (`emergencysell`,`forcesell`, `forcebuy`, `stoploss_on_exchange`,`stoploss_on_exchange_interval`,`stoploss_on_exchange_limit_ratio`) please see stop loss documentation [stop loss on exchange](stoploss.md)
Syntax for Strategy: Syntax for Strategy:
@@ -295,6 +317,8 @@ order_types = {
"buy": "limit", "buy": "limit",
"sell": "limit", "sell": "limit",
"emergencysell": "market", "emergencysell": "market",
"forcebuy": "market",
"forcesell": "market",
"stoploss": "market", "stoploss": "market",
"stoploss_on_exchange": False, "stoploss_on_exchange": False,
"stoploss_on_exchange_interval": 60, "stoploss_on_exchange_interval": 60,
@@ -309,6 +333,8 @@ Configuration:
"buy": "limit", "buy": "limit",
"sell": "limit", "sell": "limit",
"emergencysell": "market", "emergencysell": "market",
"forcebuy": "market",
"forcesell": "market",
"stoploss": "market", "stoploss": "market",
"stoploss_on_exchange": false, "stoploss_on_exchange": false,
"stoploss_on_exchange_interval": 60 "stoploss_on_exchange_interval": 60
@@ -409,26 +435,6 @@ This configuration enables binance, as well as rate limiting to avoid bans from
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings. Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings.
We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step. We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that `"enableRateLimit"` is enabled and increase the `"rateLimit"` parameter step by step.
#### Advanced Freqtrade Exchange configuration
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behaviours.
Available options are listed in the exchange-class as `_ft_has_default`.
For example, to test the order type `FOK` with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call):
```json
"exchange": {
"name": "kraken",
"_ft_has_params": {
"order_time_in_force": ["gtc", "fok"],
"ohlcv_candle_limit": 200
}
```
!!! Warning
Please make sure to fully understand the impacts of these settings before modifying them.
### What values can be used for fiat_display_currency? ### What values can be used for fiat_display_currency?
The `fiat_display_currency` configuration parameter sets the base currency to use for the The `fiat_display_currency` configuration parameter sets the base currency to use for the
@@ -448,137 +454,7 @@ The valid values are:
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT" "BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
``` ```
## Prices used for orders ## Using Dry-run mode
Prices for regular orders can be controlled via the parameter structures `bid_strategy` for buying and `ask_strategy` for selling.
Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.
!!! Note
Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function `fetch_order_book()`, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's `fetch_ticker()`/`fetch_tickers()` functions. Refer to the ccxt library [documentation](https://github.com/ccxt/ccxt/wiki/Manual#market-data) for more details.
!!! Warning "Using market orders"
Please read the section [Market order pricing](#market-order-pricing) section when using market orders.
### Buy price
#### Check depth of market
When check depth of market is enabled (`bid_strategy.check_depth_of_market.enabled=True`), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.
Orderbook `bid` (buy) side depth is then divided by the orderbook `ask` (sell) side depth and the resulting delta is compared to the value of the `bid_strategy.check_depth_of_market.bids_to_ask_delta` parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.
!!! Note
A delta value below 1 means that `ask` (sell) orderbook side depth is greater than the depth of the `bid` (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).
#### Buy price side
The configuration setting `bid_strategy.price_side` defines the side of the spread the bot looks for when buying.
The following displays an orderbook.
``` explanation
...
103
102
101 # ask
-------------Current spread
99 # bid
98
97
...
```
If `bid_strategy.price_side` is set to `"bid"`, then the bot will use 99 as buying price.
In line with that, if `bid_strategy.price_side` is set to `"ask"`, then the bot will use 101 as buying price.
Using `ask` price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary.
Taker fees instead of maker fees will most likely apply even when using limit buy orders.
Also, prices at the "ask" side of the spread are higher than prices at the "bid" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).
#### Buy price with Orderbook enabled
When buying with the orderbook enabled (`bid_strategy.use_order_book=True`), Freqtrade fetches the `bid_strategy.order_book_top` entries from the orderbook and then uses the entry specified as `bid_strategy.order_book_top` on the configured side (`bid_strategy.price_side`) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
#### Buy price without Orderbook enabled
The following section uses `side` as the configured `bid_strategy.price_side`.
When not using orderbook (`bid_strategy.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's below the `last` traded price from the ticker. Otherwise (when the `side` price is above the `last` price), it calculates a rate between `side` and `last` price.
The `bid_strategy.ask_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the `last` price and values between those interpolate between ask and last price.
### Sell price
#### Sell price side
The configuration setting `ask_strategy.price_side` defines the side of the spread the bot looks for when selling.
The following displays an orderbook:
``` explanation
...
103
102
101 # ask
-------------Current spread
99 # bid
98
97
...
```
If `ask_strategy.price_side` is set to `"ask"`, then the bot will use 101 as selling price.
In line with that, if `ask_strategy.price_side` is set to `"bid"`, then the bot will use 99 as selling price.
#### Sell price with Orderbook enabled
When selling with the orderbook enabled (`ask_strategy.use_order_book=True`), Freqtrade fetches the `ask_strategy.order_book_max` entries in the orderbook. Then each of the orderbook steps between `ask_strategy.order_book_min` and `ask_strategy.order_book_max` on the configured orderbook side are validated for a profitable sell-possibility based on the strategy configuration (`minimal_roi` conditions) and the sell order is placed at the first profitable spot.
!!! Note
Using `order_book_max` higher than `order_book_min` only makes sense when ask_strategy.price_side is set to `"ask"`.
The idea here is to place the sell order early, to be ahead in the queue.
A fixed slot (mirroring `bid_strategy.order_book_top`) can be defined by setting `ask_strategy.order_book_min` and `ask_strategy.order_book_max` to the same number.
!!! Warning "Order_book_max > 1 - increased risks for stoplosses!"
Using `ask_strategy.order_book_max` higher than 1 will increase the risk the stoploss on exchange is cancelled too early, since an eventual [stoploss on exchange](#understand-order_types) will be cancelled as soon as the order is placed.
Also, the sell order will remain on the exchange for `unfilledtimeout.sell` (or until it's filled) - which can lead to missed stoplosses (with or without using stoploss on exchange).
!!! Warning "Order_book_max > 1 in dry-run"
Using `ask_strategy.order_book_max` higher than 1 will result in improper dry-run results (significantly better than real orders executed on exchange), since dry-run assumes orders to be filled almost instantly.
It is therefore advised to not use this setting for dry-runs.
#### Sell price without Orderbook enabled
When not using orderbook (`ask_strategy.use_order_book=False`), the price at the `ask_strategy.price_side` side (defaults to `"ask"`) from the ticker will be used as the sell price.
### Market order pricing
When using market orders, prices should be configured to use the "correct" side of the orderbook to allow realistic pricing detection.
Assuming both buy and sell are using market orders, a configuration similar to the following might be used
``` jsonc
"order_types": {
"buy": "market",
"sell": "market"
// ...
},
"bid_strategy": {
"price_side": "ask",
// ...
},
"ask_strategy":{
"price_side": "bid",
// ...
},
```
Obviously, if only one side is using limit orders, different pricing combinations can be used.
--8<-- "includes/pairlists.md"
--8<-- "includes/protections.md"
## Switch to Dry-run mode
We recommend starting the bot in the Dry-run mode to see how your bot will We recommend starting the bot in the Dry-run mode to see how your bot will
behave and what is the performance of your strategy. In the Dry-run mode the behave and what is the performance of your strategy. In the Dry-run mode the
@@ -611,9 +487,10 @@ Once you will be happy with your bot performance running in the Dry-run mode, yo
### Considerations for dry-run ### Considerations for dry-run
* API-keys may or may not be provided. Only Read-Only operations (i.e. operations that do not alter account state) on the exchange are performed in the dry-run mode. * API-keys may or may not be provided. Only Read-Only operations (i.e. operations that do not alter account state) on the exchange are performed in dry-run mode.
* Wallets (`/balance`) are simulated. * Wallets (`/balance`) are simulated based on `dry_run_wallet`.
* Orders are simulated, and will not be posted to the exchange. * Orders are simulated, and will not be posted to the exchange.
* Orders are assumed to fill immediately, and will never time out.
* In combination with `stoploss_on_exchange`, the stop_loss price is assumed to be filled. * In combination with `stoploss_on_exchange`, the stop_loss price is assumed to be filled.
* Open orders (not trades, which are stored in the database) are reset on bot restart. * Open orders (not trades, which are stored in the database) are reset on bot restart.
@@ -671,32 +548,6 @@ export HTTPS_PROXY="http://addr:port"
freqtrade freqtrade
``` ```
## Embedding Strategies
Freqtrade provides you with with an easy way to embed the strategy into your configuration file.
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
in your chosen config file.
### Encoding a string as BASE64
This is a quick example, how to generate the BASE64 string in python
```python
from base64 import urlsafe_b64encode
with open(file, 'r') as f:
content = f.read()
content = urlsafe_b64encode(content.encode('utf-8'))
```
The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following
```json
"strategy": "NameOfStrategy:BASE64String"
```
Please ensure that 'NameOfStrategy' is identical to the strategy name!
## Next step ## Next step
Now you have configured your config.json, the next step is to [start your bot](bot-usage.md). Now you have configured your config.json, the next step is to [start your bot](bot-usage.md).

View File

@@ -264,7 +264,19 @@ If you are using Binance for example:
```bash ```bash
mkdir -p user_data/data/binance mkdir -p user_data/data/binance
cp freqtrade/tests/testdata/pairs.json user_data/data/binance cp tests/testdata/pairs.json user_data/data/binance
```
If you your configuration directory `user_data` was made by docker, you may get the following error:
```
cp: cannot create regular file 'user_data/data/binance/pairs.json': Permission denied
```
You can fix the permissions of your user-data directory as follows:
```
sudo chown -R $UID:$GID user_data
``` ```
The format of the `pairs.json` file is a simple json list. The format of the `pairs.json` file is a simple json list.
@@ -308,10 +320,13 @@ Since this data is large by default, the files use gzip by default. They are sto
To use this mode, simply add `--dl-trades` to your call. This will swap the download method to download trades, and resamples the data locally. To use this mode, simply add `--dl-trades` to your call. This will swap the download method to download trades, and resamples the data locally.
!!! Warning "do not use"
You should not use this unless you're a kraken user. Most other exchanges provide OHLCV data with sufficient history.
Example call: Example call:
```bash ```bash
freqtrade download-data --exchange binance --pairs XRP/ETH ETH/BTC --days 20 --dl-trades freqtrade download-data --exchange kraken --pairs XRP/EUR ETH/EUR --days 20 --dl-trades
``` ```
!!! Note !!! Note

View File

@@ -2,7 +2,7 @@
This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running. This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel on [discord](https://discord.gg/MA9v74M) or [slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA) where you can ask questions. All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel on [discord](https://discord.gg/MA9v74M) or [slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw) where you can ask questions.
## Documentation ## Documentation
@@ -177,7 +177,7 @@ In `VolumePairList`, this implements different methods of sorting, does early va
### Protections ### Protections
Best read the [Protection documentation](configuration.md#protections) to understand protections. Best read the [Protection documentation](plugins.md#protections) to understand protections.
This Guide is directed towards Developers who want to develop a new protection. This Guide is directed towards Developers who want to develop a new protection.
No protection should use datetime directly, but use the provided `date_now` variable for date calculations. This preserves the ability to backtest protections. No protection should use datetime directly, but use the provided `date_now` variable for date calculations. This preserves the ability to backtest protections.

View File

@@ -1,201 +0,0 @@
## Freqtrade with docker without docker-compose
!!! Warning
The below documentation is provided for completeness and assumes that you are familiar with running docker containers. If you're just starting out with Docker, we recommend to follow the [Quickstart](docker.md) instructions.
### Download the official Freqtrade docker image
Pull the image from docker hub.
Branches / tags available can be checked out on [Dockerhub tags page](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
```bash
docker pull freqtradeorg/freqtrade:stable
# Optionally tag the repository so the run-commands remain shorter
docker tag freqtradeorg/freqtrade:stable freqtrade
```
To update the image, simply run the above commands again and restart your running container.
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
!!! Note "Docker image update frequency"
The official docker images with tags `stable`, `develop` and `latest` are automatically rebuild once a week to keep the base image up-to-date.
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
### Prepare the configuration files
Even though you will use docker, you'll still need some files from the github repository.
#### Clone the git repository
Linux/Mac/Windows with WSL
```bash
git clone https://github.com/freqtrade/freqtrade.git
```
Windows with docker
```bash
git clone --config core.autocrlf=input https://github.com/freqtrade/freqtrade.git
```
#### Copy `config.json.example` to `config.json`
```bash
cd freqtrade
cp -n config.json.example config.json
```
> To understand the configuration options, please refer to the [Bot Configuration](configuration.md) page.
#### Create your database file
=== "Dry-Run"
``` bash
touch tradesv3.dryrun.sqlite
```
=== "Production"
``` bash
touch tradesv3.sqlite
```
!!! Warning "Database File Path"
Make sure to use the path to the correct database file when starting the bot in Docker.
### Build your own Docker image
Best start by pulling the official docker image from dockerhub as explained [here](#download-the-official-docker-image) to speed up building.
To add additional libraries to your docker image, best check out [Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/docker/Dockerfile.technical) which adds the [technical](https://github.com/freqtrade/technical) module to the image.
```bash
docker build -t freqtrade -f docker/Dockerfile.technical .
```
If you are developing using Docker, use `docker/Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
```bash
docker build -f docker/Dockerfile.develop -t freqtrade-dev .
```
!!! Warning "Include your config file manually"
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see [5. Run a restartable docker image](#run-a-restartable-docker-image)") to keep it between updates.
#### Verify the Docker image
After the build process you can verify that the image was created with:
```bash
docker images
```
The output should contain the freqtrade image.
### Run the Docker image
You can run a one-off container that is immediately deleted upon exiting with the following command (`config.json` must be in the current working directory):
```bash
docker run --rm -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
```
!!! Warning
In this example, the database will be created inside the docker instance and will be lost when you refresh your image.
#### Adjust timezone
By default, the container will use UTC timezone.
If you would like to change the timezone use the following commands:
=== "Linux"
``` bash
-v /etc/timezone:/etc/timezone:ro
# Complete command:
docker run --rm -v /etc/timezone:/etc/timezone:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
```
=== "MacOS"
```bash
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
```
!!! Note "MacOS Issues"
The OSX Docker versions after 17.09.1 have a known issue whereby `/etc/localtime` cannot be shared causing Docker to not start.<br>
A work-around for this is to start with the MacOS command above
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
### Run a restartable docker image
To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
#### 1. Move your config file and database
The following will assume that you place your configuration / database files to `~/.freqtrade`, which is a hidden directory in your home directory. Feel free to use a different directory and replace the directory in the upcomming commands.
```bash
mkdir ~/.freqtrade
mv config.json ~/.freqtrade
mv tradesv3.sqlite ~/.freqtrade
```
#### 2. Run the docker image
```bash
docker run -d \
--name freqtrade \
-v ~/.freqtrade/config.json:/freqtrade/config.json \
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
```
!!! Note
When using docker, it's best to specify `--db-url` explicitly to ensure that the database URL and the mounted database file match.
!!! Note
All available bot command line parameters can be added to the end of the `docker run` command.
!!! Note
You can define a [restart policy](https://docs.docker.com/config/containers/start-containers-automatically/) in docker. It can be useful in some cases to use the `--restart unless-stopped` flag (crash of freqtrade or reboot of your system).
### Monitor your Docker instance
You can use the following commands to monitor and manage your container:
```bash
docker logs freqtrade
docker logs -f freqtrade
docker restart freqtrade
docker stop freqtrade
docker start freqtrade
```
For more information on how to operate Docker, please refer to the [official Docker documentation](https://docs.docker.com/).
!!! Note
You do not need to rebuild the image for configuration changes, it will suffice to edit `config.json` and restart the container.
### Backtest with docker
The following assumes that the download/setup of the docker image have been completed successfully.
Also, backtest-data should be available at `~/.freqtrade/user_data/`.
```bash
docker run -d \
--name freqtrade \
-v /etc/localtime:/etc/localtime:ro \
-v ~/.freqtrade/config.json:/freqtrade/config.json \
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
-v ~/.freqtrade/user_data/:/freqtrade/user_data/ \
freqtrade backtesting --strategy AwsomelyProfitableStrategy
```
Head over to the [Backtesting Documentation](backtesting.md) for more details.
!!! Note
Additional bot command line parameters can be appended after the image name (`freqtrade` in the above example).

View File

@@ -1,5 +1,7 @@
# Using Freqtrade with Docker # Using Freqtrade with Docker
This page explains how to run the bot with Docker. It is not meant to work out of the box. You'll still need to read through the documentation and understand how to properly configure it.
## Install Docker ## Install Docker
Start by downloading and installing Docker CE for your platform: Start by downloading and installing Docker CE for your platform:
@@ -8,9 +10,7 @@ Start by downloading and installing Docker CE for your platform:
* [Windows](https://docs.docker.com/docker-for-windows/install/) * [Windows](https://docs.docker.com/docker-for-windows/install/)
* [Linux](https://docs.docker.com/install/) * [Linux](https://docs.docker.com/install/)
Optionally, [`docker-compose`](https://docs.docker.com/compose/install/) should be installed and available to follow the [docker quick start guide](#docker-quick-start). To simplify running freqtrade, please install [`docker-compose`](https://docs.docker.com/compose/install/) should be installed and available to follow the below [docker quick start guide](#docker-quick-start).
Once you have Docker installed, simply prepare the config file (e.g. `config.json`) and run the image for `freqtrade` as explained below.
## Freqtrade with docker-compose ## Freqtrade with docker-compose
@@ -71,19 +71,20 @@ The last 2 steps in the snippet create the directory with `user_data`, as well a
!!! Question "How to edit the bot configuration?" !!! Question "How to edit the bot configuration?"
You can edit the configuration at any time, which is available as `user_data/config.json` (within the directory `ft_userdata`) when using the above configuration. You can edit the configuration at any time, which is available as `user_data/config.json` (within the directory `ft_userdata`) when using the above configuration.
You can also change the both Strategy and commands by editing the `docker-compose.yml` file. You can also change the both Strategy and commands by editing the command section of your `docker-compose.yml` file.
#### Adding a custom strategy #### Adding a custom strategy
1. The configuration is now available as `user_data/config.json` 1. The configuration is now available as `user_data/config.json`
2. Copy a custom strategy to the directory `user_data/strategies/` 2. Copy a custom strategy to the directory `user_data/strategies/`
3. add the Strategy' class name to the `docker-compose.yml` file 3. Add the Strategy' class name to the `docker-compose.yml` file
The `SampleStrategy` is run by default. The `SampleStrategy` is run by default.
!!! Warning "`SampleStrategy` is just a demo!" !!! Warning "`SampleStrategy` is just a demo!"
The `SampleStrategy` is there for your reference and give you ideas for your own strategy. The `SampleStrategy` is there for your reference and give you ideas for your own strategy.
Please always backtest the strategy and use dry-run for some time before risking real money! Please always backtest your strategy and use dry-run for some time before risking real money!
You will find more information about Strategy development in the [Strategy documentation](strategy-customization.md).
Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above). Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above).
@@ -91,18 +92,26 @@ Once this is done, you're ready to launch the bot in trading mode (Dry-run or Li
docker-compose up -d docker-compose up -d
``` ```
!!! Warning "Default configuration"
While the configuration generated will be mostly functional, you will still need to verify that all options correspond to what you want (like Pricing, pairlist, ...) before starting the bot.
#### Monitoring the bot
You can check for running instances with `docker-compose ps`.
This should list the service `freqtrade` as `running`. If that's not the case, best check the logs (see next point).
#### Docker-compose logs #### Docker-compose logs
Logs will be located at: `user_data/logs/freqtrade.log`. Logs will be written to: `user_data/logs/freqtrade.log`.
You can check the latest log with the command `docker-compose logs -f`. You can also check the latest log with the command `docker-compose logs -f`.
#### Database #### Database
The database will be at: `user_data/tradesv3.sqlite` The database will be located at: `user_data/tradesv3.sqlite`
#### Updating freqtrade with docker-compose #### Updating freqtrade with docker-compose
To update freqtrade when using `docker-compose` is as simple as running the following 2 commands: Updating freqtrade when using `docker-compose` is as simple as running the following 2 commands:
``` bash ``` bash
# Download the latest image # Download the latest image
@@ -120,10 +129,10 @@ This will first pull the latest image, and will then restart the container with
Advanced users may edit the docker-compose file further to include all possible options or arguments. Advanced users may edit the docker-compose file further to include all possible options or arguments.
All possible freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`. All freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`.
!!! Note "`docker-compose run --rm`" !!! Note "`docker-compose run --rm`"
Including `--rm` will clean up the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command). Including `--rm` will remove the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command).
#### Example: Download data with docker-compose #### Example: Download data with docker-compose
@@ -172,19 +181,19 @@ docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p B
The output will be stored in the `user_data/plot` directory, and can be opened with any modern browser. The output will be stored in the `user_data/plot` directory, and can be opened with any modern browser.
## Data analayis using docker compose ## Data analysis using docker compose
Freqtrade provides a docker-compose file which starts up a jupyter lab server. Freqtrade provides a docker-compose file which starts up a jupyter lab server.
You can run this server using the following command: You can run this server using the following command:
``` bash ``` bash
docker-compose --rm -f docker/docker-compose-jupyter.yml up docker-compose -f docker/docker-compose-jupyter.yml up
``` ```
This will create a dockercontainer running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`. This will create a docker-container running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`.
Please use the link that's printed in the console after startup for simplified login. Please use the link that's printed in the console after startup for simplified login.
Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) uptodate. Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) up-to-date.
``` bash ``` bash
docker-compose -f docker/docker-compose-jupyter.yml build --no-cache docker-compose -f docker/docker-compose-jupyter.yml build --no-cache

View File

@@ -1,6 +1,6 @@
# Edge positioning # Edge positioning
The `Edge Positioning` module uses probability to calculate your win rate and risk reward ration. It will use these statistics to control your strategy trade entry points, position side and, stoploss. The `Edge Positioning` module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss.
!!! Warning !!! Warning
`Edge positioning` is not compatible with dynamic (volume-based) whitelist. `Edge positioning` is not compatible with dynamic (volume-based) whitelist.
@@ -9,6 +9,7 @@ The `Edge Positioning` module uses probability to calculate your win rate and ri
`Edge Positioning` only considers *its own* buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file. `Edge Positioning` only considers *its own* buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file.
`Edge Positioning` improves the performance of some trading strategies and *decreases* the performance of others. `Edge Positioning` improves the performance of some trading strategies and *decreases* the performance of others.
## Introduction ## Introduction
Trading strategies are not perfect. They are frameworks that are susceptible to the market and its indicators. Because the market is not at all predictable, sometimes a strategy will win and sometimes the same strategy will lose. Trading strategies are not perfect. They are frameworks that are susceptible to the market and its indicators. Because the market is not at all predictable, sometimes a strategy will win and sometimes the same strategy will lose.
@@ -55,7 +56,7 @@ Similarly, we can discover the set of losing trades $T_{lose}$ as follows:
$$ T_{lose} = \{o \in O | o \leq 0\} $$ $$ T_{lose} = \{o \in O | o \leq 0\} $$
!!! Example !!! Example
In a section where a strategy made three transactions $O = \{3.5, -1, 15, 0\}$:<br> In a section where a strategy made four transactions $O = \{3.5, -1, 15, 0\}$:<br>
$T_{win} = \{3.5, 15\}$<br> $T_{win} = \{3.5, 15\}$<br>
$T_{lose} = \{-1, 0\}$<br> $T_{lose} = \{-1, 0\}$<br>
@@ -206,7 +207,61 @@ Let's say the stake currency is **ETH** and there is $10$ **ETH** on the wallet.
- The strategy detects a sell signal in the **XLM/ETH** market. The bot exits **Trade 1** for a profit of $1$ **ETH**. The total capital in the wallet becomes $11$ **ETH** and the available capital for trading becomes $5.5$ **ETH**. - The strategy detects a sell signal in the **XLM/ETH** market. The bot exits **Trade 1** for a profit of $1$ **ETH**. The total capital in the wallet becomes $11$ **ETH** and the available capital for trading becomes $5.5$ **ETH**.
- **Trade 4** The strategy detects a new buy signal int the **XLM/ETH** market. `Edge Positioning` calculates the stoploss of $2%$, and the position size of $0.055 / 0.02 = 2.75$ **ETH**. - **Trade 4** The strategy detects a new buy signal int the **XLM/ETH** market. `Edge Positioning` calculates the stoploss of $2\%$, and the position size of $0.055 / 0.02 = 2.75$ **ETH**.
## Edge command reference
```
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH]
[-i TIMEFRAME] [--timerange TIMERANGE]
[--max-open-trades INT] [--stake-amount STAKE_AMOUNT]
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
optional arguments:
-h, --help show this help message and exit
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
`1d`).
--timerange TIMERANGE
Specify what timerange of data to use.
--max-open-trades INT
Override the value of the `max_open_trades`
configuration setting.
--stake-amount STAKE_AMOUNT
Override the value of the `stake_amount` configuration
setting.
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
entry and exit).
--stoplosses STOPLOSS_RANGE
Defines a range of stoploss values against which edge
will assess the strategy. The format is "min,max,step"
(without any space). Example:
`--stoplosses=-0.01,-0.1,-0.001`
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
--logfile FILE Log to the file specified. Special values are:
'syslog', 'journald'. See the documentation for more
details.
-V, --version show program's version number and exit
-c PATH, --config PATH
Specify configuration file (default:
`userdir/config.json` or `config.json` whichever
exists). Multiple --config options may be used. Can be
set to `-` to read config from stdin.
-d PATH, --datadir PATH
Path to directory with historical backtesting data.
--userdir PATH, --user-data-dir PATH
Path to userdata directory.
Strategy arguments:
-s NAME, --strategy NAME
Specify strategy class name which will be used by the
bot.
--strategy-path PATH Specify additional strategy lookup path.
```
## Configurations ## Configurations

View File

@@ -40,6 +40,10 @@ Due to the heavy rate-limiting applied by Kraken, the following configuration se
}, },
``` ```
!!! Warning "Downloading data from kraken"
Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine.
It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient.
## Bittrex ## Bittrex
### Order types ### Order types
@@ -92,9 +96,6 @@ To use subaccounts with FTX, you need to edit the configuration and add the foll
} }
``` ```
!!! Note
Older versions of freqtrade may require this key to be added to `"ccxt_async_config"` as well.
## All exchanges ## All exchanges
Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys. Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.
@@ -117,3 +118,23 @@ Whether your exchange returns incomplete candles or not can be checked using [th
Due to the danger of repainting, Freqtrade does not allow you to use this incomplete candle. Due to the danger of repainting, Freqtrade does not allow you to use this incomplete candle.
However, if it is based on the need for the latest price for your strategy - then this requirement can be acquired using the [data provider](strategy-customization.md#possible-options-for-dataprovider) from within the strategy. However, if it is based on the need for the latest price for your strategy - then this requirement can be acquired using the [data provider](strategy-customization.md#possible-options-for-dataprovider) from within the strategy.
### Advanced Freqtrade Exchange configuration
Advanced options can be configured using the `_ft_has_params` setting, which will override Defaults and exchange-specific behavior.
Available options are listed in the exchange-class as `_ft_has_default`.
For example, to test the order type `FOK` with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call):
```json
"exchange": {
"name": "kraken",
"_ft_has_params": {
"order_time_in_force": ["gtc", "fok"],
"ohlcv_candle_limit": 200
}
```
!!! Warning
Please make sure to fully understand the impacts of these settings before modifying them.

View File

@@ -38,12 +38,11 @@ you can't say much from few trades.
### Id like to make changes to the config. Can I do that without having to kill the bot? ### Id like to make changes to the config. Can I do that without having to kill the bot?
Yes. You can edit your config, use the `/stop` command in Telegram, followed by `/reload_config` and the bot will run with the new config. Yes. You can edit your config and use the `/reload_config` command to reload the configuration. The bot will stop, reload the configuration and strategy and will restart with the new configuration and strategy.
### I want to improve the bot with a new strategy ### I want to improve the bot with a new strategy
That's great. We have a nice backtesting and hyperoptimization setup. See That's great. We have a nice backtesting and hyperoptimization setup. See the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-commands).
### Is there a setting to only SELL the coins being held and not perform anymore BUYS? ### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
@@ -143,7 +142,7 @@ freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossD
### Why does it take a long time to run hyperopt? ### Why does it take a long time to run hyperopt?
* Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA) - or the Freqtrade [discord community](https://discord.gg/X89cVG). While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you. * Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw) - or the Freqtrade [discord community](https://discord.gg/X89cVG). While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you.
* If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers: * If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers:

View File

@@ -32,6 +32,111 @@ source .env/bin/activate
pip install -r requirements-hyperopt.txt pip install -r requirements-hyperopt.txt
``` ```
## Hyperopt command reference
```
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH]
[-i TIMEFRAME] [--timerange TIMERANGE]
[--data-format-ohlcv {json,jsongz,hdf5}]
[--max-open-trades INT]
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
[--dmmp] [--enable-protections]
[--dry-run-wallet DRY_RUN_WALLET] [-e INT]
[--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
[--print-all] [--no-color] [--print-json] [-j JOBS]
[--random-state INT] [--min-trades INT]
[--hyperopt-loss NAME]
optional arguments:
-h, --help show this help message and exit
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
`1d`).
--timerange TIMERANGE
Specify what timerange of data to use.
--data-format-ohlcv {json,jsongz,hdf5}
Storage format for downloaded candle (OHLCV) data.
(default: `None`).
--max-open-trades INT
Override the value of the `max_open_trades`
configuration setting.
--stake-amount STAKE_AMOUNT
Override the value of the `stake_amount` configuration
setting.
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
entry and exit).
--hyperopt NAME Specify hyperopt class name which will be used by the
bot.
--hyperopt-path PATH Specify additional lookup path for Hyperopt and
Hyperopt Loss functions.
--eps, --enable-position-stacking
Allow buying the same pair multiple times (position
stacking).
--dmmp, --disable-max-market-positions
Disable applying `max_open_trades` during backtest
(same as setting `max_open_trades` to a very high
number).
--enable-protections, --enableprotections
Enable protections for backtesting.Will slow
backtesting down by a considerable amount, but will
include configured protections
--dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET
Starting balance, used for backtesting / hyperopt and
dry-runs.
-e INT, --epochs INT Specify number of epochs (default: 100).
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
Specify which parameters to hyperopt. Space-separated
list.
--print-all Print all results, not only the best ones.
--no-color Disable colorization of hyperopt results. May be
useful if you are redirecting output to a file.
--print-json Print output in JSON format.
-j JOBS, --job-workers JOBS
The number of concurrently running jobs for
hyperoptimization (hyperopt worker processes). If -1
(default), all CPUs are used, for -2, all CPUs but one
are used, etc. If 1 is given, no parallel computing
code is used at all.
--random-state INT Set random state to some positive integer for
reproducible hyperopt results.
--min-trades INT Set minimal desired number of trades for evaluations
in the hyperopt optimization path (default: 1).
--hyperopt-loss NAME Specify the class name of the hyperopt loss function
class (IHyperOptLoss). Different functions can
generate completely different results, since the
target for optimization is different. Built-in
Hyperopt-loss-functions are:
ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss,
SharpeHyperOptLoss, SharpeHyperOptLossDaily,
SortinoHyperOptLoss, SortinoHyperOptLossDaily
Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
--logfile FILE Log to the file specified. Special values are:
'syslog', 'journald'. See the documentation for more
details.
-V, --version show program's version number and exit
-c PATH, --config PATH
Specify configuration file (default:
`userdir/config.json` or `config.json` whichever
exists). Multiple --config options may be used. Can be
set to `-` to read config from stdin.
-d PATH, --datadir PATH
Path to directory with historical backtesting data.
--userdir PATH, --user-data-dir PATH
Path to userdata directory.
Strategy arguments:
-s NAME, --strategy NAME
Specify strategy class name which will be used by the
bot.
--strategy-path PATH Specify additional strategy lookup path.
```
## Prepare Hyperopting ## Prepare Hyperopting
Before we start digging into Hyperopt, we recommend you to take a look at Before we start digging into Hyperopt, we recommend you to take a look at
@@ -60,7 +165,7 @@ Depending on the space you want to optimize, only some of the below are required
* fill `sell_indicator_space` - for sell signal optimization * fill `sell_indicator_space` - for sell signal optimization
!!! Note !!! Note
`populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work. `populate_indicators` needs to create all indicators any of the spaces may use, otherwise hyperopt will not work.
Optional in hyperopt - can also be loaded from a strategy (recommended): Optional in hyperopt - can also be loaded from a strategy (recommended):
@@ -178,7 +283,7 @@ So let's write the buy strategy using these values:
""" """
Define the buy strategy parameters to be used by Hyperopt. Define the buy strategy parameters to be used by Hyperopt.
""" """
def populate_buy_trend(dataframe: DataFrame) -> DataFrame: def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
conditions = [] conditions = []
# GUARDS AND TRENDS # GUARDS AND TRENDS
if 'adx-enabled' in params and params['adx-enabled']: if 'adx-enabled' in params and params['adx-enabled']:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -10,6 +10,14 @@ If multiple Pairlist Handlers are used, they are chained and a combination of al
Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the `pair_blacklist` configuration setting) are also always removed from the resulting pairlist. Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the `pair_blacklist` configuration setting) are also always removed from the resulting pairlist.
### Pair blacklist
The pair blacklist (configured via `exchange.pair_blacklist` in the configuration) disallows certain pairs from trading.
This can be as simple as excluding `DOGE/BTC` - which will remove exactly this pair.
The pair-blacklist does also support wildcards (in regex-style) - so `BNB/.*` will exclude ALL pairs that start with BNB.
You may also use something like `.*DOWN/BTC` or `.*UP/BTC` to exclude leveraged tokens (check Pair naming conventions for your exchange!)
### Available Pairlist Handlers ### Available Pairlist Handlers
* [`StaticPairList`](#static-pair-list) (default, if not configured differently) * [`StaticPairList`](#static-pair-list) (default, if not configured differently)
@@ -27,7 +35,7 @@ Inactive markets are always removed from the resulting pairlist. Explicitly blac
#### Static Pair List #### Static Pair List
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration. By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so `.*/BTC` will include all pairs with BTC as a stake.
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`. It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.

131
docs/includes/pricing.md Normal file
View File

@@ -0,0 +1,131 @@
## Prices used for orders
Prices for regular orders can be controlled via the parameter structures `bid_strategy` for buying and `ask_strategy` for selling.
Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.
!!! Note
Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function `fetch_order_book()`, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's `fetch_ticker()`/`fetch_tickers()` functions. Refer to the ccxt library [documentation](https://github.com/ccxt/ccxt/wiki/Manual#market-data) for more details.
!!! Warning "Using market orders"
Please read the section [Market order pricing](#market-order-pricing) section when using market orders.
### Buy price
#### Check depth of market
When check depth of market is enabled (`bid_strategy.check_depth_of_market.enabled=True`), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.
Orderbook `bid` (buy) side depth is then divided by the orderbook `ask` (sell) side depth and the resulting delta is compared to the value of the `bid_strategy.check_depth_of_market.bids_to_ask_delta` parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.
!!! Note
A delta value below 1 means that `ask` (sell) orderbook side depth is greater than the depth of the `bid` (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).
#### Buy price side
The configuration setting `bid_strategy.price_side` defines the side of the spread the bot looks for when buying.
The following displays an orderbook.
``` explanation
...
103
102
101 # ask
-------------Current spread
99 # bid
98
97
...
```
If `bid_strategy.price_side` is set to `"bid"`, then the bot will use 99 as buying price.
In line with that, if `bid_strategy.price_side` is set to `"ask"`, then the bot will use 101 as buying price.
Using `ask` price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary.
Taker fees instead of maker fees will most likely apply even when using limit buy orders.
Also, prices at the "ask" side of the spread are higher than prices at the "bid" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).
#### Buy price with Orderbook enabled
When buying with the orderbook enabled (`bid_strategy.use_order_book=True`), Freqtrade fetches the `bid_strategy.order_book_top` entries from the orderbook and then uses the entry specified as `bid_strategy.order_book_top` on the configured side (`bid_strategy.price_side`) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
#### Buy price without Orderbook enabled
The following section uses `side` as the configured `bid_strategy.price_side`.
When not using orderbook (`bid_strategy.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's below the `last` traded price from the ticker. Otherwise (when the `side` price is above the `last` price), it calculates a rate between `side` and `last` price.
The `bid_strategy.ask_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the `last` price and values between those interpolate between ask and last price.
### Sell price
#### Sell price side
The configuration setting `ask_strategy.price_side` defines the side of the spread the bot looks for when selling.
The following displays an orderbook:
``` explanation
...
103
102
101 # ask
-------------Current spread
99 # bid
98
97
...
```
If `ask_strategy.price_side` is set to `"ask"`, then the bot will use 101 as selling price.
In line with that, if `ask_strategy.price_side` is set to `"bid"`, then the bot will use 99 as selling price.
#### Sell price with Orderbook enabled
When selling with the orderbook enabled (`ask_strategy.use_order_book=True`), Freqtrade fetches the `ask_strategy.order_book_max` entries in the orderbook. Then each of the orderbook steps between `ask_strategy.order_book_min` and `ask_strategy.order_book_max` on the configured orderbook side are validated for a profitable sell-possibility based on the strategy configuration (`minimal_roi` conditions) and the sell order is placed at the first profitable spot.
!!! Note
Using `order_book_max` higher than `order_book_min` only makes sense when ask_strategy.price_side is set to `"ask"`.
The idea here is to place the sell order early, to be ahead in the queue.
A fixed slot (mirroring `bid_strategy.order_book_top`) can be defined by setting `ask_strategy.order_book_min` and `ask_strategy.order_book_max` to the same number.
!!! Warning "Order_book_max > 1 - increased risks for stoplosses!"
Using `ask_strategy.order_book_max` higher than 1 will increase the risk the stoploss on exchange is cancelled too early, since an eventual [stoploss on exchange](#understand-order_types) will be cancelled as soon as the order is placed.
Also, the sell order will remain on the exchange for `unfilledtimeout.sell` (or until it's filled) - which can lead to missed stoplosses (with or without using stoploss on exchange).
!!! Warning "Order_book_max > 1 in dry-run"
Using `ask_strategy.order_book_max` higher than 1 will result in improper dry-run results (significantly better than real orders executed on exchange), since dry-run assumes orders to be filled almost instantly.
It is therefore advised to not use this setting for dry-runs.
#### Sell price without Orderbook enabled
When not using orderbook (`ask_strategy.use_order_book=False`), the price at the `ask_strategy.price_side` side (defaults to `"ask"`) from the ticker will be used as the sell price.
When not using orderbook (`ask_strategy.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's below the `last` traded price from the ticker. Otherwise (when the `side` price is above the `last` price), it calculates a rate between `side` and `last` price.
The `ask_strategy.bid_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the last price and values between those interpolate between `side` and last price.
### Market order pricing
When using market orders, prices should be configured to use the "correct" side of the orderbook to allow realistic pricing detection.
Assuming both buy and sell are using market orders, a configuration similar to the following might be used
``` jsonc
"order_types": {
"buy": "market",
"sell": "market"
// ...
},
"bid_strategy": {
"price_side": "ask",
// ...
},
"ask_strategy":{
"price_side": "bid",
// ...
},
```
Obviously, if only one side is using limit orders, different pricing combinations can be used.

View File

@@ -8,6 +8,7 @@ All protection end times are rounded up to the next candle to avoid sudden, unex
!!! Note !!! Note
Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance.
To align your protection with your strategy, you can define protections in the strategy.
!!! Tip !!! Tip
Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term). Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).
@@ -39,7 +40,9 @@ All protection end times are rounded up to the next candle to avoid sudden, unex
#### Stoploss Guard #### Stoploss Guard
`StoplossGuard` selects all trades within `lookback_period`, and determines if the amount of trades that resulted in stoploss are above `trade_limit` - in which case trading will stop for `stop_duration`. `StoplossGuard` selects all trades within `lookback_period` in minutes (or in candles when using `lookback_period_candles`).
If `trade_limit` or more trades resulted in stoploss, trading will stop for `stop_duration` in minutes (or in candles when using `stop_duration_candles`).
This applies across all pairs, unless `only_per_pair` is set to true, which will then only look at one pair at a time. This applies across all pairs, unless `only_per_pair` is set to true, which will then only look at one pair at a time.
The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles. The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles.
@@ -57,14 +60,14 @@ The below example stops trading for all pairs for 4 candles after the last trade
``` ```
!!! Note !!! Note
`StoplossGuard` considers all trades with the results `"stop_loss"` and `"trailing_stop_loss"` if the resulting profit was negative. `StoplossGuard` considers all trades with the results `"stop_loss"`, `"stoploss_on_exchange"` and `"trailing_stop_loss"` if the resulting profit was negative.
`trade_limit` and `lookback_period` will need to be tuned for your strategy. `trade_limit` and `lookback_period` will need to be tuned for your strategy.
#### MaxDrawdown #### MaxDrawdown
`MaxDrawdown` uses all trades within `lookback_period` (in minutes) to determine the maximum drawdown. If the drawdown is below `max_allowed_drawdown`, trading will stop for `stop_duration` (in minutes) after the last trade - assuming that the bot needs some time to let markets recover. `MaxDrawdown` uses all trades within `lookback_period` in minutes (or in candles when using `lookback_period_candles`) to determine the maximum drawdown. If the drawdown is below `max_allowed_drawdown`, trading will stop for `stop_duration` in minutes (or in candles when using `stop_duration_candles`) after the last trade - assuming that the bot needs some time to let markets recover.
The below sample stops trading for 12 candles if max-drawdown is > 20% considering all trades within the last 48 candles. The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of `trade_limit` trades - within the last 48 candles. If desired, `lookback_period` and/or `stop_duration` can be used.
```json ```json
"protections": [ "protections": [
@@ -76,13 +79,12 @@ The below sample stops trading for 12 candles if max-drawdown is > 20% consideri
"max_allowed_drawdown": 0.2 "max_allowed_drawdown": 0.2
}, },
], ],
``` ```
#### Low Profit Pairs #### Low Profit Pairs
`LowProfitPairs` uses all trades for a pair within `lookback_period` (in minutes) to determine the overall profit ratio. `LowProfitPairs` uses all trades for a pair within `lookback_period` in minutes (or in candles when using `lookback_period_candles`) to determine the overall profit ratio.
If that ratio is below `required_profit`, that pair will be locked for `stop_duration` (in minutes). If that ratio is below `required_profit`, that pair will be locked for `stop_duration` in minutes (or in candles when using `stop_duration_candles`).
The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles. The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles.
@@ -100,7 +102,7 @@ The below example will stop trading a pair for 60 minutes if the pair does not h
#### Cooldown Period #### Cooldown Period
`CooldownPeriod` locks a pair for `stop_duration` (in minutes) after selling, avoiding a re-entry for this pair for `stop_duration` minutes. `CooldownPeriod` locks a pair for `stop_duration` in minutes (or in candles when using `stop_duration_candles`) after selling, avoiding a re-entry for this pair for `stop_duration` minutes.
The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to "cool down". The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to "cool down".
@@ -167,3 +169,47 @@ The below example assumes a timeframe of 1 hour:
} }
], ],
``` ```
You can use the same in your strategy, the syntax is only slightly different:
``` python
from freqtrade.strategy import IStrategy
class AwesomeStrategy(IStrategy)
timeframe = '1h'
protections = [
{
"method": "CooldownPeriod",
"stop_duration_candles": 5
},
{
"method": "MaxDrawdown",
"lookback_period_candles": 48,
"trade_limit": 20,
"stop_duration_candles": 4,
"max_allowed_drawdown": 0.2
},
{
"method": "StoplossGuard",
"lookback_period_candles": 24,
"trade_limit": 4,
"stop_duration_candles": 2,
"only_per_pair": False
},
{
"method": "LowProfitPairs",
"lookback_period_candles": 6,
"trade_limit": 2,
"stop_duration_candles": 60,
"required_profit": 0.02
},
{
"method": "LowProfitPairs",
"lookback_period_candles": 24,
"trade_limit": 4,
"stop_duration_candles": 2,
"required_profit": 0.01
}
]
# ...
```

View File

@@ -5,12 +5,8 @@
<!-- Place this tag where you want the button to render. --> <!-- Place this tag where you want the button to render. -->
<a class="github-button" href="https://github.com/freqtrade/freqtrade" data-icon="octicon-star" data-size="large" aria-label="Star freqtrade/freqtrade on GitHub">Star</a> <a class="github-button" href="https://github.com/freqtrade/freqtrade" data-icon="octicon-star" data-size="large" aria-label="Star freqtrade/freqtrade on GitHub">Star</a>
<!-- Place this tag where you want the button to render. -->
<a class="github-button" href="https://github.com/freqtrade/freqtrade/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork freqtrade/freqtrade on GitHub">Fork</a> <a class="github-button" href="https://github.com/freqtrade/freqtrade/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork freqtrade/freqtrade on GitHub">Fork</a>
<!-- Place this tag where you want the button to render. -->
<a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/stable.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a> <a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/stable.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a>
<!-- Place this tag where you want the button to render. -->
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
## Introduction ## Introduction
@@ -35,6 +31,22 @@ Freqtrade is a crypto-currency algorithmic trading software developed in python
- Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.). - Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).
- Analyse: Further analysis can be performed on either Backtesting data or Freqtrade trading history (SQL database), including automated standard plots, and methods to load the data into [interactive environments](data-analysis.md). - Analyse: Further analysis can be performed on either Backtesting data or Freqtrade trading history (SQL database), including automated standard plots, and methods to load the data into [interactive environments](data-analysis.md).
## Supported exchange marketplaces
Please read the [exchange specific notes](exchanges.md) to learn about eventual, special configurations needed for each exchange.
- [X] [Binance](https://www.binance.com/) ([*Note for binance users](exchanges.md#blacklists))
- [X] [Bittrex](https://bittrex.com/)
- [X] [FTX](https://ftx.com)
- [X] [Kraken](https://kraken.com/)
- [ ] [potentially many others](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
### Community tested
Exchanges confirmed working by the community:
- [X] [Bitvavo](https://bitvavo.com/)
## Requirements ## Requirements
### Hardware requirements ### Hardware requirements
@@ -65,7 +77,7 @@ For any questions not covered by the documentation or for further information ab
Please check out our [discord server](https://discord.gg/MA9v74M). Please check out our [discord server](https://discord.gg/MA9v74M).
You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-k9o2v5ut-jX8Mc4CwNM8CDc2Dyg96YA). You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-mm786y93-Fxo37glxMY9g8OQC5AoOIw).
## Ready to try? ## Ready to try?

View File

@@ -2,93 +2,49 @@
This page explains how to prepare your environment for running the bot. This page explains how to prepare your environment for running the bot.
Please consider using the prebuilt [docker images](docker.md) to get started quickly while trying out freqtrade evaluating how it operates. The freqtrade documentation describes various ways to install freqtrade
## Prerequisite * [Docker images](docker_quickstart.md) (separate page)
* [Script Installation](#script-installation)
* [Manual Installation](#manual-installation)
* [Installation with Conda](#installation-with-conda)
### Requirements Please consider using the prebuilt [docker images](docker_quickstart.md) to get started quickly while evaluating how freqtrade works.
Click each one for install guide: ------
## Information
For Windows installation, please use the [windows installation guide](windows_installation.md).
The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the `./setup.sh` script, if it's available for your platform.
!!! Note "Version considerations"
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests).
The `stable` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
!!! Note
Python3.7 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
Also, python headers (`python<yourversion>-dev` / `python<yourversion>-devel`) must be available for the installation to complete successfully.
!!! Warning "Up-to-date clock"
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
------
## Requirements
These requirements apply to both [Script Installation](#script-installation) and [Manual Installation](#manual-installation).
### Install guide
* [Python >= 3.7.x](http://docs.python-guide.org/en/latest/starting/installation/) * [Python >= 3.7.x](http://docs.python-guide.org/en/latest/starting/installation/)
* [pip](https://pip.pypa.io/en/stable/installing/) * [pip](https://pip.pypa.io/en/stable/installing/)
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) * [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended) * [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended)
* [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html) (install instructions below) * [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html) (install instructions [below](#install-ta-lib))
We also recommend a [Telegram bot](telegram-usage.md#setup-your-telegram-bot), which is optional but recommended. ### Install code
!!! Warning "Up-to-date clock"
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
## Quick start
Freqtrade provides the Linux/MacOS Easy Installation script to install all dependencies and help you configure the bot.
!!! Note
Windows installation is explained [here](#windows).
The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the Easy Installation script, if it's available for your platform.
!!! Note "Version considerations"
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The `stable` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
!!! Note
Python3.7 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
This can be achieved with the following commands:
```bash
git clone https://github.com/freqtrade/freqtrade.git
cd freqtrade
# git checkout stable # Optional, see (1)
./setup.sh --install
```
(1) This command switches the cloned repository to the use of the `stable` branch. It's not needed if you wish to stay on the `develop` branch. You may later switch between branches at any time with the `git checkout stable`/`git checkout develop` commands.
## Easy Installation Script (Linux/MacOS)
If you are on Debian, Ubuntu or MacOS Freqtrade provides the script to install, update, configure and reset the codebase of your bot.
```bash
$ ./setup.sh
usage:
-i,--install Install freqtrade from scratch
-u,--update Command git pull to update.
-r,--reset Hard reset your develop/stable branch.
-c,--config Easy config generator (Will override your existing file).
```
** --install **
With this option, the script will install the bot and most dependencies:
You will need to have git and python3.7+ installed beforehand for this to work.
* Mandatory software as: `ta-lib`
* Setup your virtualenv under `.env/`
This option is a combination of installation tasks, `--reset` and `--config`.
** --update **
This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot.
** --reset **
This option will hard reset your branch (only if you are on either `stable` or `develop`) and recreate your virtualenv.
** --config **
DEPRECATED - use `freqtrade new-config -c config.json` instead.
### Activate your virtual environment
Each time you open a new terminal, you must run `source .env/bin/activate`.
------
## Custom Installation
We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros. We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros.
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems. OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
@@ -96,12 +52,15 @@ OS Specific steps are listed first, the [Common](#common) section below is neces
!!! Note !!! Note
Python3.7 or higher and the corresponding pip are assumed to be available. Python3.7 or higher and the corresponding pip are assumed to be available.
=== "Ubuntu/Debian" === "Debian/Ubuntu"
#### Install necessary dependencies #### Install necessary dependencies
```bash ```bash
# update repository
sudo apt-get update sudo apt-get update
sudo apt-get install build-essential git
# install packages
sudo apt install -y python3-pip python3-venv python3-pandas python3-pip git
``` ```
=== "RaspberryPi/Raspbian" === "RaspberryPi/Raspbian"
@@ -111,7 +70,7 @@ OS Specific steps are listed first, the [Common](#common) section below is neces
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied. Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
``` bash ```bash
sudo apt-get install python3-venv libatlas-base-dev cmake sudo apt-get install python3-venv libatlas-base-dev cmake
# Use pywheels.org to speed up installation # Use pywheels.org to speed up installation
sudo echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > tee /etc/pip.conf sudo echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > tee /etc/pip.conf
@@ -124,17 +83,106 @@ OS Specific steps are listed first, the [Common](#common) section below is neces
!!! Note "Installation duration" !!! Note "Installation duration"
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete. Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
Due to this, we recommend to use the prebuild docker-image for Raspberry, by following the [Docker quickstart documentation](docker_quickstart.md) Due to this, we recommend to use the pre-build docker-image for Raspberry, by following the [Docker quickstart documentation](docker_quickstart.md)
!!! Note !!! Note
The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`. The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine. We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
### Common ------
#### 1. Install TA-Lib ## Freqtrade repository
Use the provided ta-lib installation script Freqtrade is an open source crypto-currency trading bot, whose code is hosted on `github.com`
```bash
# Download `develop` branch of freqtrade repository
git clone https://github.com/freqtrade/freqtrade.git
# Enter downloaded directory
cd freqtrade
# your choice (1): novice user
git checkout stable
# your choice (2): advanced user
git checkout develop
```
(1) This command switches the cloned repository to the use of the `stable` branch. It's not needed, if you wish to stay on the (2) `develop` branch.
You may later switch between branches at any time with the `git checkout stable`/`git checkout develop` commands.
------
## Script Installation
First of the ways to install Freqtrade, is to use provided the Linux/MacOS `./setup.sh` script, which install all dependencies and help you configure the bot.
Make sure you fulfill the [Requirements](#requirements) and have downloaded the [Freqtrade repository](#freqtrade-repository).
### Use /setup.sh -install (Linux/MacOS)
If you are on Debian, Ubuntu or MacOS, freqtrade provides the script to install freqtrade.
```bash
# --install, Install freqtrade from scratch
./setup.sh -i
```
### Activate your virtual environment
Each time you open a new terminal, you must run `source .env/bin/activate` to activate your virtual environment.
```bash
# then activate your .env
source ./.env/bin/activate
```
### Congratulations
[You are ready](#you-are-ready), and run the bot
### Other options of /setup.sh script
You can as well update, configure and reset the codebase of your bot with `./script.sh`
```bash
# --update, Command git pull to update.
./setup.sh -u
# --reset, Hard reset your develop/stable branch.
./setup.sh -r
```
```
** --install **
With this option, the script will install the bot and most dependencies:
You will need to have git and python3.7+ installed beforehand for this to work.
* Mandatory software as: `ta-lib`
* Setup your virtualenv under `.env/`
This option is a combination of installation tasks and `--reset`
** --update **
This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot.
** --reset **
This option will hard reset your branch (only if you are on either `stable` or `develop`) and recreate your virtualenv.
```
-----
## Manual Installation
Make sure you fulfill the [Requirements](#requirements) and have downloaded the [Freqtrade repository](#freqtrade-repository).
### Install TA-Lib
#### TA-Lib script installation
```bash ```bash
sudo ./build_helpers/install_ta-lib.sh sudo ./build_helpers/install_ta-lib.sh
@@ -159,78 +207,194 @@ cd ..
rm -rf ./ta-lib* rm -rf ./ta-lib*
``` ```
!!! Note #### Setup Python virtual environment (virtualenv)
An already downloaded version of ta-lib is included in the repository, as the sourceforge.net source seems to have problems frequently.
#### 2. Setup your Python virtual environment (virtualenv) You will run freqtrade in separated `virtual environment`
!!! Note
This step is optional but strongly recommended to keep your system organized
```bash ```bash
# create virtualenv in directory /freqtrade/.env
python3 -m venv .env python3 -m venv .env
# run virtualenv
source .env/bin/activate source .env/bin/activate
``` ```
#### 3. Install Freqtrade #### Install python dependencies
Clone the git repository:
```bash ```bash
git clone https://github.com/freqtrade/freqtrade.git
cd freqtrade
git checkout stable
```
#### 4. Install python dependencies
``` bash
python3 -m pip install --upgrade pip python3 -m pip install --upgrade pip
python3 -m pip install -e . python3 -m pip install -e .
``` ```
#### 5. Initialize the configuration ### Congratulations
```bash [You are ready](#you-are-ready), and run the bot
# Initialize the user_directory
freqtrade create-userdir --userdir user_data/
# Create a new configuration file #### (Optional) Post-installation Tasks
freqtrade new-config --config config.json
```
> *To edit the config please refer to [Bot Configuration](configuration.md).* !!! Note
If you run the bot on a server, you should consider using [Docker](docker_quickstart.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
#### 6. Run the Bot On Linux with software suite `systemd`, as an optional post-installation task, you may wish to setup the bot to run as a `systemd service` or configure it to send the log messages to the `syslog`/`rsyslog` or `journald` daemons. See [Advanced Logging](advanced-setup.md#advanced-logging) for details.
If this is the first time you run the bot, ensure you are running it in Dry-run `"dry_run": true,` otherwise it will start to buy and sell coins.
```bash
freqtrade trade -c config.json
```
*Note*: If you run the bot on a server, you should consider using [Docker](docker.md) or a terminal multiplexer like `screen` or [`tmux`](https://en.wikipedia.org/wiki/Tmux) to avoid that the bot is stopped on logout.
#### 7. (Optional) Post-installation Tasks
On Linux, as an optional post-installation task, you may wish to setup the bot to run as a `systemd` service or configure it to send the log messages to the `syslog`/`rsyslog` or `journald` daemons. See [Advanced Logging](advanced-setup.md#advanced-logging) for details.
------ ------
### Anaconda ## Installation with Conda
Freqtrade can also be installed using Anaconda (or Miniconda). Freqtrade can also be installed with Miniconda or Anaconda. We recommend using Miniconda as it's installation footprint is smaller. Conda will automatically prepare and manage the extensive library-dependencies of the Freqtrade program.
!!! Note ### What is Conda?
This requires the [ta-lib](#1-install-ta-lib) C-library to be installed first. See below.
``` bash Conda is a package, dependency and environment manager for multiple programming languages: [conda docs](https://docs.conda.io/projects/conda/en/latest/index.html)
conda env create -f environment.yml
### Installation with conda
#### Install Conda
[Installing on linux](https://conda.io/projects/conda/en/latest/user-guide/install/linux.html#install-linux-silent)
[Installing on windows](https://conda.io/projects/conda/en/latest/user-guide/install/windows.html)
Answer all questions. After installation, it is mandatory to turn your terminal OFF and ON again.
#### Freqtrade download
Download and install freqtrade.
```bash
# download freqtrade
git clone https://github.com/freqtrade/freqtrade.git
# enter downloaded directory 'freqtrade'
cd freqtrade
``` ```
#### Freqtrade instal: Conda Environment
Prepare conda-freqtrade environment, using file `environment.yml`, which exist in main freqtrade directory
```bash
conda env create -n freqtrade-conda -f environment.yml
```
!!! Note "Creating Conda Environment"
The conda command `create -n` automatically installs all nested dependencies for the selected libraries, general structure of installation command is:
```bash
# choose your own packages
conda env create -n [name of the environment] [python version] [packages]
# point to file with packages
conda env create -n [name of the environment] -f [file]
```
#### Enter/exit freqtrade-conda environment
To check available environments, type
```bash
conda env list
```
Enter installed environment
```bash
# enter conda environment
conda activate freqtrade-conda
# exit conda environment - don't do it now
conda deactivate
```
Install last python dependencies with pip
```bash
python3 -m pip install --upgrade pip
python3 -m pip install -e .
```
### Congratulations
[You are ready](#you-are-ready), and run the bot
### Important shortcuts
```bash
# list installed conda environments
conda env list
# activate base environment
conda activate
# activate freqtrade-conda environment
conda activate freqtrade-conda
#deactivate any conda environments
conda deactivate
```
### Further info on anaconda
!!! Info "New heavy packages"
It may happen that creating a new Conda environment, populated with selected packages at the moment of creation takes less time than installing a large, heavy library or application, into previously set environment.
!!! Warning "pip install within conda"
The documentation of conda says that pip should NOT be used within conda, because internal problems can occur.
However, they are rare. [Anaconda Blogpost](https://www.anaconda.com/blog/using-pip-in-a-conda-environment)
Nevertheless, that is why, the `conda-forge` channel is preferred:
* more libraries are available (less need for `pip`)
* `conda-forge` works better with `pip`
* the libraries are newer
Happy trading!
----- -----
## You are ready
You've made it this far, so you have successfully installed freqtrade.
### Initialize the configuration
```bash
# Step 1 - Initialize user folder
freqtrade create-userdir --userdir user_data
# Step 2 - Create a new configuration file
freqtrade new-config --config config.json
```
You are ready to run, read [Bot Configuration](configuration.md), remember to start with `dry_run: True` and verify that everything is working.
To learn how to setup your configuration, please refer to the [Bot Configuration](configuration.md) documentation page.
### Start the Bot
```bash
freqtrade trade --config config.json --strategy SampleStrategy
```
!!! Warning
You should read through the rest of the documentation, backtest the strategy you're going to use, and use dry-run before enabling trading with real money.
-----
## Troubleshooting ## Troubleshooting
### Common problem: "command not found"
If you used (1)`Script` or (2)`Manual` installation, you need to run the bot in virtual environment. If you get error as below, make sure venv is active.
```bash
# if:
bash: freqtrade: command not found
# then activate your .env
source ./.env/bin/activate
```
### MacOS installation error ### MacOS installation error
Newer versions of MacOS may have installation failed with errors like `error: command 'g++' failed with exit status 1`. Newer versions of MacOS may have installation failed with errors like `error: command 'g++' failed with exit status 1`.
@@ -238,13 +402,21 @@ Newer versions of MacOS may have installation failed with errors like `error: co
This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS. This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS.
For MacOS 10.14, this can be accomplished with the below command. For MacOS 10.14, this can be accomplished with the below command.
``` bash ```bash
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
``` ```
If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details. If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.
----- ### MacOS installation error with python 3.9
Now you have an environment ready, the next step is When using python 3.9 on macOS, it's currently necessary to install some os-level modules to allow dependencies to compile.
[Bot Configuration](configuration.md). The errors you'll see happen during installation and are related to the installation of `tables` or `blosc`.
You can install the necessary libraries with the following command:
```bash
brew install hdf5 c-blosc
```
After this, please run the installation (script) again.

View File

@@ -6,22 +6,22 @@ This file was automatically generated - do not edit
{% set site_url = site_url ~ "/index.html" %} {% set site_url = site_url ~ "/index.html" %}
{% endif %} {% endif %}
<header class="md-header" data-md-component="header"> <header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid" aria-label="{{ lang.t('header.title') }}"> <nav class="md-header__inner md-grid" aria-label="{{ lang.t('header.title') }}">
<a href="{{ site_url }}" title="{{ config.site_name | e }}" class="md-header-nav__button md-logo" <a href="{{ site_url }}" title="{{ config.site_name | e }}" class="md-header__button md-logo"
aria-label="{{ config.site_name }}"> aria-label="{{ config.site_name }}">
{% include "partials/logo.html" %} {% include "partials/logo.html" %}
</a> </a>
<label class="md-header-nav__button md-icon" for="__drawer"> <label class="md-header__button md-icon" for="__drawer">
{% include ".icons/material/menu" ~ ".svg" %} {% include ".icons/material/menu" ~ ".svg" %}
</label> </label>
<div class="md-header-nav__title" data-md-component="header-title"> <div class="md-header__title" data-md-component="header-title">
<div class="md-header-nav__ellipsis"> <div class="md-header__ellipsis">
<div class="md-header-nav__topic"> <div class="md-header__topic">
<span class="md-ellipsis"> <span class="md-ellipsis">
{{ config.site_name }} {{ config.site_name }}
</span> </span>
</div> </div>
<div class="md-header-nav__topic"> <div class="md-header__topic" data-md-component="header-topic">
<span class="md-ellipsis"> <span class="md-ellipsis">
{% if page and page.meta and page.meta.title %} {% if page and page.meta and page.meta.title %}
{{ page.meta.title }} {{ page.meta.title }}
@@ -32,20 +32,41 @@ This file was automatically generated - do not edit
</div> </div>
</div> </div>
</div> </div>
<div class="md-header__options">
{% if config.extra.alternate %}
<div class="md-select">
{% set icon = config.theme.icon.alternate or "material/translate" %}
<span class="md-header__button md-icon">
{% include ".icons/" ~ icon ~ ".svg" %}
</span>
<div class="md-select__inner">
<ul class="md-select__list">
{% for alt in config.extra.alternate %}
<li class="md-select__item">
<a href="{{ alt.link | url }}" class="md-select__link">
{{ alt.name }}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
{% endif %}
</div>
{% if "search" in config["plugins"] %} {% if "search" in config["plugins"] %}
<label class="md-header-nav__button md-icon" for="__search"> <label class="md-header__button md-icon" for="__search">
{% include ".icons/material/magnify.svg" %} {% include ".icons/material/magnify.svg" %}
</label> </label>
{% include "partials/search.html" %} {% include "partials/search.html" %}
{% endif %} {% endif %}
{% if config.repo_url %} {% if config.repo_url %}
<div class="md-header-nav__source"> <div class="md-header__source">
{% include "partials/source.html" %} {% include "partials/source.html" %}
</div> </div>
{% endif %} {% endif %}
</nav> </nav>
<!-- Place this tag in your head or just before your close body tag. --> <!-- Place this tag in your head or just before your close body tag. -->
<script async defer src="https://buttons.github.io/buttons.js"></script> <script async defer src="https://buttons.github.io/buttons.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" <script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</header> </header>

View File

@@ -188,7 +188,7 @@ Sample configuration with inline comments explaining the process:
'senkou_a': { 'senkou_a': {
'color': 'green', #optional 'color': 'green', #optional
'fill_to': 'senkou_b', 'fill_to': 'senkou_b',
'fill_label': 'Ichimoku Cloud' #optional, 'fill_label': 'Ichimoku Cloud', #optional
'fill_color': 'rgba(255,76,46,0.2)', #optional 'fill_color': 'rgba(255,76,46,0.2)', #optional
}, },
# plot senkou_b, too. Not only the area to it. # plot senkou_b, too. Not only the area to it.
@@ -208,6 +208,7 @@ Sample configuration with inline comments explaining the process:
} }
``` ```
!!! Note !!! Note
The above configuration assumes that `ema10`, `ema50`, `senkou_a`, `senkou_b`, The above configuration assumes that `ema10`, `ema50`, `senkou_a`, `senkou_b`,
`macd`, `macdsignal`, `macdhist` and `rsi` are columns in the DataFrame created by the strategy. `macd`, `macdsignal`, `macdhist` and `rsi` are columns in the DataFrame created by the strategy.

View File

@@ -1,3 +1,3 @@
mkdocs-material==6.2.3 mkdocs-material==7.0.6
mdx_truly_sane_lists==1.2 mdx_truly_sane_lists==1.2
pymdown-extensions==8.1 pymdown-extensions==8.1.1

View File

@@ -1,4 +1,19 @@
# REST API Usage # REST API & FreqUI
## FreqUI
Freqtrade provides a builtin webserver, which can serve [FreqUI](https://github.com/freqtrade/frequi), the freqtrade UI.
By default, the UI is not included in the installation (except for docker images), and must be installed explicitly with `freqtrade install-ui`.
This same command can also be used to update freqUI, should there be a new release.
Once the bot is started in trade / dry-run mode (with `freqtrade trade`) - the UI will be available under the configured port below (usually `http://127.0.0.1:8080`).
!!! info "Alpha release"
FreqUI is still considered an alpha release - if you encounter bugs or inconsistencies please open a [FreqUI issue](https://github.com/freqtrade/frequi/issues/new/choose).
!!! Note "developers"
Developers should not use this method, but instead use the method described in the [freqUI repository](https://github.com/freqtrade/frequi) to get the source-code of freqUI.
## Configuration ## Configuration
@@ -11,7 +26,8 @@ Sample configuration:
"enabled": true, "enabled": true,
"listen_ip_address": "127.0.0.1", "listen_ip_address": "127.0.0.1",
"listen_port": 8080, "listen_port": 8080,
"verbosity": "info", "verbosity": "error",
"enable_openapi": false,
"jwt_secret_key": "somethingrandom", "jwt_secret_key": "somethingrandom",
"CORS_origins": [], "CORS_origins": [],
"username": "Freqtrader", "username": "Freqtrader",
@@ -22,9 +38,6 @@ Sample configuration:
!!! Danger "Security warning" !!! Danger "Security warning"
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot. By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
!!! Danger "Password selection"
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
You can then access the API by going to `http://127.0.0.1:8080/api/v1/ping` in a browser to check if the API is running correctly. You can then access the API by going to `http://127.0.0.1:8080/api/v1/ping` in a browser to check if the API is running correctly.
This should return the response: This should return the response:
@@ -34,16 +47,22 @@ This should return the response:
All other endpoints return sensitive info and require authentication and are therefore not available through a web browser. All other endpoints return sensitive info and require authentication and are therefore not available through a web browser.
To generate a secure password, either use a password manager, or use the below code snipped. ### Security
To generate a secure password, best use a password manager, or use the below code.
``` python ``` python
import secrets import secrets
secrets.token_hex() secrets.token_hex()
``` ```
!!! Hint !!! Hint "JWT token"
Use the same method to also generate a JWT secret key (`jwt_secret_key`). Use the same method to also generate a JWT secret key (`jwt_secret_key`).
!!! Danger "Password selection"
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
Also change `jwt_secret_key` to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!).
### Configuration with docker ### Configuration with docker
If you run your bot using docker, you'll need to have the bot listen to incoming connections. The security is then handled by docker. If you run your bot using docker, you'll need to have the bot listen to incoming connections. The security is then handled by docker.
@@ -56,28 +75,20 @@ If you run your bot using docker, you'll need to have the bot listen to incoming
}, },
``` ```
Add the following to your docker command: Uncomment the following from your docker-compose file:
``` bash ```yml
-p 127.0.0.1:8080:8080 ports:
``` - "127.0.0.1:8080:8080"
A complete sample-command may then look as follows:
```bash
docker run -d \
--name freqtrade \
-v ~/.freqtrade/config.json:/freqtrade/config.json \
-v ~/.freqtrade/user_data/:/freqtrade/user_data \
-v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \
-p 127.0.0.1:8080:8080 \
freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy
``` ```
!!! Danger "Security warning" !!! Danger "Security warning"
By using `-p 8080:8080` the API is available to everyone connecting to the server under the correct port, so others may be able to control your bot. By using `8080:8080` in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot.
## Consuming the API
## Rest API
### Consuming the API
You can consume the API by using the script `scripts/rest_client.py`. You can consume the API by using the script `scripts/rest_client.py`.
The client script only requires the `requests` module, so Freqtrade does not need to be installed on the system. The client script only requires the `requests` module, so Freqtrade does not need to be installed on the system.
@@ -88,7 +99,7 @@ python3 scripts/rest_client.py <command> [optional parameters]
By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be used, however you can specify a configuration file to override this behaviour. By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be used, however you can specify a configuration file to override this behaviour.
### Minimalistic client config #### Minimalistic client config
``` json ``` json
{ {
@@ -104,7 +115,7 @@ By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be use
python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters] python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]
``` ```
## Available endpoints ### Available endpoints
| Command | Description | | Command | Description |
|----------|-------------| |----------|-------------|
@@ -120,6 +131,7 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
| `status` | Lists all open trades. | `status` | Lists all open trades.
| `count` | Displays number of trades used and available. | `count` | Displays number of trades used and available.
| `locks` | Displays currently locked pairs. | `locks` | Displays currently locked pairs.
| `delete_lock <lock_id>` | Deletes (disables) the lock by id.
| `profit` | Display a summary of your profit/loss from close trades and some stats about your performance. | `profit` | Display a summary of your profit/loss from close trades and some stats about your performance.
| `forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`). | `forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`).
| `forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`). | `forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`).
@@ -171,6 +183,11 @@ count
daily daily
Return the amount of open trades. Return the amount of open trades.
delete_lock
Delete (disable) lock from the database.
:param lock_id: ID for the lock to delete
delete_trade delete_trade
Delete trade from the database. Delete trade from the database.
Tries to close open orders. Requires manual handling of this asset on the exchange. Tries to close open orders. Requires manual handling of this asset on the exchange.
@@ -191,6 +208,9 @@ forcesell
:param tradeid: Id of the trade (can be received via status command) :param tradeid: Id of the trade (can be received via status command)
locks
Return current locks
logs logs
Show latest logs. Show latest logs.
@@ -263,7 +283,12 @@ whitelist
``` ```
## Advanced API usage using JWT tokens ### 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.
### Advanced API usage using JWT tokens
!!! Note !!! Note
The below should be done in an application (a Freqtrade REST API client, which fetches info via API), and is not intended to be used on a regular basis. The below should be done in an application (a Freqtrade REST API client, which fetches info via API), and is not intended to be used on a regular basis.
@@ -288,9 +313,9 @@ Since the access token has a short timeout (15 min) - the `token/refresh` reques
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs"} {"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs"}
``` ```
## CORS ### CORS
All web-based frontends are subject to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) - Cross-Origin Resource Sharing. All web-based front-ends are subject to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) - Cross-Origin Resource Sharing.
Since most of the requests to the Freqtrade API must be authenticated, a proper CORS policy is key to avoid security problems. Since most of the requests to the Freqtrade API must be authenticated, a proper CORS policy is key to avoid security problems.
Also, the standard disallows `*` CORS policies for requests with credentials, so this setting must be set appropriately. Also, the standard disallows `*` CORS policies for requests with credentials, so this setting must be set appropriately.

View File

@@ -6,6 +6,10 @@ With some configuration, freqtrade (in combination with ccxt) provides access to
This document is an overview to configure Freqtrade to be used with sandboxes. This document is an overview to configure Freqtrade to be used with sandboxes.
This can be useful to developers and trader alike. This can be useful to developers and trader alike.
!!! Warning
Sandboxes usually have very low volume, and either a very wide spread, or no orders available at all.
Therefore, sandboxes will usually not do a good job of showing you how a strategy would work in real trading.
## Exchanges known to have a sandbox / testnet ## Exchanges known to have a sandbox / testnet
* [binance](https://testnet.binance.vision/) * [binance](https://testnet.binance.vision/)

View File

@@ -51,6 +51,14 @@ The bot cannot do these every 5 seconds (at each iteration), otherwise it would
So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute). So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally. This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
### forcesell
`forcesell` is an optional value, which defaults to the same value as `sell` and is used when sending a `/forcesell` command from Telegram or from the Rest API.
### forcebuy
`forcebuy` is an optional value, which defaults to the same value as `buy` and is used when sending a `/forcebuy` command from Telegram or from the Rest API.
### emergencysell ### emergencysell
`emergencysell` is an optional value, which defaults to `market` and is used when creating stop loss on exchange orders fails. `emergencysell` is an optional value, which defaults to `market` and is used when creating stop loss on exchange orders fails.
@@ -78,6 +86,7 @@ At this stage the bot contains the following stoploss support modes:
2. Trailing stop loss. 2. Trailing stop loss.
3. Trailing stop loss, custom positive loss. 3. Trailing stop loss, custom positive loss.
4. Trailing stop loss only once the trade has reached a certain offset. 4. Trailing stop loss only once the trade has reached a certain offset.
5. [Custom stoploss function](strategy-advanced.md#custom-stoploss)
### Static Stop Loss ### Static Stop Loss

View File

@@ -8,11 +8,303 @@ If you're just getting started, please be familiar with the methods described in
!!! Note !!! Note
All callback methods described below should only be implemented in a strategy if they are actually used. All callback methods described below should only be implemented in a strategy if they are actually used.
!!! Tip
You can get a strategy template containing all below methods by running `freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced`
## Storing information
Storing information can be accomplished by creating a new dictionary within the strategy class.
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
```python
class AwesomeStrategy(IStrategy):
# Create custom dictionary
custom_info = {}
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# Check if the entry already exists
if not metadata["pair"] in self.custom_info:
# Create empty entry for this pair
self.custom_info[metadata["pair"]] = {}
if "crosstime" in self.custom_info[metadata["pair"]]:
self.custom_info[metadata["pair"]]["crosstime"] += 1
else:
self.custom_info[metadata["pair"]]["crosstime"] = 1
```
!!! Warning
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
!!! Note
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
***
### Storing custom information using DatetimeIndex from `dataframe`
Imagine you need to store an indicator like `ATR` or `RSI` into `custom_info`. To use this in a meaningful way, you will not only need the raw data of the indicator, but probably also need to keep the right timestamps.
```python
import talib.abstract as ta
class AwesomeStrategy(IStrategy):
# Create custom dictionary
custom_info = {}
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# using "ATR" here as example
dataframe['atr'] = ta.ATR(dataframe)
if self.dp.runmode.value in ('backtest', 'hyperopt'):
# add indicator mapped to correct DatetimeIndex to custom_info
self.custom_info[metadata['pair']] = dataframe[['date', 'atr']].copy().set_index('date')
return dataframe
```
!!! Warning
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
!!! Note
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
See `custom_stoploss` examples below on how to access the saved dataframe columns
## Custom stoploss
The stoploss price can only ever move upwards - if the stoploss value returned from `custom_stoploss` would result in a lower stoploss price than was previously set, it will be ignored. The traditional `stoploss` value serves as an absolute lower level and will be instated as the initial stoploss.
The usage of the custom stoploss method must be enabled by setting `use_custom_stoploss=True` on the strategy object.
The method must return a stoploss value (float / number) as a percentage of the current price.
E.g. If the `current_rate` is 200 USD, then returning `0.02` will set the stoploss price 2% lower, at 196 USD.
The absolute value of the return value is used (the sign is ignored), so returning `0.05` or `-0.05` have the same result, a stoploss 5% below the current price.
To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:
``` python
# additional imports required
from datetime import datetime
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
"""
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
e.g. returning -0.05 would create a stoploss 5% below current_rate.
The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss.
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
When not implemented by a strategy, returns the initial stoploss value
Only called when use_custom_stoploss is set to True.
:param pair: Pair that's currently analyzed
:param trade: trade object.
:param current_time: datetime object, containing the current datetime
:param current_rate: Rate, calculated based on pricing settings in ask_strategy.
:param current_profit: Current profit (as ratio), calculated based on current_rate.
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
:return float: New stoploss value, relative to the currentrate
"""
return -0.04
```
Stoploss on exchange works similar to `trailing_stop`, and the stoploss on exchange is updated as configured in `stoploss_on_exchange_interval` ([More details about stoploss on exchange](stoploss.md#stop-loss-on-exchange-freqtrade)).
!!! Note "Use of dates"
All time-based calculations should be done based on `current_time` - using `datetime.now()` or `datetime.utcnow()` is discouraged, as this will break backtesting support.
!!! Tip "Trailing stoploss"
It's recommended to disable `trailing_stop` when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.
### Custom stoploss examples
The next section will show some examples on what's possible with the custom stoploss function.
Of course, many more things are possible, and all examples can be combined at will.
#### Time based trailing stop
Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.
``` python
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
if current_time - timedelta(minutes=120) > trade.open_date_utc:
return -0.05
elif current_time - timedelta(minutes=60) > trade.open_date_utc:
return -0.10
return 1
```
#### Different stoploss per pair
Use a different stoploss depending on the pair.
In this example, we'll trail the highest price with 10% trailing stoploss for `ETH/BTC` and `XRP/BTC`, with 5% trailing stoploss for `LTC/BTC` and with 15% for all other pairs.
``` python
from datetime import datetime
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
if pair in ('ETH/BTC', 'XRP/BTC'):
return -0.10
elif pair in ('LTC/BTC'):
return -0.05
return -0.15
```
#### Trailing stoploss with positive offset
Use the initial stoploss until the profit is above 4%, then use a trailing stoploss of 50% of the current profit with a minimum of 2.5% and a maximum of 5%.
Please note that the stoploss can only increase, values lower than the current stoploss are ignored.
``` python
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
if current_profit < 0.04:
return -1 # return a value bigger than the inital stoploss to keep using the inital stoploss
# After reaching the desired offset, allow the stoploss to trail by half the profit
desired_stoploss = current_profit / 2
# Use a minimum of 2.5% and a maximum of 5%
return max(min(desired_stoploss, 0.05), 0.025)
```
#### Calculating stoploss relative to open price
Stoploss values returned from `custom_stoploss()` always specify a percentage relative to `current_rate`. In order to set a stoploss relative to the *open* price, we need to use `current_profit` to calculate what percentage relative to the `current_rate` will give you the same result as if the percentage was specified from the open price.
The helper function [`stoploss_from_open()`](strategy-customization.md#stoploss_from_open) can be used to convert from an open price relative stop, to a current price relative stop which can be returned from `custom_stoploss()`.
#### Stepped stoploss
Instead of continuously trailing behind the current price, this example sets fixed stoploss price levels based on the current profit.
* Use the regular stoploss until 20% profit is reached
* Once profit is > 20% - set stoploss to 7% above open price.
* Once profit is > 25% - set stoploss to 15% above open price.
* Once profit is > 40% - set stoploss to 25% above open price.
``` python
from datetime import datetime
from freqtrade.persistence import Trade
from freqtrade.strategy import stoploss_from_open
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
# evaluate highest to lowest, so that highest possible stop is used
if current_profit > 0.40:
return stoploss_from_open(0.25, current_profit)
elif current_profit > 0.25:
return stoploss_from_open(0.15, current_profit)
elif current_profit > 0.20:
return stoploss_from_open(0.07, current_profit)
# return maximum stoploss value, keeping current stoploss price unchanged
return 1
```
#### Custom stoploss using an indicator from dataframe example
Imagine you want to use `custom_stoploss()` to use a trailing indicator like e.g. "ATR"
See: "Storing custom information using DatetimeIndex from `dataframe`" example above) on how to store the indicator into `custom_info`
!!! Warning
only use .iat[-1] in live mode, not in backtesting/hyperopt
otherwise you will look into the future
see [Common mistakes when developing strategies](strategy-customization.md#common-mistakes-when-developing-strategies) for more info.
``` python
from freqtrade.persistence import Trade
from freqtrade.state import RunMode
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
result = 1
if self.custom_info and pair in self.custom_info and trade:
# using current_time directly (like below) will only work in backtesting.
# so check "runmode" to make sure that it's only used in backtesting/hyperopt
if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'):
relative_sl = self.custom_info[pair].loc[current_time]['atr']
# in live / dry-run, it'll be really the current time
else:
# but we can just use the last entry from an already analyzed dataframe instead
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
timeframe=self.timeframe)
# WARNING
# only use .iat[-1] in live mode, not in backtesting/hyperopt
# otherwise you will look into the future
# see: https://www.freqtrade.io/en/latest/strategy-customization/#common-mistakes-when-developing-strategies
relative_sl = dataframe['atr'].iat[-1]
if (relative_sl is not None):
# new stoploss relative to current_rate
new_stoploss = (current_rate-relative_sl)/current_rate
# turn into relative negative offset required by `custom_stoploss` return implementation
result = new_stoploss - 1
return result
```
---
## Custom order timeout rules ## Custom order timeout rules
Simple, timebased order-timeouts can be configured either via strategy or in the configuration in the `unfilledtimeout` section. Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the `unfilledtimeout` section.
However, freqtrade also offers a custom callback for both ordertypes, which allows you to decide based on custom criteria if a order did time out or not. However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if a order did time out or not.
!!! Note !!! Note
Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances. Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances.
@@ -25,10 +317,10 @@ It applies a tight timeout for higher priced assets, while allowing more time to
The function must return either `True` (cancel order) or `False` (keep order alive). The function must return either `True` (cancel order) or `False` (keep order alive).
``` python ``` python
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from freqtrade.persistence import Trade from freqtrade.persistence import Trade
class Awesomestrategy(IStrategy): class AwesomeStrategy(IStrategy):
# ... populate_* methods # ... populate_* methods
@@ -39,21 +331,21 @@ class Awesomestrategy(IStrategy):
} }
def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool: def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:
if trade.open_rate > 100 and trade.open_date < datetime.utcnow() - timedelta(minutes=5): if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5):
return True return True
elif trade.open_rate > 10 and trade.open_date < datetime.utcnow() - timedelta(minutes=3): elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3):
return True return True
elif trade.open_rate < 1 and trade.open_date < datetime.utcnow() - timedelta(hours=24): elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24):
return True return True
return False return False
def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool: def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:
if trade.open_rate > 100 and trade.open_date < datetime.utcnow() - timedelta(minutes=5): if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5):
return True return True
elif trade.open_rate > 10 and trade.open_date < datetime.utcnow() - timedelta(minutes=3): elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3):
return True return True
elif trade.open_rate < 1 and trade.open_date < datetime.utcnow() - timedelta(hours=24): elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24):
return True return True
return False return False
``` ```
@@ -67,7 +359,7 @@ class Awesomestrategy(IStrategy):
from datetime import datetime from datetime import datetime
from freqtrade.persistence import Trade from freqtrade.persistence import Trade
class Awesomestrategy(IStrategy): class AwesomeStrategy(IStrategy):
# ... populate_* methods # ... populate_* methods
@@ -95,6 +387,8 @@ class Awesomestrategy(IStrategy):
return False return False
``` ```
---
## Bot loop start callback ## Bot loop start callback
A simple callback which is called once at the start of every bot throttling iteration. A simple callback which is called once at the start of every bot throttling iteration.
@@ -103,7 +397,7 @@ This can be used to perform calculations which are pair independent (apply to al
``` python ``` python
import requests import requests
class Awesomestrategy(IStrategy): class AwesomeStrategy(IStrategy):
# ... populate_* methods # ... populate_* methods
@@ -128,7 +422,7 @@ class Awesomestrategy(IStrategy):
`confirm_trade_entry()` can be used to abort a trade entry at the latest second (maybe because the price is not what we expect). `confirm_trade_entry()` can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).
``` python ``` python
class Awesomestrategy(IStrategy): class AwesomeStrategy(IStrategy):
# ... populate_* methods # ... populate_* methods
@@ -164,7 +458,7 @@ class Awesomestrategy(IStrategy):
from freqtrade.persistence import Trade from freqtrade.persistence import Trade
class Awesomestrategy(IStrategy): class AwesomeStrategy(IStrategy):
# ... populate_* methods # ... populate_* methods
@@ -200,6 +494,8 @@ class Awesomestrategy(IStrategy):
``` ```
---
## Derived strategies ## Derived strategies
The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched: The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
@@ -219,4 +515,41 @@ class MyAwesomeStrategy2(MyAwesomeStrategy):
trailing_stop = True trailing_stop = True
``` ```
Both attributes and methods may be overriden, altering behavior of the original strategy in a way you need. Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need.
!!! Note "Parent-strategy in different files"
If you have the parent-strategy in a different file, you'll need to add the following to the top of your "child"-file to ensure proper loading, otherwise freqtrade may not be able to load the parent strategy correctly.
``` python
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))
from myawesomestrategy import MyAwesomeStrategy
```
## Embedding Strategies
Freqtrade provides you with with an easy way to embed the strategy into your configuration file.
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
in your chosen config file.
### Encoding a string as BASE64
This is a quick example, how to generate the BASE64 string in python
```python
from base64 import urlsafe_b64encode
with open(file, 'r') as f:
content = f.read()
content = urlsafe_b64encode(content.encode('utf-8'))
```
The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following
```json
"strategy": "NameOfStrategy:BASE64String"
```
Please ensure that 'NameOfStrategy' is identical to the strategy name!

View File

@@ -300,38 +300,7 @@ The metadata-dict (available for `populate_buy_trend`, `populate_sell_trend`, `p
Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`. Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`.
The Metadata-dict should not be modified and does not persist information across multiple calls. The Metadata-dict should not be modified and does not persist information across multiple calls.
Instead, have a look at the section [Storing information](#Storing-information) Instead, have a look at the section [Storing information](strategy-advanced.md#Storing-information)
### Storing information
Storing information can be accomplished by creating a new dictionary within the strategy class.
The name of the variable can be chosen at will, but should be prefixed with `cust_` to avoid naming collisions with predefined strategy variables.
```python
class Awesomestrategy(IStrategy):
# Create custom dictionary
cust_info = {}
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# Check if the entry already exists
if not metadata["pair"] in self._cust_info:
# Create empty entry for this pair
self._cust_info[metadata["pair"]] = {}
if "crosstime" in self.cust_info[metadata["pair"]:
self.cust_info[metadata["pair"]]["crosstime"] += 1
else:
self.cust_info[metadata["pair"]]["crosstime"] = 1
```
!!! Warning
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
!!! Note
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
***
## Additional data (informative_pairs) ## Additional data (informative_pairs)
@@ -444,14 +413,19 @@ It can also be used in specific callbacks to get the signal that caused the acti
``` python ``` python
# fetch current dataframe # fetch current dataframe
if self.dp: if self.dp:
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'], if self.dp.runmode.value in ('live', 'dry_run'):
timeframe=self.timeframe) dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'],
timeframe=self.timeframe)
``` ```
!!! Note "No data available" !!! Note "No data available"
Returns an empty dataframe if the requested pair was not cached. Returns an empty dataframe if the requested pair was not cached.
This should not happen when using whitelisted pairs. This should not happen when using whitelisted pairs.
!!! Warning "Warning about backtesting"
This method will return an empty dataframe during backtesting.
### *orderbook(pair, maximum)* ### *orderbook(pair, maximum)*
``` python ``` python
@@ -462,8 +436,28 @@ if self.dp:
dataframe['best_ask'] = ob['asks'][0][0] dataframe['best_ask'] = ob['asks'][0][0]
``` ```
!!! Warning The orderbook structure is aligned with the order structure from [ccxt](https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure), so the result will look as follows:
The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used.
``` js
{
'bids': [
[ price, amount ], // [ float, float ]
[ price, amount ],
...
],
'asks': [
[ price, amount ],
[ price, amount ],
//...
],
//...
}
```
Therefore, using `ob['bids'][0][0]` as demonstrated above will result in using the best bid price. `ob['bids'][0][1]` would look at the amount at this orderbook position.
!!! Warning "Warning about backtesting"
The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used, as the method will return uptodate values.
### *ticker(pair)* ### *ticker(pair)*
@@ -613,6 +607,43 @@ All columns of the informative dataframe will be available on the returning data
*** ***
### *stoploss_from_open()*
Stoploss values returned from `custom_stoploss` must specify a percentage relative to `current_rate`, but sometimes you may want to specify a stoploss relative to the open price instead. `stoploss_from_open()` is a helper function to calculate a stoploss value that can be returned from `custom_stoploss` which will be equivalent to the desired percentage above the open price.
??? Example "Returning a stoploss relative to the open price from the custom stoploss function"
Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21`).
If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100.
``` python
from datetime import datetime
from freqtrade.persistence import Trade
from freqtrade.strategy import IStrategy, stoploss_from_open
class AwesomeStrategy(IStrategy):
# ... populate_* methods
use_custom_stoploss = True
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
current_rate: float, current_profit: float, **kwargs) -> float:
# once the profit has risin above 10%, keep the stoploss at 7% above the open price
if current_profit > 0.10:
return stoploss_from_open(0.07, current_profit)
return 1
```
Full examples can be found in the [Custom stoploss](strategy-advanced.md#custom-stoploss) section of the Documentation.
## Additional data (Wallets) ## Additional data (Wallets)
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange. The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
@@ -653,7 +684,7 @@ The following example queries for the current pair and trades from today, howeve
if self.config['runmode'].value in ('live', 'dry_run'): if self.config['runmode'].value in ('live', 'dry_run'):
trades = Trade.get_trades([Trade.pair == metadata['pair'], trades = Trade.get_trades([Trade.pair == metadata['pair'],
Trade.open_date > datetime.utcnow() - timedelta(days=1), Trade.open_date > datetime.utcnow() - timedelta(days=1),
Trade.is_open == False, Trade.is_open.is_(False),
]).order_by(Trade.close_date).all() ]).order_by(Trade.close_date).all()
# Summarize profit for this pair. # Summarize profit for this pair.
curdayprofit = sum(trade.close_profit for trade in trades) curdayprofit = sum(trade.close_profit for trade in trades)
@@ -704,7 +735,7 @@ To verify if a pair is currently locked, use `self.is_pair_locked(pair)`.
Locked pairs will always be rounded up to the next candle. So assuming a `5m` timeframe, a lock with `until` set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished. Locked pairs will always be rounded up to the next candle. So assuming a `5m` timeframe, a lock with `until` set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished.
!!! Warning !!! Warning
Locking pairs is not available during backtesting. Manually locking pairs is not available during backtesting, only locks via Protections are allowed.
#### Pair locking example #### Pair locking example
@@ -719,7 +750,7 @@ if self.config['runmode'].value in ('live', 'dry_run'):
# fetch closed trades for the last 2 days # fetch closed trades for the last 2 days
trades = Trade.get_trades([Trade.pair == metadata['pair'], trades = Trade.get_trades([Trade.pair == metadata['pair'],
Trade.open_date > datetime.utcnow() - timedelta(days=2), Trade.open_date > datetime.utcnow() - timedelta(days=2),
Trade.is_open == False, Trade.is_open.is_(False),
]).all() ]).all()
# Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy
sumprofit = sum(trade.close_profit for trade in trades) sumprofit = sum(trade.close_profit for trade in trades)

View File

@@ -24,7 +24,7 @@ config["strategy"] = "SampleStrategy"
# Location of the data # Location of the data
data_location = Path(config['user_data_dir'], 'data', 'binance') data_location = Path(config['user_data_dir'], 'data', 'binance')
# Pair to analyze - Only use one pair here # Pair to analyze - Only use one pair here
pair = "BTC_USDT" pair = "BTC/USDT"
``` ```
@@ -34,7 +34,9 @@ from freqtrade.data.history import load_pair_history
candles = load_pair_history(datadir=data_location, candles = load_pair_history(datadir=data_location,
timeframe=config["timeframe"], timeframe=config["timeframe"],
pair=pair) pair=pair,
data_format = "hdf5",
)
# Confirm success # Confirm success
print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}") print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}")

View File

@@ -83,10 +83,13 @@ Example configuration showing the different settings:
"sell": "on", "sell": "on",
"buy_cancel": "silent", "buy_cancel": "silent",
"sell_cancel": "on" "sell_cancel": "on"
} },
"balance_dust_level": 0.01
}, },
``` ```
`balance_dust_level` will define what the `/balance` command takes as "dust" - Currencies with a balance below this will be shown.
## Create a custom keyboard (command shortcut buttons) ## Create a custom keyboard (command shortcut buttons)
Telegram allows us to create a custom keyboard with buttons for commands. Telegram allows us to create a custom keyboard with buttons for commands.
@@ -137,11 +140,13 @@ official commands. You can ask at any moment for help with `/help`.
| `/show_config` | Shows part of the current configuration with relevant settings to operation | `/show_config` | Shows part of the current configuration with relevant settings to operation
| `/logs [limit]` | Show last log messages. | `/logs [limit]` | Show last log messages.
| `/status` | Lists all open trades | `/status` | Lists all open trades
| `/status <trade_id>` | Lists one or more specific trade. Separate multiple <trade_id> with a blank space.
| `/status table` | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**) | `/status table` | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
| `/trades [limit]` | List all recently closed trades in a table format. | `/trades [limit]` | List all recently closed trades in a table format.
| `/delete <trade_id>` | Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange. | `/delete <trade_id>` | Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange.
| `/count` | Displays number of trades used and available | `/count` | Displays number of trades used and available
| `/locks` | Show currently locked pairs. | `/locks` | Show currently locked pairs.
| `/unlock <pair or lock_id>` | Remove the lock for this pair (or for this lock id).
| `/profit` | Display a summary of your profit/loss from close trades and some stats about your performance | `/profit` | Display a summary of your profit/loss from close trades and some stats about your performance
| `/forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`). | `/forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`).
| `/forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`). | `/forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`).

View File

@@ -391,7 +391,7 @@ $ freqtrade list-markets --exchange kraken --all
## Test pairlist ## Test pairlist
Use the `test-pairlist` subcommand to test the configuration of [dynamic pairlists](configuration.md#pairlists). Use the `test-pairlist` subcommand to test the configuration of [dynamic pairlists](plugins.md#pairlists).
Requires a configuration with specified `pairlists` attribute. Requires a configuration with specified `pairlists` attribute.
Can be used to generate static pairlists to be used during backtesting / hyperopt. Can be used to generate static pairlists to be used during backtesting / hyperopt.
@@ -415,7 +415,7 @@ optional arguments:
### Examples ### Examples
Show whitelist when using a [dynamic pairlist](configuration.md#pairlists). Show whitelist when using a [dynamic pairlist](plugins.md#pairlists).
``` ```
freqtrade test-pairlist --config config.json --quote USDT BTC freqtrade test-pairlist --config config.json --quote USDT BTC

View File

@@ -40,6 +40,21 @@ Sample configuration (tested using IFTTT).
The url in `webhook.url` should point to the correct url for your webhook. If you're using [IFTTT](https://ifttt.com) (as shown in the sample above) please insert our event and key to the url. The url in `webhook.url` should point to the correct url for your webhook. If you're using [IFTTT](https://ifttt.com) (as shown in the sample above) please insert our event and key to the url.
You can set the POST body format to Form-Encoded (default) or JSON-Encoded. Use `"format": "form"` or `"format": "json"` respectively. Example configuration for Mattermost Cloud integration:
```json
"webhook": {
"enabled": true,
"url": "https://<YOURSUBDOMAIN>.cloud.mattermost.com/hooks/<YOURHOOK>",
"format": "json",
"webhookstatus": {
"text": "Status: {status}"
}
},
```
The result would be POST request with e.g. `{"text":"Status: running"}` body and `Content-Type: application/json` header which results `Status: running` message in the Mattermost channel.
Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called. Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called.
### Webhookbuy ### Webhookbuy

View File

@@ -1,4 +1,4 @@
We **strongly** recommend that Windows users use [Docker](docker.md) as this will work much easier and smoother (also more secure). We **strongly** recommend that Windows users use [Docker](docker_quickstart.md) as this will work much easier and smoother (also more secure).
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work. If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work.
Otherwise, try the instructions below. Otherwise, try the instructions below.
@@ -52,6 +52,6 @@ error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++
Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use. Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building C code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or [docker](docker.md) first. The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building C code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or [docker compose](docker_quickstart.md) first.
--- ---

View File

@@ -1,60 +1,71 @@
name: freqtrade name: freqtrade
channels: channels:
- defaults
- conda-forge - conda-forge
# - defaults
dependencies: dependencies:
# Required for app # 1/4 req main
- python>=3.7 - python>=3.7
- pip - numpy
- wheel - pandas
- numpy - pip
- pandas
- SQLAlchemy - aiohttp
- arrow - SQLAlchemy
- requests - python-telegram-bot
- urllib3 - arrow
- wrapt - cachetools
- jsonschema - requests
- tabulate - urllib3
- python-rapidjson - wrapt
- flask - jsonschema
- python-dotenv
- cachetools
- python-telegram-bot
# Optional for plotting
- plotly
# Optional for hyperopt
- scipy
- scikit-optimize
- scikit-learn
- filelock
- joblib
# Optional for development
- flake8
- pytest
- pytest-mock
- pytest-asyncio
- pytest-cov
- coveralls
- mypy
# Useful for jupyter
- jupyter
- ipykernel
- isort
- yapf
- pip:
# Required for app
- cython
- pycoingecko
- ccxt
- TA-Lib - TA-Lib
- py_find_1st - tabulate
- jinja2
- blosc
- sdnotify - sdnotify
# Optional for develpment - fastapi
- flake8-tidy-imports - uvicorn
- flake8-type-annotations - pyjwt
- pytest-random-order - colorama
- -e . - questionary
- prompt-toolkit
# ============================
# 2/4 req dev
- coveralls
- flake8
- mypy
- pytest
- pytest-asyncio
- pytest-cov
- pytest-mock
- isort
- nbconvert
# ============================
# 3/4 req hyperopt
- scipy
- scikit-learn
- filelock
- scikit-optimize
- joblib
- progressbar2
# ============================
# 4/4 req plot
- plotly
- jupyter
- pip:
- pycoingecko
- py_find_1st
- tables
- pytest-random-order
- flake8-type-annotations
- ccxt
- flake8-tidy-imports
- -e .
# - python-rapidjso

View File

@@ -1,5 +1,5 @@
""" Freqtrade bot """ """ Freqtrade bot """
__version__ = '2020.12' __version__ = '2021.3'
if __version__ == 'develop': if __version__ == 'develop':

View File

@@ -10,8 +10,8 @@ from freqtrade.commands.arguments import Arguments
from freqtrade.commands.build_config_commands import start_new_config from freqtrade.commands.build_config_commands import start_new_config
from freqtrade.commands.data_commands import (start_convert_data, start_download_data, from freqtrade.commands.data_commands import (start_convert_data, start_download_data,
start_list_data) start_list_data)
from freqtrade.commands.deploy_commands import (start_create_userdir, start_new_hyperopt, from freqtrade.commands.deploy_commands import (start_create_userdir, start_install_ui,
start_new_strategy) start_new_hyperopt, start_new_strategy)
from freqtrade.commands.hyperopt_commands import start_hyperopt_list, start_hyperopt_show from freqtrade.commands.hyperopt_commands import start_hyperopt_list, start_hyperopt_show
from freqtrade.commands.list_commands import (start_list_exchanges, start_list_hyperopts, from freqtrade.commands.list_commands import (start_list_exchanges, start_list_hyperopts,
start_list_markets, start_list_strategies, start_list_markets, start_list_strategies,

View File

@@ -14,18 +14,18 @@ ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_dat
ARGS_STRATEGY = ["strategy", "strategy_path"] ARGS_STRATEGY = ["strategy", "strategy_path"]
ARGS_TRADE = ["db_url", "sd_notify", "dry_run"] ARGS_TRADE = ["db_url", "sd_notify", "dry_run", "dry_run_wallet", "fee"]
ARGS_COMMON_OPTIMIZE = ["timeframe", "timerange", "dataformat_ohlcv", ARGS_COMMON_OPTIMIZE = ["timeframe", "timerange", "dataformat_ohlcv",
"max_open_trades", "stake_amount", "fee"] "max_open_trades", "stake_amount", "fee"]
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions", ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
"enable_protections", "enable_protections", "dry_run_wallet",
"strategy_list", "export", "exportfilename"] "strategy_list", "export", "exportfilename"]
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path", ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
"position_stacking", "use_max_market_positions", "position_stacking", "use_max_market_positions",
"enable_protections", "enable_protections", "dry_run_wallet",
"epochs", "spaces", "print_all", "epochs", "spaces", "print_all",
"print_colorized", "print_json", "hyperopt_jobs", "print_colorized", "print_json", "hyperopt_jobs",
"hyperopt_random_state", "hyperopt_min_trades", "hyperopt_random_state", "hyperopt_min_trades",
@@ -70,6 +70,8 @@ ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url", ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
"trade_source", "timeframe"] "trade_source", "timeframe"]
ARGS_INSTALL_UI = ["erase_ui_only"]
ARGS_SHOW_TRADES = ["db_url", "trade_ids", "print_json"] ARGS_SHOW_TRADES = ["db_url", "trade_ids", "print_json"]
ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable", ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable",
@@ -167,8 +169,8 @@ class Arguments:
from freqtrade.commands import (start_backtesting, start_convert_data, start_create_userdir, from freqtrade.commands import (start_backtesting, start_convert_data, start_create_userdir,
start_download_data, start_edge, start_hyperopt, start_download_data, start_edge, start_hyperopt,
start_hyperopt_list, start_hyperopt_show, start_list_data, start_hyperopt_list, start_hyperopt_show, start_install_ui,
start_list_exchanges, start_list_hyperopts, start_list_data, start_list_exchanges, start_list_hyperopts,
start_list_markets, start_list_strategies, start_list_markets, start_list_strategies,
start_list_timeframes, start_new_config, start_new_hyperopt, start_list_timeframes, start_new_config, start_new_hyperopt,
start_new_strategy, start_plot_dataframe, start_plot_profit, start_new_strategy, start_plot_dataframe, start_plot_profit,
@@ -355,6 +357,14 @@ class Arguments:
test_pairlist_cmd.set_defaults(func=start_test_pairlist) test_pairlist_cmd.set_defaults(func=start_test_pairlist)
self._build_args(optionlist=ARGS_TEST_PAIRLIST, parser=test_pairlist_cmd) self._build_args(optionlist=ARGS_TEST_PAIRLIST, parser=test_pairlist_cmd)
# Add install-ui subcommand
install_ui_cmd = subparsers.add_parser(
'install-ui',
help='Install FreqUI',
)
install_ui_cmd.set_defaults(func=start_install_ui)
self._build_args(optionlist=ARGS_INSTALL_UI, parser=install_ui_cmd)
# Add Plotting subcommand # Add Plotting subcommand
plot_dataframe_cmd = subparsers.add_parser( plot_dataframe_cmd = subparsers.add_parser(
'plot-dataframe', 'plot-dataframe',

View File

@@ -93,10 +93,10 @@ def ask_user_config() -> Dict[str, Any]:
"message": "Select exchange", "message": "Select exchange",
"choices": [ "choices": [
"binance", "binance",
"binanceje",
"binanceus", "binanceus",
"bittrex", "bittrex",
"kraken", "kraken",
"ftx",
Separator(), Separator(),
"other", "other",
], ],
@@ -173,6 +173,9 @@ def deploy_new_config(config_path: Path, selections: Dict[str, Any]) -> None:
arguments=selections) arguments=selections)
logger.info(f"Writing config to `{config_path}`.") logger.info(f"Writing config to `{config_path}`.")
logger.info(
"Please make sure to check the configuration contents and adjust settings to your needs.")
config_path.write_text(config_text) config_path.write_text(config_text)

View File

@@ -110,6 +110,11 @@ AVAILABLE_CLI_OPTIONS = {
help='Enforce dry-run for trading (removes Exchange secrets and simulates trades).', help='Enforce dry-run for trading (removes Exchange secrets and simulates trades).',
action='store_true', action='store_true',
), ),
"dry_run_wallet": Arg(
'--dry-run-wallet', '--starting-balance',
help='Starting balance, used for backtesting / hyperopt and dry-runs.',
type=float,
),
# Optimize common # Optimize common
"timeframe": Arg( "timeframe": Arg(
'-i', '--timeframe', '--ticker-interval', '-i', '--timeframe', '--ticker-interval',
@@ -128,7 +133,6 @@ AVAILABLE_CLI_OPTIONS = {
"stake_amount": Arg( "stake_amount": Arg(
'--stake-amount', '--stake-amount',
help='Override the value of the `stake_amount` configuration setting.', help='Override the value of the `stake_amount` configuration setting.',
type=float,
), ),
# Backtesting # Backtesting
"position_stacking": Arg( "position_stacking": Arg(
@@ -387,6 +391,12 @@ AVAILABLE_CLI_OPTIONS = {
help='Clean all existing data for the selected exchange/pairs/timeframes.', help='Clean all existing data for the selected exchange/pairs/timeframes.',
action='store_true', action='store_true',
), ),
"erase_ui_only": Arg(
'--erase',
help="Clean UI folder, don't download new version.",
action='store_true',
default=False,
),
# Templating options # Templating options
"template": Arg( "template": Arg(
'--template', '--template',

View File

@@ -10,6 +10,7 @@ from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_oh
refresh_backtest_trades_data) refresh_backtest_trades_data)
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import timeframe_to_minutes
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.resolvers import ExchangeResolver from freqtrade.resolvers import ExchangeResolver
from freqtrade.state import RunMode from freqtrade.state import RunMode
@@ -42,15 +43,17 @@ def start_download_data(args: Dict[str, Any]) -> None:
"Downloading data requires a list of pairs. " "Downloading data requires a list of pairs. "
"Please check the documentation on how to configure this.") "Please check the documentation on how to configure this.")
logger.info(f"About to download pairs: {config['pairs']}, "
f"intervals: {config['timeframes']} to {config['datadir']}")
pairs_not_available: List[str] = [] pairs_not_available: List[str] = []
# Init exchange # Init exchange
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False) exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
# Manual validations of relevant settings # Manual validations of relevant settings
exchange.validate_pairs(config['pairs']) exchange.validate_pairs(config['pairs'])
expanded_pairs = expand_pairlist(config['pairs'], list(exchange.markets))
logger.info(f"About to download pairs: {expanded_pairs}, "
f"intervals: {config['timeframes']} to {config['datadir']}")
for timeframe in config['timeframes']: for timeframe in config['timeframes']:
exchange.validate_timeframes(timeframe) exchange.validate_timeframes(timeframe)
@@ -58,20 +61,20 @@ def start_download_data(args: Dict[str, Any]) -> None:
if config.get('download_trades'): if config.get('download_trades'):
pairs_not_available = refresh_backtest_trades_data( pairs_not_available = refresh_backtest_trades_data(
exchange, pairs=config['pairs'], datadir=config['datadir'], exchange, pairs=expanded_pairs, datadir=config['datadir'],
timerange=timerange, erase=bool(config.get('erase')), timerange=timerange, erase=bool(config.get('erase')),
data_format=config['dataformat_trades']) data_format=config['dataformat_trades'])
# Convert downloaded trade data to different timeframes # Convert downloaded trade data to different timeframes
convert_trades_to_ohlcv( convert_trades_to_ohlcv(
pairs=config['pairs'], timeframes=config['timeframes'], pairs=expanded_pairs, timeframes=config['timeframes'],
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')), datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
data_format_ohlcv=config['dataformat_ohlcv'], data_format_ohlcv=config['dataformat_ohlcv'],
data_format_trades=config['dataformat_trades'], data_format_trades=config['dataformat_trades'],
) )
else: else:
pairs_not_available = refresh_backtest_ohlcv_data( pairs_not_available = refresh_backtest_ohlcv_data(
exchange, pairs=config['pairs'], timeframes=config['timeframes'], exchange, pairs=expanded_pairs, timeframes=config['timeframes'],
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')), datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
data_format=config['dataformat_ohlcv']) data_format=config['dataformat_ohlcv'])

View File

@@ -1,7 +1,9 @@
import logging import logging
import sys import sys
from pathlib import Path from pathlib import Path
from typing import Any, Dict from typing import Any, Dict, Optional, Tuple
import requests
from freqtrade.configuration import setup_utils_configuration from freqtrade.configuration import setup_utils_configuration
from freqtrade.configuration.directory_operations import copy_sample_files, create_userdata_dir from freqtrade.configuration.directory_operations import copy_sample_files, create_userdata_dir
@@ -137,3 +139,87 @@ def start_new_hyperopt(args: Dict[str, Any]) -> None:
deploy_new_hyperopt(args['hyperopt'], new_path, args['template']) deploy_new_hyperopt(args['hyperopt'], new_path, args['template'])
else: else:
raise OperationalException("`new-hyperopt` requires --hyperopt to be set.") raise OperationalException("`new-hyperopt` requires --hyperopt to be set.")
def clean_ui_subdir(directory: Path):
if directory.is_dir():
logger.info("Removing UI directory content.")
for p in reversed(list(directory.glob('**/*'))): # iterate contents from leaves to root
if p.name in ('.gitkeep', 'fallback_file.html'):
continue
if p.is_file():
p.unlink()
elif p.is_dir():
p.rmdir()
def read_ui_version(dest_folder: Path) -> Optional[str]:
file = dest_folder / '.uiversion'
if not file.is_file():
return None
with file.open('r') as f:
return f.read()
def download_and_install_ui(dest_folder: Path, dl_url: str, version: str):
from io import BytesIO
from zipfile import ZipFile
logger.info(f"Downloading {dl_url}")
resp = requests.get(dl_url).content
dest_folder.mkdir(parents=True, exist_ok=True)
with ZipFile(BytesIO(resp)) as zf:
for fn in zf.filelist:
with zf.open(fn) as x:
destfile = dest_folder / fn.filename
if fn.is_dir():
destfile.mkdir(exist_ok=True)
else:
destfile.write_bytes(x.read())
with (dest_folder / '.uiversion').open('w') as f:
f.write(version)
def get_ui_download_url() -> Tuple[str, str]:
base_url = 'https://api.github.com/repos/freqtrade/frequi/'
# Get base UI Repo path
resp = requests.get(f"{base_url}releases")
resp.raise_for_status()
r = resp.json()
latest_version = r[0]['name']
assets = r[0].get('assets', [])
dl_url = ''
if assets and len(assets) > 0:
dl_url = assets[0]['browser_download_url']
# URL not found - try assets url
if not dl_url:
assets = r[0]['assets_url']
resp = requests.get(assets)
r = resp.json()
dl_url = r[0]['browser_download_url']
return dl_url, latest_version
def start_install_ui(args: Dict[str, Any]) -> None:
dest_folder = Path(__file__).parents[1] / 'rpc/api_server/ui/installed/'
# First make sure the assets are removed.
dl_url, latest_version = get_ui_download_url()
curr_version = read_ui_version(dest_folder)
if curr_version == latest_version and not args.get('erase_ui_only'):
logger.info(f"UI already up-to-date, FreqUI Version {curr_version}.")
return
clean_ui_subdir(dest_folder)
if args.get('erase_ui_only'):
logger.info("Erased UI directory content. Not downloading new version.")
else:
# Download a new version
download_and_install_ui(dest_folder, dl_url, latest_version)

View File

@@ -17,7 +17,7 @@ def start_hyperopt_list(args: Dict[str, Any]) -> None:
""" """
List hyperopt epochs previously evaluated List hyperopt epochs previously evaluated
""" """
from freqtrade.optimize.hyperopt import Hyperopt from freqtrade.optimize.hyperopt_tools import HyperoptTools
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
@@ -47,7 +47,7 @@ def start_hyperopt_list(args: Dict[str, Any]) -> None:
config.get('hyperoptexportfilename')) config.get('hyperoptexportfilename'))
# Previous evaluations # Previous evaluations
epochs = Hyperopt.load_previous_results(results_file) epochs = HyperoptTools.load_previous_results(results_file)
total_epochs = len(epochs) total_epochs = len(epochs)
epochs = hyperopt_filter_epochs(epochs, filteroptions) epochs = hyperopt_filter_epochs(epochs, filteroptions)
@@ -57,18 +57,19 @@ def start_hyperopt_list(args: Dict[str, Any]) -> None:
if not export_csv: if not export_csv:
try: try:
print(Hyperopt.get_result_table(config, epochs, total_epochs, print(HyperoptTools.get_result_table(config, epochs, total_epochs,
not filteroptions['only_best'], print_colorized, 0)) not filteroptions['only_best'],
print_colorized, 0))
except KeyboardInterrupt: except KeyboardInterrupt:
print('User interrupted..') print('User interrupted..')
if epochs and not no_details: if epochs and not no_details:
sorted_epochs = sorted(epochs, key=itemgetter('loss')) sorted_epochs = sorted(epochs, key=itemgetter('loss'))
results = sorted_epochs[0] results = sorted_epochs[0]
Hyperopt.print_epoch_details(results, total_epochs, print_json, no_header) HyperoptTools.print_epoch_details(results, total_epochs, print_json, no_header)
if epochs and export_csv: if epochs and export_csv:
Hyperopt.export_csv_file( HyperoptTools.export_csv_file(
config, epochs, total_epochs, not filteroptions['only_best'], export_csv config, epochs, total_epochs, not filteroptions['only_best'], export_csv
) )
@@ -77,7 +78,7 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
""" """
Show details of a hyperopt epoch previously evaluated Show details of a hyperopt epoch previously evaluated
""" """
from freqtrade.optimize.hyperopt import Hyperopt from freqtrade.optimize.hyperopt_tools import HyperoptTools
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
@@ -105,7 +106,7 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
} }
# Previous evaluations # Previous evaluations
epochs = Hyperopt.load_previous_results(results_file) epochs = HyperoptTools.load_previous_results(results_file)
total_epochs = len(epochs) total_epochs = len(epochs)
epochs = hyperopt_filter_epochs(epochs, filteroptions) epochs = hyperopt_filter_epochs(epochs, filteroptions)
@@ -124,8 +125,8 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
if epochs: if epochs:
val = epochs[n] val = epochs[n]
Hyperopt.print_epoch_details(val, total_epochs, print_json, no_header, HyperoptTools.print_epoch_details(val, total_epochs, print_json, no_header,
header_str="Epoch details") header_str="Epoch details")
def hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List: def hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:

View File

@@ -3,7 +3,8 @@ from typing import Any, Dict
from freqtrade import constants from freqtrade import constants
from freqtrade.configuration import setup_utils_configuration from freqtrade.configuration import setup_utils_configuration
from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.misc import round_coin_value
from freqtrade.state import RunMode from freqtrade.state import RunMode
@@ -22,11 +23,13 @@ def setup_optimize_configuration(args: Dict[str, Any], method: RunMode) -> Dict[
RunMode.BACKTEST: 'backtesting', RunMode.BACKTEST: 'backtesting',
RunMode.HYPEROPT: 'hyperoptimization', RunMode.HYPEROPT: 'hyperoptimization',
} }
if (method in no_unlimited_runmodes.keys() and if method in no_unlimited_runmodes.keys():
config['stake_amount'] == constants.UNLIMITED_STAKE_AMOUNT): if (config['stake_amount'] != constants.UNLIMITED_STAKE_AMOUNT
raise DependencyException( and config['stake_amount'] > config['dry_run_wallet']):
f'The value of `stake_amount` cannot be set as "{constants.UNLIMITED_STAKE_AMOUNT}" ' wallet = round_coin_value(config['dry_run_wallet'], config['stake_currency'])
f'for {no_unlimited_runmodes[method]}') stake = round_coin_value(config['stake_amount'], config['stake_currency'])
raise OperationalException(f"Starting balance ({wallet}) "
f"is smaller than stake_amount {stake}.")
return config return config

View File

@@ -47,6 +47,8 @@ def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
conf_schema = deepcopy(constants.CONF_SCHEMA) conf_schema = deepcopy(constants.CONF_SCHEMA)
if conf.get('runmode', RunMode.OTHER) in (RunMode.DRY_RUN, RunMode.LIVE): if conf.get('runmode', RunMode.OTHER) in (RunMode.DRY_RUN, RunMode.LIVE):
conf_schema['required'] = constants.SCHEMA_TRADE_REQUIRED conf_schema['required'] = constants.SCHEMA_TRADE_REQUIRED
elif conf.get('runmode', RunMode.OTHER) in (RunMode.BACKTEST, RunMode.HYPEROPT):
conf_schema['required'] = constants.SCHEMA_BACKTEST_REQUIRED
else: else:
conf_schema['required'] = constants.SCHEMA_MINIMAL_REQUIRED conf_schema['required'] = constants.SCHEMA_MINIMAL_REQUIRED
try: try:
@@ -54,7 +56,7 @@ def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
return conf return conf
except ValidationError as e: except ValidationError as e:
logger.critical( logger.critical(
f"Invalid configuration. See config.json.example. Reason: {e}" f"Invalid configuration. Reason: {e}"
) )
raise ValidationError( raise ValidationError(
best_match(Draft4Validator(conf_schema).iter_errors(conf)).message best_match(Draft4Validator(conf_schema).iter_errors(conf)).message
@@ -72,6 +74,7 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
# validating trailing stoploss # validating trailing stoploss
_validate_trailing_stoploss(conf) _validate_trailing_stoploss(conf)
_validate_price_config(conf)
_validate_edge(conf) _validate_edge(conf)
_validate_whitelist(conf) _validate_whitelist(conf)
_validate_protections(conf) _validate_protections(conf)
@@ -93,6 +96,19 @@ def _validate_unlimited_amount(conf: Dict[str, Any]) -> None:
raise OperationalException("`max_open_trades` and `stake_amount` cannot both be unlimited.") raise OperationalException("`max_open_trades` and `stake_amount` cannot both be unlimited.")
def _validate_price_config(conf: Dict[str, Any]) -> None:
"""
When using market orders, price sides must be using the "other" side of the price
"""
if (conf.get('order_types', {}).get('buy') == 'market'
and conf.get('bid_strategy', {}).get('price_side') != 'ask'):
raise OperationalException('Market buy orders require bid_strategy.price_side = "ask".')
if (conf.get('order_types', {}).get('sell') == 'market'
and conf.get('ask_strategy', {}).get('price_side') != 'bid'):
raise OperationalException('Market sell orders require ask_strategy.price_side = "bid".')
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None: def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
if conf.get('stoploss') == 0.0: if conf.get('stoploss') == 0.0:

View File

@@ -214,9 +214,6 @@ class Configuration:
self._args_to_config( self._args_to_config(
config, argname='enable_protections', config, argname='enable_protections',
logstring='Parameter --enable-protections detected, enabling Protections. ...') logstring='Parameter --enable-protections detected, enabling Protections. ...')
# Setting max_open_trades to infinite if -1
if config.get('max_open_trades') == -1:
config['max_open_trades'] = float('inf')
if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]: if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]:
config.update({'use_max_market_positions': False}) config.update({'use_max_market_positions': False})
@@ -228,11 +225,23 @@ class Configuration:
'overriding max_open_trades to: %s ...', config.get('max_open_trades')) 'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
elif config['runmode'] in NON_UTIL_MODES: elif config['runmode'] in NON_UTIL_MODES:
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades')) logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
# Setting max_open_trades to infinite if -1
if config.get('max_open_trades') == -1:
config['max_open_trades'] = float('inf')
if self.args.get('stake_amount', None):
# Convert explicitly to float to support CLI argument for both unlimited and value
try:
self.args['stake_amount'] = float(self.args['stake_amount'])
except ValueError:
pass
self._args_to_config(config, argname='stake_amount', self._args_to_config(config, argname='stake_amount',
logstring='Parameter --stake-amount detected, ' logstring='Parameter --stake-amount detected, '
'overriding stake_amount to: {} ...') 'overriding stake_amount to: {} ...')
self._args_to_config(config, argname='dry_run_wallet',
logstring='Parameter --dry-run-wallet detected, '
'overriding dry_run_wallet to: {} ...')
self._args_to_config(config, argname='fee', self._args_to_config(config, argname='fee',
logstring='Parameter --fee detected, ' logstring='Parameter --fee detected, '
'setting fee to: {} ...') 'setting fee to: {} ...')

View File

@@ -7,6 +7,8 @@ from typing import Optional
import arrow import arrow
from freqtrade.exceptions import OperationalException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -103,5 +105,8 @@ class TimeRange:
stop = int(stops) // 1000 stop = int(stops) // 1000
else: else:
stop = int(stops) stop = int(stops)
if start > stop > 0:
raise OperationalException(
f'Start date is after stop date for timerange "{text}"')
return TimeRange(stype[0], stype[1], start, stop) return TimeRange(stype[0], stype[1], start, stop)
raise Exception('Incorrect syntax for timerange "%s"' % text) raise OperationalException(f'Incorrect syntax for timerange "{text}"')

View File

@@ -45,6 +45,21 @@ USERPATH_NOTEBOOKS = 'notebooks'
TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent'] TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent']
# Define decimals per coin for outputs
# Only used for outputs.
DECIMAL_PER_COIN_FALLBACK = 3 # Should be low to avoid listing all possible FIAT's
DECIMALS_PER_COIN = {
'BTC': 8,
'ETH': 5,
}
DUST_PER_COIN = {
'BTC': 0.0001,
'ETH': 0.01
}
# Soure files with destination directories within user-directory # Soure files with destination directories within user-directory
USER_DATA_FILES = { USER_DATA_FILES = {
'sample_strategy.py': USERPATH_STRATEGIES, 'sample_strategy.py': USERPATH_STRATEGIES,
@@ -116,6 +131,7 @@ CONF_SCHEMA = {
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1}, 'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1}, 'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
'trailing_only_offset_is_reached': {'type': 'boolean'}, 'trailing_only_offset_is_reached': {'type': 'boolean'},
'bot_name': {'type': 'string'},
'unfilledtimeout': { 'unfilledtimeout': {
'type': 'object', 'type': 'object',
'properties': { 'properties': {
@@ -149,11 +165,18 @@ CONF_SCHEMA = {
'type': 'object', 'type': 'object',
'properties': { 'properties': {
'price_side': {'type': 'string', 'enum': ORDERBOOK_SIDES, 'default': 'ask'}, 'price_side': {'type': 'string', 'enum': ORDERBOOK_SIDES, 'default': 'ask'},
'bid_last_balance': {
'type': 'number',
'minimum': 0,
'maximum': 1,
'exclusiveMaximum': False,
},
'use_order_book': {'type': 'boolean'}, 'use_order_book': {'type': 'boolean'},
'order_book_min': {'type': 'integer', 'minimum': 1}, 'order_book_min': {'type': 'integer', 'minimum': 1},
'order_book_max': {'type': 'integer', 'minimum': 1, 'maximum': 50}, 'order_book_max': {'type': 'integer', 'minimum': 1, 'maximum': 50},
'use_sell_signal': {'type': 'boolean'}, 'use_sell_signal': {'type': 'boolean'},
'sell_profit_only': {'type': 'boolean'}, 'sell_profit_only': {'type': 'boolean'},
'sell_profit_offset': {'type': 'number', 'minimum': 0.0},
'ignore_roi_if_buy_signal': {'type': 'boolean'} 'ignore_roi_if_buy_signal': {'type': 'boolean'}
} }
}, },
@@ -162,6 +185,8 @@ CONF_SCHEMA = {
'properties': { 'properties': {
'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES}, 'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES}, 'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
'forcesell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
'forcebuy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
'emergencysell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES}, 'emergencysell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES}, 'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
'stoploss_on_exchange': {'type': 'boolean'}, 'stoploss_on_exchange': {'type': 'boolean'},
@@ -218,6 +243,7 @@ CONF_SCHEMA = {
'enabled': {'type': 'boolean'}, 'enabled': {'type': 'boolean'},
'token': {'type': 'string'}, 'token': {'type': 'string'},
'chat_id': {'type': 'string'}, 'chat_id': {'type': 'string'},
'balance_dust_level': {'type': 'number', 'minimum': 0.0},
'notification_settings': { 'notification_settings': {
'type': 'object', 'type': 'object',
'properties': { 'properties': {
@@ -231,7 +257,7 @@ CONF_SCHEMA = {
} }
} }
}, },
'required': ['enabled', 'token', 'chat_id'] 'required': ['enabled', 'token', 'chat_id'],
}, },
'webhook': { 'webhook': {
'type': 'object', 'type': 'object',
@@ -358,6 +384,16 @@ SCHEMA_TRADE_REQUIRED = [
'dataformat_trades', 'dataformat_trades',
] ]
SCHEMA_BACKTEST_REQUIRED = [
'exchange',
'max_open_trades',
'stake_currency',
'stake_amount',
'dry_run_wallet',
'dataformat_ohlcv',
'dataformat_trades',
]
SCHEMA_MINIMAL_REQUIRED = [ SCHEMA_MINIMAL_REQUIRED = [
'exchange', 'exchange',
'dry_run', 'dry_run',

View File

@@ -2,23 +2,35 @@
Helpers when analyzing backtest data Helpers when analyzing backtest data
""" """
import logging import logging
from datetime import timezone
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from freqtrade.constants import LAST_BT_RESULT_FN from freqtrade.constants import LAST_BT_RESULT_FN
from freqtrade.misc import json_load from freqtrade.misc import json_load
from freqtrade.persistence import Trade, init_db from freqtrade.persistence import LocalTrade, Trade, init_db
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# must align with columns in backtest.py # Old format - maybe remove?
BT_DATA_COLUMNS = ["pair", "profit_percent", "open_date", "close_date", "index", "trade_duration", BT_DATA_COLUMNS_OLD = ["pair", "profit_percent", "open_date", "close_date", "index",
"open_rate", "close_rate", "open_at_end", "sell_reason"] "trade_duration", "open_rate", "close_rate", "open_at_end", "sell_reason"]
# Mid-term format, crated by BacktestResult Named Tuple
BT_DATA_COLUMNS_MID = ['pair', 'profit_percent', 'open_date', 'close_date', 'trade_duration',
'open_rate', 'close_rate', 'open_at_end', 'sell_reason', 'fee_open',
'fee_close', 'amount', 'profit_abs', 'profit_ratio']
# Newest format
BT_DATA_COLUMNS = ['pair', 'stake_amount', 'amount', 'open_date', 'close_date',
'open_rate', 'close_rate',
'fee_open', 'fee_close', 'trade_duration',
'profit_ratio', 'profit_abs', 'sell_reason',
'initial_stop_loss_abs', 'initial_stop_loss_ratio', 'stop_loss_abs',
'stop_loss_ratio', 'min_rate', 'max_rate', 'is_open', ]
def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str: def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str:
@@ -154,7 +166,7 @@ def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = Non
) )
else: else:
# old format - only with lists. # old format - only with lists.
df = pd.DataFrame(data, columns=BT_DATA_COLUMNS) df = pd.DataFrame(data, columns=BT_DATA_COLUMNS_OLD)
df['open_date'] = pd.to_datetime(df['open_date'], df['open_date'] = pd.to_datetime(df['open_date'],
unit='s', unit='s',
@@ -166,7 +178,10 @@ def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = Non
utc=True, utc=True,
infer_datetime_format=True infer_datetime_format=True
) )
# Create compatibility with new format
df['profit_abs'] = df['close_rate'] - df['open_rate'] df['profit_abs'] = df['close_rate'] - df['open_rate']
if 'profit_ratio' not in df.columns:
df['profit_ratio'] = df['profit_percent']
df = df.sort_values("open_date").reset_index(drop=True) df = df.sort_values("open_date").reset_index(drop=True)
return df return df
@@ -209,6 +224,20 @@ def evaluate_result_multi(results: pd.DataFrame, timeframe: str,
return df_final[df_final['open_trades'] > max_open_trades] return df_final[df_final['open_trades'] > max_open_trades]
def trade_list_to_dataframe(trades: List[LocalTrade]) -> pd.DataFrame:
"""
Convert list of Trade objects to pandas Dataframe
:param trades: List of trade objects
:return: Dataframe with BT_DATA_COLUMNS
"""
df = pd.DataFrame.from_records([t.to_json() for t in trades], columns=BT_DATA_COLUMNS)
if len(df) > 0:
df.loc[:, 'close_date'] = pd.to_datetime(df['close_date'], utc=True)
df.loc[:, 'open_date'] = pd.to_datetime(df['open_date'], utc=True)
df.loc[:, 'close_rate'] = df['close_rate'].astype('float64')
return df
def load_trades_from_db(db_url: str, strategy: Optional[str] = None) -> pd.DataFrame: def load_trades_from_db(db_url: str, strategy: Optional[str] = None) -> pd.DataFrame:
""" """
Load trades from a DB (using dburl) Load trades from a DB (using dburl)
@@ -219,36 +248,10 @@ def load_trades_from_db(db_url: str, strategy: Optional[str] = None) -> pd.DataF
""" """
init_db(db_url, clean_open_orders=False) init_db(db_url, clean_open_orders=False)
columns = ["pair", "open_date", "close_date", "profit", "profit_percent",
"open_rate", "close_rate", "amount", "trade_duration", "sell_reason",
"fee_open", "fee_close", "open_rate_requested", "close_rate_requested",
"stake_amount", "max_rate", "min_rate", "id", "exchange",
"stop_loss", "initial_stop_loss", "strategy", "timeframe"]
filters = [] filters = []
if strategy: if strategy:
filters.append(Trade.strategy == strategy) filters.append(Trade.strategy == strategy)
trades = trade_list_to_dataframe(Trade.get_trades(filters).all())
trades = pd.DataFrame([(t.pair,
t.open_date.replace(tzinfo=timezone.utc),
t.close_date.replace(tzinfo=timezone.utc) if t.close_date else None,
t.calc_profit(), t.calc_profit_ratio(),
t.open_rate, t.close_rate, t.amount,
(round((t.close_date.timestamp() - t.open_date.timestamp()) / 60, 2)
if t.close_date else None),
t.sell_reason,
t.fee_open, t.fee_close,
t.open_rate_requested,
t.close_rate_requested,
t.stake_amount,
t.max_rate,
t.min_rate,
t.id, t.exchange,
t.stop_loss, t.initial_stop_loss,
t.strategy, t.timeframe
)
for t in Trade.get_trades(filters).all()],
columns=columns)
return trades return trades
@@ -309,7 +312,7 @@ def calculate_market_change(data: Dict[str, pd.DataFrame], column: str = "close"
end = df[column].dropna().iloc[-1] end = df[column].dropna().iloc[-1]
tmp_means.append((end - start) / start) tmp_means.append((end - start) / start)
return np.mean(tmp_means) return float(np.mean(tmp_means))
def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame], def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame],
@@ -334,7 +337,7 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
""" """
Adds a column `col_name` with the cumulative profit for the given trades array. Adds a column `col_name` with the cumulative profit for the given trades array.
:param df: DataFrame with date index :param df: DataFrame with date index
:param trades: DataFrame containing trades (requires columns close_date and profit_percent) :param trades: DataFrame containing trades (requires columns close_date and profit_ratio)
:param col_name: Column name that will be assigned the results :param col_name: Column name that will be assigned the results
:param timeframe: Timeframe used during the operations :param timeframe: Timeframe used during the operations
:return: Returns df with one additional column, col_name, containing the cumulative profit. :return: Returns df with one additional column, col_name, containing the cumulative profit.
@@ -346,8 +349,8 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
timeframe_minutes = timeframe_to_minutes(timeframe) timeframe_minutes = timeframe_to_minutes(timeframe)
# Resample to timeframe to make sure trades match candles # Resample to timeframe to make sure trades match candles
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_date' _trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_date'
)[['profit_percent']].sum() )[['profit_ratio']].sum()
df.loc[:, col_name] = _trades_sum.cumsum() df.loc[:, col_name] = _trades_sum['profit_ratio'].cumsum()
# Set first value to 0 # Set first value to 0
df.loc[df.iloc[0].name, col_name] = 0 df.loc[df.iloc[0].name, col_name] = 0
# FFill to get continuous # FFill to get continuous
@@ -356,14 +359,15 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date', def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date',
value_col: str = 'profit_percent' value_col: str = 'profit_ratio'
) -> Tuple[float, pd.Timestamp, pd.Timestamp]: ) -> Tuple[float, pd.Timestamp, pd.Timestamp, float, float]:
""" """
Calculate max drawdown and the corresponding close dates Calculate max drawdown and the corresponding close dates
:param trades: DataFrame containing trades (requires columns close_date and profit_percent) :param trades: DataFrame containing trades (requires columns close_date and profit_ratio)
:param date_col: Column in DataFrame to use for dates (defaults to 'close_date') :param date_col: Column in DataFrame to use for dates (defaults to 'close_date')
:param value_col: Column in DataFrame to use for values (defaults to 'profit_percent') :param value_col: Column in DataFrame to use for values (defaults to 'profit_ratio')
:return: Tuple (float, highdate, lowdate) with absolute max drawdown, high and low time :return: Tuple (float, highdate, lowdate, highvalue, lowvalue) with absolute max drawdown,
high and low time and high and low value.
:raise: ValueError if trade-dataframe was found empty. :raise: ValueError if trade-dataframe was found empty.
""" """
if len(trades) == 0: if len(trades) == 0:
@@ -379,4 +383,26 @@ def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date'
raise ValueError("No losing trade, therefore no drawdown.") raise ValueError("No losing trade, therefore no drawdown.")
high_date = profit_results.loc[max_drawdown_df.iloc[:idxmin]['high_value'].idxmax(), date_col] high_date = profit_results.loc[max_drawdown_df.iloc[:idxmin]['high_value'].idxmax(), date_col]
low_date = profit_results.loc[idxmin, date_col] low_date = profit_results.loc[idxmin, date_col]
return abs(min(max_drawdown_df['drawdown'])), high_date, low_date high_val = max_drawdown_df.loc[max_drawdown_df.iloc[:idxmin]
['high_value'].idxmax(), 'cumulative']
low_val = max_drawdown_df.loc[idxmin, 'cumulative']
return abs(min(max_drawdown_df['drawdown'])), high_date, low_date, high_val, low_val
def calculate_csum(trades: pd.DataFrame, starting_balance: float = 0) -> Tuple[float, float]:
"""
Calculate min/max cumsum of trades, to show if the wallet/stake amount ratio is sane
:param trades: DataFrame containing trades (requires columns close_date and profit_percent)
:param starting_balance: Add starting balance to results, to show the wallets high / low points
:return: Tuple (float, float) with cumsum of profit_abs
:raise: ValueError if trade-dataframe was found empty.
"""
if len(trades) == 0:
raise ValueError("Trade dataframe empty.")
csum_df = pd.DataFrame()
csum_df['sum'] = trades['profit_abs'].cumsum()
csum_min = csum_df['sum'].min() + starting_balance
csum_max = csum_df['sum'].max() + starting_balance
return csum_min, csum_max

View File

@@ -86,8 +86,12 @@ class JsonDataHandler(IDataHandler):
filename = self._pair_data_filename(self._datadir, pair, timeframe) filename = self._pair_data_filename(self._datadir, pair, timeframe)
if not filename.exists(): if not filename.exists():
return DataFrame(columns=self._columns) return DataFrame(columns=self._columns)
pairdata = read_json(filename, orient='values') try:
pairdata.columns = self._columns pairdata = read_json(filename, orient='values')
pairdata.columns = self._columns
except ValueError:
logger.error(f"Could not load data for {pair}.")
return DataFrame(columns=self._columns)
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float', pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
'low': 'float', 'close': 'float', 'volume': 'float'}) 'low': 'float', 'close': 'float', 'volume': 'float'})
pairdata['date'] = to_datetime(pairdata['date'], pairdata['date'] = to_datetime(pairdata['date'],

View File

@@ -12,6 +12,7 @@ from freqtrade.configuration import TimeRange
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
from freqtrade.data.history import get_timerange, load_data, refresh_data from freqtrade.data.history import get_timerange, load_data, refresh_data
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.strategy.interface import SellType from freqtrade.strategy.interface import SellType
@@ -80,10 +81,12 @@ class Edge:
if config.get('fee'): if config.get('fee'):
self.fee = config['fee'] self.fee = config['fee']
else: else:
self.fee = self.exchange.get_fee(symbol=self.config['exchange']['pair_whitelist'][0]) self.fee = self.exchange.get_fee(symbol=expand_pairlist(
self.config['exchange']['pair_whitelist'], list(self.exchange.markets))[0])
def calculate(self) -> bool: def calculate(self) -> bool:
pairs = self.config['exchange']['pair_whitelist'] pairs = expand_pairlist(self.config['exchange']['pair_whitelist'],
list(self.exchange.markets))
heartbeat = self.edge_config.get('process_throttle_secs') heartbeat = self.edge_config.get('process_throttle_secs')
if (self._last_updated > 0) and ( if (self._last_updated > 0) and (
@@ -101,6 +104,7 @@ class Edge:
exchange=self.exchange, exchange=self.exchange,
timeframe=self.strategy.timeframe, timeframe=self.strategy.timeframe,
timerange=self._timerange, timerange=self._timerange,
data_format=self.config.get('dataformat_ohlcv', 'json'),
) )
data = load_data( data = load_data(
@@ -156,7 +160,8 @@ class Edge:
available_capital = (total_capital + capital_in_trade) * self._capital_ratio available_capital = (total_capital + capital_in_trade) * self._capital_ratio
allowed_capital_at_risk = available_capital * self._allowed_risk allowed_capital_at_risk = available_capital * self._allowed_risk
max_position_size = abs(allowed_capital_at_risk / stoploss) max_position_size = abs(allowed_capital_at_risk / stoploss)
position_size = min(max_position_size, free_capital) # Position size must be below available capital.
position_size = min(min(max_position_size, free_capital), available_capital)
if pair in self._cached_pairs: if pair in self._cached_pairs:
logger.info( logger.info(
'winrate: %s, expectancy: %s, position size: %s, pair: %s,' 'winrate: %s, expectancy: %s, position size: %s, pair: %s,'

View File

@@ -19,5 +19,11 @@ class Bittrex(Exchange):
""" """
_ft_has: Dict = { _ft_has: Dict = {
"ohlcv_candle_limit_per_timeframe": {
'1m': 1440,
'5m': 288,
'1h': 744,
'1d': 365,
},
"l2_limit_range": [1, 25, 500], "l2_limit_range": [1, 25, 500],
} }

View File

@@ -21,6 +21,7 @@ BAD_EXCHANGES = {
"hitbtc": "This API cannot be used with Freqtrade. " "hitbtc": "This API cannot be used with Freqtrade. "
"Use `hitbtc2` exchange id to access this exchange.", "Use `hitbtc2` exchange id to access this exchange.",
"phemex": "Does not provide history. ", "phemex": "Does not provide history. ",
"poloniex": "Does not provide fetch_order endpoint to fetch both open and closed orders.",
**dict.fromkeys([ **dict.fromkeys([
'adara', 'adara',
'anxpro', 'anxpro',

View File

@@ -3,6 +3,7 @@
Cryptocurrency Exchanges support Cryptocurrency Exchanges support
""" """
import asyncio import asyncio
import http
import inspect import inspect
import logging import logging
from copy import deepcopy from copy import deepcopy
@@ -17,7 +18,7 @@ from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE, TRU
decimal_to_precision) decimal_to_precision)
from pandas import DataFrame from pandas import DataFrame
from freqtrade.constants import ListPairsWithTimeframes from freqtrade.constants import DEFAULT_AMOUNT_RESERVE_PERCENT, ListPairsWithTimeframes
from freqtrade.data.converter import ohlcv_to_dataframe, trades_dict_to_list from freqtrade.data.converter import ohlcv_to_dataframe, trades_dict_to_list
from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError, from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError,
InvalidOrderException, OperationalException, RetryableOrderError, InvalidOrderException, OperationalException, RetryableOrderError,
@@ -25,6 +26,7 @@ from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFun
from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, BAD_EXCHANGES, retrier, from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, BAD_EXCHANGES, retrier,
retrier_async) retrier_async)
from freqtrade.misc import deep_merge_dicts, safe_value_fallback2 from freqtrade.misc import deep_merge_dicts, safe_value_fallback2
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
CcxtModuleType = Any CcxtModuleType = Any
@@ -33,6 +35,12 @@ CcxtModuleType = Any
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Workaround for adding samesite support to pre 3.8 python
# Only applies to python3.7, and only on certain exchanges (kraken)
# Replicates the fix from starlette (which is actually causing this problem)
http.cookies.Morsel._reserved["samesite"] = "SameSite" # type: ignore
class Exchange: class Exchange:
_config: Dict = {} _config: Dict = {}
@@ -65,6 +73,7 @@ class Exchange:
""" """
self._api: ccxt.Exchange = None self._api: ccxt.Exchange = None
self._api_async: ccxt_async.Exchange = None self._api_async: ccxt_async.Exchange = None
self._markets: Dict = {}
self._config.update(config) self._config.update(config)
@@ -92,7 +101,6 @@ class Exchange:
logger.info("Overriding exchange._ft_has with config params, result: %s", self._ft_has) logger.info("Overriding exchange._ft_has with config params, result: %s", self._ft_has)
# Assign this directly for easy access # Assign this directly for easy access
self._ohlcv_candle_limit = self._ft_has['ohlcv_candle_limit']
self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle'] self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle']
self._trades_pagination = self._ft_has['trades_pagination'] self._trades_pagination = self._ft_has['trades_pagination']
@@ -128,7 +136,8 @@ class Exchange:
self.validate_pairs(config['exchange']['pair_whitelist']) self.validate_pairs(config['exchange']['pair_whitelist'])
self.validate_ordertypes(config.get('order_types', {})) self.validate_ordertypes(config.get('order_types', {}))
self.validate_order_time_in_force(config.get('order_time_in_force', {})) self.validate_order_time_in_force(config.get('order_time_in_force', {}))
self.validate_required_startup_candles(config.get('startup_candle_count', 0)) self.validate_required_startup_candles(config.get('startup_candle_count', 0),
config.get('timeframe', ''))
# Converts the interval provided in minutes in config to seconds # Converts the interval provided in minutes in config to seconds
self.markets_refresh_interval: int = exchange_config.get( self.markets_refresh_interval: int = exchange_config.get(
@@ -138,6 +147,9 @@ class Exchange:
""" """
Destructor - clean up async stuff Destructor - clean up async stuff
""" """
self.close()
def close(self):
logger.debug("Exchange object destroyed, closing async loop") logger.debug("Exchange object destroyed, closing async loop")
if self._api_async and inspect.iscoroutinefunction(self._api_async.close): if self._api_async and inspect.iscoroutinefunction(self._api_async.close):
asyncio.get_event_loop().run_until_complete(self._api_async.close()) asyncio.get_event_loop().run_until_complete(self._api_async.close())
@@ -189,26 +201,32 @@ class Exchange:
def timeframes(self) -> List[str]: def timeframes(self) -> List[str]:
return list((self._api.timeframes or {}).keys()) return list((self._api.timeframes or {}).keys())
@property
def ohlcv_candle_limit(self) -> int:
"""exchange ohlcv candle limit"""
return int(self._ohlcv_candle_limit)
@property @property
def markets(self) -> Dict: def markets(self) -> Dict:
"""exchange ccxt markets""" """exchange ccxt markets"""
if not self._api.markets: if not self._markets:
logger.info("Markets were not loaded. Loading them now..") logger.info("Markets were not loaded. Loading them now..")
self._load_markets() self._load_markets()
return self._api.markets return self._markets
@property @property
def precisionMode(self) -> str: def precisionMode(self) -> str:
"""exchange ccxt precisionMode""" """exchange ccxt precisionMode"""
return self._api.precisionMode return self._api.precisionMode
def ohlcv_candle_limit(self, timeframe: str) -> int:
"""
Exchange ohlcv candle limit
Uses ohlcv_candle_limit_per_timeframe if the exchange has different limts
per timeframe (e.g. bittrex), otherwise falls back to ohlcv_candle_limit
:param timeframe: Timeframe to check
:return: Candle limit as integer
"""
return int(self._ft_has.get('ohlcv_candle_limit_per_timeframe', {}).get(
timeframe, self._ft_has.get('ohlcv_candle_limit')))
def get_markets(self, base_currencies: List[str] = None, quote_currencies: List[str] = None, def get_markets(self, base_currencies: List[str] = None, quote_currencies: List[str] = None,
pairs_only: bool = False, active_only: bool = False) -> Dict: pairs_only: bool = False, active_only: bool = False) -> Dict[str, Any]:
""" """
Return exchange ccxt markets, filtered out by base currency and quote currency Return exchange ccxt markets, filtered out by base currency and quote currency
if this was requested in parameters. if this was requested in parameters.
@@ -290,11 +308,11 @@ class Exchange:
def _load_markets(self) -> None: def _load_markets(self) -> None:
""" Initialize markets both sync and async """ """ Initialize markets both sync and async """
try: try:
self._api.load_markets() self._markets = self._api.load_markets()
self._load_async_markets() self._load_async_markets()
self._last_markets_refresh = arrow.utcnow().int_timestamp self._last_markets_refresh = arrow.utcnow().int_timestamp
except ccxt.BaseError as e: except ccxt.BaseError:
logger.warning('Unable to initialize markets. Reason: %s', e) logger.exception('Unable to initialize markets.')
def reload_markets(self) -> None: def reload_markets(self) -> None:
"""Reload markets both sync and async if refresh interval has passed """ """Reload markets both sync and async if refresh interval has passed """
@@ -305,7 +323,7 @@ class Exchange:
return None return None
logger.debug("Performing scheduled market reload..") logger.debug("Performing scheduled market reload..")
try: try:
self._api.load_markets(reload=True) self._markets = self._api.load_markets(reload=True)
# Also reload async markets to avoid issues with newly listed pairs # Also reload async markets to avoid issues with newly listed pairs
self._load_async_markets(reload=True) self._load_async_markets(reload=True)
self._last_markets_refresh = arrow.utcnow().int_timestamp self._last_markets_refresh = arrow.utcnow().int_timestamp
@@ -335,8 +353,9 @@ class Exchange:
if not self.markets: if not self.markets:
logger.warning('Unable to validate pairs (assuming they are correct).') logger.warning('Unable to validate pairs (assuming they are correct).')
return return
extended_pairs = expand_pairlist(pairs, list(self.markets), keep_invalid=True)
invalid_pairs = [] invalid_pairs = []
for pair in pairs: for pair in extended_pairs:
# Note: ccxt has BaseCurrency/QuoteCurrency format for pairs # Note: ccxt has BaseCurrency/QuoteCurrency format for pairs
# TODO: add a support for having coins in BTC/USDT format # TODO: add a support for having coins in BTC/USDT format
if self.markets and pair not in self.markets: if self.markets and pair not in self.markets:
@@ -418,15 +437,16 @@ class Exchange:
raise OperationalException( raise OperationalException(
f'Time in force policies are not supported for {self.name} yet.') f'Time in force policies are not supported for {self.name} yet.')
def validate_required_startup_candles(self, startup_candles: int) -> None: def validate_required_startup_candles(self, startup_candles: int, timeframe: str) -> None:
""" """
Checks if required startup_candles is more than ohlcv_candle_limit. Checks if required startup_candles is more than ohlcv_candle_limit().
Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default. Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default.
""" """
if startup_candles + 5 > self._ft_has['ohlcv_candle_limit']: candle_limit = self.ohlcv_candle_limit(timeframe)
if startup_candles + 5 > candle_limit:
raise OperationalException( raise OperationalException(
f"This strategy requires {startup_candles} candles to start. " f"This strategy requires {startup_candles} candles to start. "
f"{self.name} only provides {self._ft_has['ohlcv_candle_limit']}.") f"{self.name} only provides {candle_limit} for {timeframe}.")
def exchange_has(self, endpoint: str) -> bool: def exchange_has(self, endpoint: str) -> bool:
""" """
@@ -487,6 +507,41 @@ class Exchange:
else: else:
return 1 / pow(10, precision) return 1 / pow(10, precision)
def get_min_pair_stake_amount(self, pair: str, price: float,
stoploss: float) -> Optional[float]:
try:
market = self.markets[pair]
except KeyError:
raise ValueError(f"Can't get market information for symbol {pair}")
if 'limits' not in market:
return None
min_stake_amounts = []
limits = market['limits']
if ('cost' in limits and 'min' in limits['cost']
and limits['cost']['min'] is not None):
min_stake_amounts.append(limits['cost']['min'])
if ('amount' in limits and 'min' in limits['amount']
and limits['amount']['min'] is not None):
min_stake_amounts.append(limits['amount']['min'] * price)
if not min_stake_amounts:
return None
# reserve some percent defined in config (5% default) + stoploss
amount_reserve_percent = 1.0 + self._config.get('amount_reserve_percent',
DEFAULT_AMOUNT_RESERVE_PERCENT)
amount_reserve_percent += abs(stoploss)
# it should not be more than 50%
amount_reserve_percent = max(min(amount_reserve_percent, 1.5), 1)
# The value returned should satisfy both limits: for amount (base currency) and
# for cost (quote, stake currency), so max() is used here.
# See also #2575 at github.
return max(min_stake_amounts) * amount_reserve_percent
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float, def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
rate: float, params: Dict = {}) -> Dict[str, Any]: rate: float, params: Dict = {}) -> Dict[str, Any]:
order_id = f'dry_run_{side}_{datetime.now().timestamp()}' order_id = f'dry_run_{side}_{datetime.now().timestamp()}'
@@ -658,8 +713,8 @@ class Exchange:
@retrier @retrier
def fetch_ticker(self, pair: str) -> dict: def fetch_ticker(self, pair: str) -> dict:
try: try:
if (pair not in self._api.markets or if (pair not in self.markets or
self._api.markets[pair].get('active', False) is False): self.markets[pair].get('active', False) is False):
raise ExchangeError(f"Pair {pair} not available") raise ExchangeError(f"Pair {pair} not available")
data = self._api.fetch_ticker(pair) data = self._api.fetch_ticker(pair)
return data return data
@@ -676,7 +731,7 @@ class Exchange:
""" """
Get candle history using asyncio and returns the list of candles. Get candle history using asyncio and returns the list of candles.
Handles all async work for this. Handles all async work for this.
Async over one pair, assuming we get `self._ohlcv_candle_limit` candles per call. Async over one pair, assuming we get `self.ohlcv_candle_limit()` candles per call.
:param pair: Pair to download :param pair: Pair to download
:param timeframe: Timeframe to get data for :param timeframe: Timeframe to get data for
:param since_ms: Timestamp in milliseconds to get history from :param since_ms: Timestamp in milliseconds to get history from
@@ -706,7 +761,7 @@ class Exchange:
Download historic ohlcv Download historic ohlcv
""" """
one_call = timeframe_to_msecs(timeframe) * self._ohlcv_candle_limit one_call = timeframe_to_msecs(timeframe) * self.ohlcv_candle_limit(timeframe)
logger.debug( logger.debug(
"one_call: %s msecs (%s)", "one_call: %s msecs (%s)",
one_call, one_call,
@@ -808,7 +863,7 @@ class Exchange:
data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe, data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe,
since=since_ms, since=since_ms,
limit=self._ohlcv_candle_limit) limit=self.ohlcv_candle_limit(timeframe))
# Some exchanges sort OHLCV in ASC order and others in DESC. # Some exchanges sort OHLCV in ASC order and others in DESC.
# Ex: Bittrex returns the list of OHLCV in ASC order (oldest first, newest last) # Ex: Bittrex returns the list of OHLCV in ASC order (oldest first, newest last)
@@ -936,7 +991,7 @@ class Exchange:
while True: while True:
t = await self._async_fetch_trades(pair, since=since) t = await self._async_fetch_trades(pair, since=since)
if len(t): if len(t):
since = t[-1][1] since = t[-1][0]
trades.extend(t) trades.extend(t)
# Reached the end of the defined-download period # Reached the end of the defined-download period
if until and t[-1][0] > until: if until and t[-1][0] > until:
@@ -981,7 +1036,7 @@ class Exchange:
""" """
Get trade history data using asyncio. Get trade history data using asyncio.
Handles all async work and returns the list of candles. Handles all async work and returns the list of candles.
Async over one pair, assuming we get `self._ohlcv_candle_limit` candles per call. Async over one pair, assuming we get `self.ohlcv_candle_limit()` candles per call.
:param pair: Pair to download :param pair: Pair to download
:param since: Timestamp in milliseconds to get history from :param since: Timestamp in milliseconds to get history from
:param until: Timestamp in milliseconds. Defaults to current timestamp if not defined. :param until: Timestamp in milliseconds. Defaults to current timestamp if not defined.
@@ -1001,7 +1056,8 @@ class Exchange:
:param order: Order dict as returned from fetch_order() :param order: Order dict as returned from fetch_order()
:return: True if order has been cancelled without being filled, False otherwise. :return: True if order has been cancelled without being filled, False otherwise.
""" """
return order.get('status') in ('closed', 'canceled') and order.get('filled') == 0.0 return (order.get('status') in ('closed', 'canceled', 'cancelled')
and order.get('filled') == 0.0)
@retrier @retrier
def cancel_order(self, order_id: str, pair: str) -> Dict: def cancel_order(self, order_id: str, pair: str) -> Dict:
@@ -1176,6 +1232,8 @@ class Exchange:
def get_fee(self, symbol: str, type: str = '', side: str = '', amount: float = 1, def get_fee(self, symbol: str, type: str = '', side: str = '', amount: float = 1,
price: float = 1, taker_or_maker: str = 'maker') -> float: price: float = 1, taker_or_maker: str = 'maker') -> float:
try: try:
if self._config['dry_run'] and self._config.get('fee', None) is not None:
return self._config['fee']
# validate that markets are loaded before trying to get fee # validate that markets are loaded before trying to get fee
if self._api.markets is None or len(self._api.markets) == 0: if self._api.markets is None or len(self._api.markets) == 0:
self._api.load_markets() self._api.load_markets()

View File

@@ -48,7 +48,7 @@ class Kraken(Exchange):
orders = self._api.fetch_open_orders() orders = self._api.fetch_open_orders()
order_list = [(x["symbol"].split("/")[0 if x["side"] == "sell" else 1], order_list = [(x["symbol"].split("/")[0 if x["side"] == "sell" else 1],
x["remaining"], x["remaining"] if x["side"] == "sell" else x["remaining"] * x["price"],
# Don't remove the below comment, this can be important for debuggung # Don't remove the below comment, this can be important for debuggung
# x["side"], x["amount"], # x["side"], x["amount"],
) for x in orders] ) for x in orders]

View File

@@ -179,6 +179,7 @@ class FreqtradeBot(LoggingMixin):
# Without this, freqtrade my try to recreate stoploss_on_exchange orders # Without this, freqtrade my try to recreate stoploss_on_exchange orders
# while selling is in process, since telegram messages arrive in an different thread. # while selling is in process, since telegram messages arrive in an different thread.
with self._sell_lock: with self._sell_lock:
trades = Trade.get_open_trades()
# First process current opened trades (positions) # First process current opened trades (positions)
self.exit_positions(trades) self.exit_positions(trades)
@@ -200,7 +201,7 @@ class FreqtradeBot(LoggingMixin):
Notify the user when the bot is stopped Notify the user when the bot is stopped
and there are still open trades active. and there are still open trades active.
""" """
open_trades = Trade.get_trades([Trade.is_open == 1]).all() open_trades = Trade.get_trades([Trade.is_open.is_(True)]).all()
if len(open_trades) != 0: if len(open_trades) != 0:
msg = { msg = {
@@ -233,7 +234,7 @@ class FreqtradeBot(LoggingMixin):
_whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist]) _whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist])
return _whitelist return _whitelist
def get_free_open_trades(self): def get_free_open_trades(self) -> int:
""" """
Return the number of free open trades slots or 0 if Return the number of free open trades slots or 0 if
max number of open trades reached max number of open trades reached
@@ -246,6 +247,10 @@ class FreqtradeBot(LoggingMixin):
Updates open orders based on order list kept in the database. Updates open orders based on order list kept in the database.
Mainly updates the state of orders - but may also close trades Mainly updates the state of orders - but may also close trades
""" """
if self.config['dry_run'] or self.config['exchange'].get('skip_open_order_update', False):
# Updating open orders in dry-run does not make sense and will fail.
return
orders = Order.get_open_orders() orders = Order.get_open_orders()
logger.info(f"Updating {len(orders)} open orders.") logger.info(f"Updating {len(orders)} open orders.")
for order in orders: for order in orders:
@@ -256,6 +261,7 @@ class FreqtradeBot(LoggingMixin):
self.update_trade_state(order.trade, order.order_id, fo) self.update_trade_state(order.trade, order.order_id, fo)
except ExchangeError as e: except ExchangeError as e:
logger.warning(f"Error updating Order {order.order_id} due to {e}") logger.warning(f"Error updating Order {order.order_id} due to {e}")
def update_closed_trades_without_assigned_fees(self): def update_closed_trades_without_assigned_fees(self):
@@ -263,6 +269,10 @@ class FreqtradeBot(LoggingMixin):
Update closed trades without close fees assigned. Update closed trades without close fees assigned.
Only acts when Orders are in the database, otherwise the last orderid is unknown. Only acts when Orders are in the database, otherwise the last orderid is unknown.
""" """
if self.config['dry_run']:
# Updating open orders in dry-run does not make sense and will fail.
return
trades: List[Trade] = Trade.get_sold_trades_without_assigned_fees() trades: List[Trade] = Trade.get_sold_trades_without_assigned_fees()
for trade in trades: for trade in trades:
@@ -422,7 +432,7 @@ class FreqtradeBot(LoggingMixin):
ticker = self.exchange.fetch_ticker(pair) ticker = self.exchange.fetch_ticker(pair)
ticker_rate = ticker[bid_strategy['price_side']] ticker_rate = ticker[bid_strategy['price_side']]
if ticker['last'] and ticker_rate > ticker['last']: if ticker['last'] and ticker_rate > ticker['last']:
balance = self.config['bid_strategy']['ask_last_balance'] balance = bid_strategy['ask_last_balance']
ticker_rate = ticker_rate + balance * (ticker['last'] - ticker_rate) ticker_rate = ticker_rate + balance * (ticker['last'] - ticker_rate)
used_rate = ticker_rate used_rate = ticker_rate
@@ -430,117 +440,6 @@ class FreqtradeBot(LoggingMixin):
return used_rate return used_rate
def get_trade_stake_amount(self, pair: str) -> float:
"""
Calculate stake amount for the trade
:return: float: Stake amount
:raise: DependencyException if the available stake amount is too low
"""
stake_amount: float
# Ensure wallets are uptodate.
self.wallets.update()
if self.edge:
stake_amount = self.edge.stake_amount(
pair,
self.wallets.get_free(self.config['stake_currency']),
self.wallets.get_total(self.config['stake_currency']),
Trade.total_open_trades_stakes()
)
else:
stake_amount = self.config['stake_amount']
if stake_amount == constants.UNLIMITED_STAKE_AMOUNT:
stake_amount = self._calculate_unlimited_stake_amount()
return self._check_available_stake_amount(stake_amount)
def _get_available_stake_amount(self) -> float:
"""
Return the total currently available balance in stake currency,
respecting tradable_balance_ratio.
Calculated as
<open_trade stakes> + free amount ) * tradable_balance_ratio - <open_trade stakes>
"""
val_tied_up = Trade.total_open_trades_stakes()
# Ensure <tradable_balance_ratio>% is used from the overall balance
# Otherwise we'd risk lowering stakes with each open trade.
# (tied up + current free) * ratio) - tied up
available_amount = ((val_tied_up + self.wallets.get_free(self.config['stake_currency'])) *
self.config['tradable_balance_ratio']) - val_tied_up
return available_amount
def _calculate_unlimited_stake_amount(self) -> float:
"""
Calculate stake amount for "unlimited" stake amount
:return: 0 if max number of trades reached, else stake_amount to use.
"""
free_open_trades = self.get_free_open_trades()
if not free_open_trades:
return 0
available_amount = self._get_available_stake_amount()
return available_amount / free_open_trades
def _check_available_stake_amount(self, stake_amount: float) -> float:
"""
Check if stake amount can be fulfilled with the available balance
for the stake currency
:return: float: Stake amount
"""
available_amount = self._get_available_stake_amount()
if self.config['amend_last_stake_amount']:
# Remaining amount needs to be at least stake_amount * last_stake_amount_min_ratio
# Otherwise the remaining amount is too low to trade.
if available_amount > (stake_amount * self.config['last_stake_amount_min_ratio']):
stake_amount = min(stake_amount, available_amount)
else:
stake_amount = 0
if available_amount < stake_amount:
raise DependencyException(
f"Available balance ({available_amount} {self.config['stake_currency']}) is "
f"lower than stake amount ({stake_amount} {self.config['stake_currency']})"
)
return stake_amount
def _get_min_pair_stake_amount(self, pair: str, price: float) -> Optional[float]:
try:
market = self.exchange.markets[pair]
except KeyError:
raise ValueError(f"Can't get market information for symbol {pair}")
if 'limits' not in market:
return None
min_stake_amounts = []
limits = market['limits']
if ('cost' in limits and 'min' in limits['cost']
and limits['cost']['min'] is not None):
min_stake_amounts.append(limits['cost']['min'])
if ('amount' in limits and 'min' in limits['amount']
and limits['amount']['min'] is not None):
min_stake_amounts.append(limits['amount']['min'] * price)
if not min_stake_amounts:
return None
# reserve some percent defined in config (5% default) + stoploss
amount_reserve_percent = 1.0 - self.config.get('amount_reserve_percent',
constants.DEFAULT_AMOUNT_RESERVE_PERCENT)
amount_reserve_percent += self.strategy.stoploss
# it should not be more than 50%
amount_reserve_percent = max(amount_reserve_percent, 0.5)
# The value returned should satisfy both limits: for amount (base currency) and
# for cost (quote, stake currency), so max() is used here.
# See also #2575 at github.
return max(min_stake_amounts) / amount_reserve_percent
def create_trade(self, pair: str) -> bool: def create_trade(self, pair: str) -> bool:
""" """
Check the implemented trading strategy for buy signals. Check the implemented trading strategy for buy signals.
@@ -574,7 +473,8 @@ class FreqtradeBot(LoggingMixin):
(buy, sell) = self.strategy.get_signal(pair, self.strategy.timeframe, analyzed_df) (buy, sell) = self.strategy.get_signal(pair, self.strategy.timeframe, analyzed_df)
if buy and not sell: if buy and not sell:
stake_amount = self.get_trade_stake_amount(pair) stake_amount = self.wallets.get_trade_stake_amount(pair, self.get_free_open_trades(),
self.edge)
if not stake_amount: if not stake_amount:
logger.debug(f"Stake amount is 0, ignoring possible trade for {pair}.") logger.debug(f"Stake amount is 0, ignoring possible trade for {pair}.")
return False return False
@@ -620,7 +520,8 @@ class FreqtradeBot(LoggingMixin):
logger.info(f"Bids to asks delta for {pair} does not satisfy condition.") logger.info(f"Bids to asks delta for {pair} does not satisfy condition.")
return False return False
def execute_buy(self, pair: str, stake_amount: float, price: Optional[float] = None) -> bool: def execute_buy(self, pair: str, stake_amount: float, price: Optional[float] = None,
forcebuy: bool = False) -> bool:
""" """
Executes a limit buy for the given pair Executes a limit buy for the given pair
:param pair: pair for which we want to create a LIMIT_BUY :param pair: pair for which we want to create a LIMIT_BUY
@@ -637,7 +538,8 @@ class FreqtradeBot(LoggingMixin):
if not buy_limit_requested: if not buy_limit_requested:
raise PricingError('Could not determine buy price.') raise PricingError('Could not determine buy price.')
min_stake_amount = self._get_min_pair_stake_amount(pair, buy_limit_requested) min_stake_amount = self.exchange.get_min_pair_stake_amount(pair, buy_limit_requested,
self.strategy.stoploss)
if min_stake_amount is not None and min_stake_amount > stake_amount: if min_stake_amount is not None and min_stake_amount > stake_amount:
logger.warning( logger.warning(
f"Can't open a new trade for {pair}: stake amount " f"Can't open a new trade for {pair}: stake amount "
@@ -647,6 +549,10 @@ class FreqtradeBot(LoggingMixin):
amount = stake_amount / buy_limit_requested amount = stake_amount / buy_limit_requested
order_type = self.strategy.order_types['buy'] order_type = self.strategy.order_types['buy']
if forcebuy:
# Forcebuy can define a different ordertype
order_type = self.strategy.order_types.get('forcebuy', order_type)
if not strategy_safe_wrapper(self.strategy.confirm_trade_entry, default_retval=True)( if not strategy_safe_wrapper(self.strategy.confirm_trade_entry, default_retval=True)(
pair=pair, order_type=order_type, amount=amount, rate=buy_limit_requested, pair=pair, order_type=order_type, amount=amount, rate=buy_limit_requested,
time_in_force=time_in_force): time_in_force=time_in_force):
@@ -839,7 +745,13 @@ class FreqtradeBot(LoggingMixin):
logger.warning("Sell Price at location from orderbook could not be determined.") logger.warning("Sell Price at location from orderbook could not be determined.")
raise PricingError from e raise PricingError from e
else: else:
rate = self.exchange.fetch_ticker(pair)[ask_strategy['price_side']] ticker = self.exchange.fetch_ticker(pair)
ticker_rate = ticker[ask_strategy['price_side']]
if ticker['last'] and ticker_rate < ticker['last']:
balance = ask_strategy.get('bid_last_balance', 0.0)
ticker_rate = ticker_rate - balance * (ticker_rate - ticker['last'])
rate = ticker_rate
if rate is None: if rate is None:
raise PricingError(f"Sell-Rate for {pair} was empty.") raise PricingError(f"Sell-Rate for {pair} was empty.")
self._sell_rate_cache[pair] = rate self._sell_rate_cache[pair] = rate
@@ -989,7 +901,8 @@ class FreqtradeBot(LoggingMixin):
logger.warning('Stoploss order was cancelled, but unable to recreate one.') logger.warning('Stoploss order was cancelled, but unable to recreate one.')
# Finally we check if stoploss on exchange should be moved up because of trailing. # Finally we check if stoploss on exchange should be moved up because of trailing.
if stoploss_order and self.config.get('trailing_stop', False): if stoploss_order and (self.config.get('trailing_stop', False)
or self.config.get('use_custom_stoploss', False)):
# if trailing stoploss is enabled we check if stoploss value has changed # if trailing stoploss is enabled we check if stoploss value has changed
# in which case we cancel stoploss order and put another one with new # in which case we cancel stoploss order and put another one with new
# value immediately # value immediately
@@ -1030,7 +943,7 @@ class FreqtradeBot(LoggingMixin):
Check and execute sell Check and execute sell
""" """
should_sell = self.strategy.should_sell( should_sell = self.strategy.should_sell(
trade, sell_rate, datetime.utcnow(), buy, sell, trade, sell_rate, datetime.now(timezone.utc), buy, sell,
force_stoploss=self.edge.stoploss(trade.pair) if self.edge else 0 force_stoploss=self.edge.stoploss(trade.pair) if self.edge else 0
) )
@@ -1116,13 +1029,13 @@ class FreqtradeBot(LoggingMixin):
was_trade_fully_canceled = False was_trade_fully_canceled = False
# Cancelled orders may have the status of 'canceled' or 'closed' # Cancelled orders may have the status of 'canceled' or 'closed'
if order['status'] not in ('canceled', 'closed'): if order['status'] not in ('cancelled', 'canceled', 'closed'):
corder = self.exchange.cancel_order_with_result(trade.open_order_id, trade.pair, corder = self.exchange.cancel_order_with_result(trade.open_order_id, trade.pair,
trade.amount) trade.amount)
# Avoid race condition where the order could not be cancelled coz its already filled. # Avoid race condition where the order could not be cancelled coz its already filled.
# Simply bailing here is the only safe way - as this order will then be # Simply bailing here is the only safe way - as this order will then be
# handled in the next iteration. # handled in the next iteration.
if corder.get('status') not in ('canceled', 'closed'): if corder.get('status') not in ('cancelled', 'canceled', 'closed'):
logger.warning(f"Order {trade.open_order_id} for {trade.pair} not cancelled.") logger.warning(f"Order {trade.open_order_id} for {trade.pair} not cancelled.")
return False return False
else: else:
@@ -1169,7 +1082,9 @@ class FreqtradeBot(LoggingMixin):
if not self.exchange.check_order_canceled_empty(order): if not self.exchange.check_order_canceled_empty(order):
try: try:
# if trade is not partially completed, just delete the order # if trade is not partially completed, just delete the order
self.exchange.cancel_order(trade.open_order_id, trade.pair) co = self.exchange.cancel_order_with_result(trade.open_order_id, trade.pair,
trade.amount)
trade.update_order(co)
except InvalidOrderException: except InvalidOrderException:
logger.exception(f"Could not cancel sell order {trade.open_order_id}") logger.exception(f"Could not cancel sell order {trade.open_order_id}")
return 'error cancelling order' return 'error cancelling order'
@@ -1177,6 +1092,7 @@ class FreqtradeBot(LoggingMixin):
else: else:
reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE'] reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
logger.info('Sell order %s for %s.', reason, trade) logger.info('Sell order %s for %s.', reason, trade)
trade.update_order(order)
trade.close_rate = None trade.close_rate = None
trade.close_rate_requested = None trade.close_rate_requested = None
@@ -1251,6 +1167,10 @@ class FreqtradeBot(LoggingMixin):
if sell_reason == SellType.EMERGENCY_SELL: if sell_reason == SellType.EMERGENCY_SELL:
# Emergency sells (default to market!) # Emergency sells (default to market!)
order_type = self.strategy.order_types.get("emergencysell", "market") order_type = self.strategy.order_types.get("emergencysell", "market")
if sell_reason == SellType.FORCE_SELL:
# Force sells (default to the sell_type defined in the strategy,
# but we allow this value to be changed)
order_type = self.strategy.order_types.get("forcesell", order_type)
amount = self._safe_sell_amount(trade.pair, trade.amount) amount = self._safe_sell_amount(trade.pair, trade.amount)
time_in_force = self.strategy.order_time_in_force['sell'] time_in_force = self.strategy.order_time_in_force['sell']
@@ -1279,6 +1199,7 @@ class FreqtradeBot(LoggingMixin):
trade.orders.append(order_obj) trade.orders.append(order_obj)
trade.open_order_id = order['id'] trade.open_order_id = order['id']
trade.sell_order_status = ''
trade.close_rate_requested = limit trade.close_rate_requested = limit
trade.sell_reason = sell_reason.value trade.sell_reason = sell_reason.value
# In case of market sell orders the order can be closed immediately # In case of market sell orders the order can be closed immediately

View File

@@ -9,13 +9,37 @@ from pathlib import Path
from typing import Any from typing import Any
from typing.io import IO from typing.io import IO
import numpy as np
import rapidjson import rapidjson
from freqtrade.constants import DECIMAL_PER_COIN_FALLBACK, DECIMALS_PER_COIN
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def decimals_per_coin(coin: str):
"""
Helper method getting decimal amount for this coin
example usage: f".{decimals_per_coin('USD')}f"
:param coin: Which coin are we printing the price / value for
"""
return DECIMALS_PER_COIN.get(coin, DECIMAL_PER_COIN_FALLBACK)
def round_coin_value(value: float, coin: str, show_coin_name=True) -> str:
"""
Get price value for this coin
:param value: Value to be printed
:param coin: Which coin are we printing the price / value for
:param show_coin_name: Return string in format: "222.22 USDT" or "222.22"
:return: Formatted / rounded value (with or without coin name)
"""
if show_coin_name:
return f"{value:.{decimals_per_coin(coin)}f} {coin}"
else:
return f"{value:.{decimals_per_coin(coin)}f}"
def shorten_date(_date: str) -> str: def shorten_date(_date: str) -> str:
""" """
Trim the date so it fits on small screens Trim the date so it fits on small screens
@@ -28,20 +52,6 @@ def shorten_date(_date: str) -> str:
return new_date return new_date
############################################
# Used by scripts #
# Matplotlib doesn't support ::datetime64, #
# so we need to convert it into ::datetime #
############################################
def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
"""
Convert an pandas-array of timestamps into
An numpy-array of datetimes
:return: numpy-array of datetime
"""
return dates.dt.to_pydatetime()
def file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool = True) -> None: def file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool = True) -> None:
""" """
Dump JSON data into a file Dump JSON data into a file

View File

@@ -6,26 +6,29 @@ This module contains the backtesting logic
import logging import logging
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, NamedTuple, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
from pandas import DataFrame from pandas import DataFrame
from freqtrade.configuration import TimeRange, remove_credentials, validate_config_consistency from freqtrade.configuration import TimeRange, remove_credentials, validate_config_consistency
from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.constants import DATETIME_PRINT_FORMAT
from freqtrade.data import history from freqtrade.data import history
from freqtrade.data.btanalysis import trade_list_to_dataframe
from freqtrade.data.converter import trim_dataframe from freqtrade.data.converter import trim_dataframe
from freqtrade.data.dataprovider import DataProvider from freqtrade.data.dataprovider import DataProvider
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.optimize.optimize_reports import (generate_backtest_stats, show_backtest_results, from freqtrade.optimize.optimize_reports import (generate_backtest_stats, show_backtest_results,
store_backtest_stats) store_backtest_stats)
from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence import LocalTrade, PairLocks, Trade
from freqtrade.plugins.pairlistmanager import PairListManager from freqtrade.plugins.pairlistmanager import PairListManager
from freqtrade.plugins.protectionmanager import ProtectionManager from freqtrade.plugins.protectionmanager import ProtectionManager
from freqtrade.resolvers import ExchangeResolver, StrategyResolver from freqtrade.resolvers import ExchangeResolver, StrategyResolver
from freqtrade.strategy.interface import IStrategy, SellCheckTuple, SellType from freqtrade.strategy.interface import IStrategy, SellCheckTuple, SellType
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
from freqtrade.wallets import Wallets
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -40,25 +43,6 @@ LOW_IDX = 5
HIGH_IDX = 6 HIGH_IDX = 6
class BacktestResult(NamedTuple):
"""
NamedTuple Defining BacktestResults inputs.
"""
pair: str
profit_percent: float
profit_abs: float
open_date: datetime
open_rate: float
open_fee: float
close_date: datetime
close_rate: float
close_fee: float
amount: float
trade_duration: float
open_at_end: bool
sell_reason: SellType
class Backtesting: class Backtesting:
""" """
Backtesting class, this class contains all the logic to run a backtest Backtesting class, this class contains all the logic to run a backtest
@@ -76,6 +60,8 @@ class Backtesting:
# Reset keys for backtesting # Reset keys for backtesting
remove_credentials(self.config) remove_credentials(self.config)
self.strategylist: List[IStrategy] = [] self.strategylist: List[IStrategy] = []
self.all_results: Dict[str, Dict] = {}
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config) self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
dataprovider = DataProvider(self.config, self.exchange) dataprovider = DataProvider(self.config, self.exchange)
@@ -129,6 +115,8 @@ class Backtesting:
if self.config.get('enable_protections', False): if self.config.get('enable_protections', False):
self.protections = ProtectionManager(self.config) self.protections = ProtectionManager(self.config)
self.wallets = Wallets(self.config, self.exchange, log=False)
# Get maximum required startup period # Get maximum required startup period
self.required_startup = max([strat.startup_candle_count for strat in self.strategylist]) self.required_startup = max([strat.startup_candle_count for strat in self.strategylist])
# Load one (first) strategy # Load one (first) strategy
@@ -139,7 +127,7 @@ class Backtesting:
PairLocks.use_db = True PairLocks.use_db = True
Trade.use_db = True Trade.use_db = True
def _set_strategy(self, strategy): def _set_strategy(self, strategy: IStrategy):
""" """
Load strategy into backtesting Load strategy into backtesting
""" """
@@ -150,6 +138,10 @@ class Backtesting:
self.strategy.order_types['stoploss_on_exchange'] = False self.strategy.order_types['stoploss_on_exchange'] = False
def load_bt_data(self) -> Tuple[Dict[str, DataFrame], TimeRange]: def load_bt_data(self) -> Tuple[Dict[str, DataFrame], TimeRange]:
"""
Loads backtest data and returns the data combined with the timerange
as tuple.
"""
timerange = TimeRange.parse_timerange(None if self.config.get( timerange = TimeRange.parse_timerange(None if self.config.get(
'timerange') is None else str(self.config.get('timerange'))) 'timerange') is None else str(self.config.get('timerange')))
@@ -180,11 +172,10 @@ class Backtesting:
Backtesting setup method - called once for every call to "backtest()". Backtesting setup method - called once for every call to "backtest()".
""" """
PairLocks.use_db = False PairLocks.use_db = False
PairLocks.timeframe = self.config['timeframe']
Trade.use_db = False Trade.use_db = False
if enable_protections: PairLocks.reset_locks()
# Reset persisted data - used for protections only Trade.reset_trades()
PairLocks.reset_locks()
Trade.reset_trades()
def _get_ohlcv_as_lists(self, processed: Dict[str, DataFrame]) -> Dict[str, Tuple]: def _get_ohlcv_as_lists(self, processed: Dict[str, DataFrame]) -> Dict[str, Tuple]:
""" """
@@ -213,10 +204,10 @@ class Backtesting:
# Convert from Pandas to list for performance reasons # Convert from Pandas to list for performance reasons
# (Looping Pandas is slow.) # (Looping Pandas is slow.)
data[pair] = [x for x in df_analyzed.itertuples(index=False, name=None)] data[pair] = df_analyzed.values.tolist()
return data return data
def _get_close_rate(self, sell_row: Tuple, trade: Trade, sell: SellCheckTuple, def _get_close_rate(self, sell_row: Tuple, trade: LocalTrade, sell: SellCheckTuple,
trade_dur: int) -> float: trade_dur: int) -> float:
""" """
Get close rate for backtesting result Get close rate for backtesting result
@@ -256,37 +247,67 @@ class Backtesting:
else: else:
return sell_row[OPEN_IDX] return sell_row[OPEN_IDX]
def _get_sell_trade_entry(self, trade: Trade, sell_row: Tuple) -> Optional[BacktestResult]: def _get_sell_trade_entry(self, trade: LocalTrade, sell_row: Tuple) -> Optional[LocalTrade]:
sell = self.strategy.should_sell(trade, sell_row[OPEN_IDX], sell_row[DATE_IDX], sell = self.strategy.should_sell(trade, sell_row[OPEN_IDX], # type: ignore
sell_row[BUY_IDX], sell_row[SELL_IDX], sell_row[DATE_IDX], sell_row[BUY_IDX], sell_row[SELL_IDX],
low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX]) low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX])
if sell.sell_flag: if sell.sell_flag:
trade_dur = int((sell_row[DATE_IDX] - trade.open_date).total_seconds() // 60) trade.close_date = sell_row[DATE_IDX]
trade.sell_reason = sell.sell_type.value
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
closerate = self._get_close_rate(sell_row, trade, sell, trade_dur) closerate = self._get_close_rate(sell_row, trade, sell, trade_dur)
trade.close_date = sell_row[DATE_IDX] # Confirm trade exit:
trade.sell_reason = sell.sell_type time_in_force = self.strategy.order_time_in_force['sell']
trade.close(closerate, show_msg=False) if not strategy_safe_wrapper(self.strategy.confirm_trade_exit, default_retval=True)(
pair=trade.pair, trade=trade, order_type='limit', amount=trade.amount,
rate=closerate,
time_in_force=time_in_force,
sell_reason=sell.sell_type.value):
return None
trade.close(closerate, show_msg=False)
return trade
return BacktestResult(pair=trade.pair,
profit_percent=trade.calc_profit_ratio(rate=closerate),
profit_abs=trade.calc_profit(rate=closerate),
open_date=trade.open_date,
open_rate=trade.open_rate,
open_fee=self.fee,
close_date=sell_row[DATE_IDX],
close_rate=closerate,
close_fee=self.fee,
amount=trade.amount,
trade_duration=trade_dur,
open_at_end=False,
sell_reason=sell.sell_type
)
return None return None
def handle_left_open(self, open_trades: Dict[str, List[Trade]], def _enter_trade(self, pair: str, row: List, max_open_trades: int,
data: Dict[str, List[Tuple]]) -> List[BacktestResult]: open_trade_count: int) -> Optional[LocalTrade]:
try:
stake_amount = self.wallets.get_trade_stake_amount(
pair, max_open_trades - open_trade_count, None)
except DependencyException:
return None
min_stake_amount = self.exchange.get_min_pair_stake_amount(pair, row[OPEN_IDX], -0.05)
order_type = self.strategy.order_types['buy']
time_in_force = self.strategy.order_time_in_force['sell']
# Confirm trade entry:
if not strategy_safe_wrapper(self.strategy.confirm_trade_entry, default_retval=True)(
pair=pair, order_type=order_type, amount=stake_amount, rate=row[OPEN_IDX],
time_in_force=time_in_force):
return None
if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount):
# Enter trade
trade = LocalTrade(
pair=pair,
open_rate=row[OPEN_IDX],
open_date=row[DATE_IDX],
stake_amount=stake_amount,
amount=round(stake_amount / row[OPEN_IDX], 8),
fee_open=self.fee,
fee_close=self.fee,
is_open=True,
exchange='backtesting',
)
return trade
return None
def handle_left_open(self, open_trades: Dict[str, List[LocalTrade]],
data: Dict[str, List[Tuple]]) -> List[LocalTrade]:
""" """
Handling of left open trades at the end of backtesting Handling of left open trades at the end of backtesting
""" """
@@ -296,27 +317,17 @@ class Backtesting:
for trade in open_trades[pair]: for trade in open_trades[pair]:
sell_row = data[pair][-1] sell_row = data[pair][-1]
trade_entry = BacktestResult(pair=trade.pair, trade.close_date = sell_row[DATE_IDX]
profit_percent=trade.calc_profit_ratio( trade.sell_reason = SellType.FORCE_SELL.value
rate=sell_row[OPEN_IDX]), trade.close(sell_row[OPEN_IDX], show_msg=False)
profit_abs=trade.calc_profit(sell_row[OPEN_IDX]), LocalTrade.close_bt_trade(trade)
open_date=trade.open_date, # Deepcopy object to have wallets update correctly
open_rate=trade.open_rate, trade1 = deepcopy(trade)
open_fee=self.fee, trade1.is_open = True
close_date=sell_row[DATE_IDX], trades.append(trade1)
close_rate=sell_row[OPEN_IDX],
close_fee=self.fee,
amount=trade.amount,
trade_duration=int((
sell_row[DATE_IDX] - trade.open_date
).total_seconds() // 60),
open_at_end=True,
sell_reason=SellType.FORCE_SELL
)
trades.append(trade_entry)
return trades return trades
def backtest(self, processed: Dict, stake_amount: float, def backtest(self, processed: Dict,
start_date: datetime, end_date: datetime, start_date: datetime, end_date: datetime,
max_open_trades: int = 0, position_stacking: bool = False, max_open_trades: int = 0, position_stacking: bool = False,
enable_protections: bool = False) -> DataFrame: enable_protections: bool = False) -> DataFrame:
@@ -328,7 +339,6 @@ class Backtesting:
Avoid extensive logging in this method and functions it calls. Avoid extensive logging in this method and functions it calls.
:param processed: a processed dictionary with format {pair, data} :param processed: a processed dictionary with format {pair, data}
:param stake_amount: amount to use for each trade
:param start_date: backtesting timerange start datetime :param start_date: backtesting timerange start datetime
:param end_date: backtesting timerange end datetime :param end_date: backtesting timerange end datetime
:param max_open_trades: maximum number of concurrent trades, <= 0 means unlimited :param max_open_trades: maximum number of concurrent trades, <= 0 means unlimited
@@ -336,11 +346,7 @@ class Backtesting:
:param enable_protections: Should protections be enabled? :param enable_protections: Should protections be enabled?
:return: DataFrame with trades (results of backtesting) :return: DataFrame with trades (results of backtesting)
""" """
logger.debug(f"Run backtest, stake_amount: {stake_amount}, " trades: List[LocalTrade] = []
f"start_date: {start_date}, end_date: {end_date}, "
f"max_open_trades: {max_open_trades}, position_stacking: {position_stacking}"
)
trades = []
self.prepare_backtest(enable_protections) self.prepare_backtest(enable_protections)
# Use dict of lists with data for performance # Use dict of lists with data for performance
@@ -351,7 +357,7 @@ class Backtesting:
indexes: Dict = {} indexes: Dict = {}
tmp = start_date + timedelta(minutes=self.timeframe_min) tmp = start_date + timedelta(minutes=self.timeframe_min)
open_trades: Dict[str, List] = defaultdict(list) open_trades: Dict[str, List[LocalTrade]] = defaultdict(list)
open_trade_count = 0 open_trade_count = 0
# Loop timerange and get candle for each pair at that point in time # Loop timerange and get candle for each pair at that point in time
@@ -382,28 +388,18 @@ class Backtesting:
and tmp != end_date and tmp != end_date
and row[BUY_IDX] == 1 and row[SELL_IDX] != 1 and row[BUY_IDX] == 1 and row[SELL_IDX] != 1
and not PairLocks.is_pair_locked(pair, row[DATE_IDX])): and not PairLocks.is_pair_locked(pair, row[DATE_IDX])):
# Enter trade trade = self._enter_trade(pair, row, max_open_trades, open_trade_count_start)
trade = Trade( if trade:
pair=pair, # TODO: hacky workaround to avoid opening > max_open_trades
open_rate=row[OPEN_IDX], # This emulates previous behaviour - not sure if this is correct
open_date=row[DATE_IDX], # Prevents buying if the trade-slot was freed in this candle
stake_amount=stake_amount, open_trade_count_start += 1
amount=round(stake_amount / row[OPEN_IDX], 8), open_trade_count += 1
fee_open=self.fee, # logger.debug(f"{pair} - Emulate creation of new trade: {trade}.")
fee_close=self.fee, open_trades[pair].append(trade)
is_open=True, LocalTrade.add_bt_trade(trade)
)
# TODO: hacky workaround to avoid opening > max_open_trades
# This emulates previous behaviour - not sure if this is correct
# Prevents buying if the trade-slot was freed in this candle
open_trade_count_start += 1
open_trade_count += 1
# logger.debug(f"{pair} - Backtesting emulates creation of new trade: {trade}.")
open_trades[pair].append(trade)
Trade.trades.append(trade)
for trade in open_trades[pair]: for trade in open_trades[pair]:
# since indexes has been incremented before, we need to go one step back to
# also check the buying candle for sell conditions. # also check the buying candle for sell conditions.
trade_entry = self._get_sell_trade_entry(trade, row) trade_entry = self._get_sell_trade_entry(trade, row)
# Sell occured # Sell occured
@@ -411,6 +407,8 @@ class Backtesting:
# logger.debug(f"{pair} - Backtesting sell {trade}") # logger.debug(f"{pair} - Backtesting sell {trade}")
open_trade_count -= 1 open_trade_count -= 1
open_trades[pair].remove(trade) open_trades[pair].remove(trade)
LocalTrade.close_bt_trade(trade)
trades.append(trade_entry) trades.append(trade_entry)
if enable_protections: if enable_protections:
self.protections.stop_per_pair(pair, row[DATE_IDX]) self.protections.stop_per_pair(pair, row[DATE_IDX])
@@ -420,8 +418,56 @@ class Backtesting:
tmp += timedelta(minutes=self.timeframe_min) tmp += timedelta(minutes=self.timeframe_min)
trades += self.handle_left_open(open_trades, data=data) trades += self.handle_left_open(open_trades, data=data)
self.wallets.update()
return DataFrame.from_records(trades, columns=BacktestResult._fields) return trade_list_to_dataframe(trades)
def backtest_one_strategy(self, strat: IStrategy, data: Dict[str, Any], timerange: TimeRange):
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name())
backtest_start_time = datetime.now(timezone.utc)
self._set_strategy(strat)
strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)()
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
if self.config.get('use_max_market_positions', True):
# Must come from strategy config, as the strategy may modify this setting.
max_open_trades = self.strategy.config['max_open_trades']
else:
logger.info(
'Ignoring max_open_trades (--disable-max-market-positions was used) ...')
max_open_trades = 0
# need to reprocess data every time to populate signals
preprocessed = self.strategy.ohlcvdata_to_dataframe(data)
# Trim startup period from analyzed dataframe
for pair, df in preprocessed.items():
preprocessed[pair] = trim_dataframe(df, timerange)
min_date, max_date = history.get_timerange(preprocessed)
logger.info(f'Backtesting with data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
f'({(max_date - min_date).days} days)..')
# Execute backtest and store results
results = self.backtest(
processed=preprocessed,
start_date=min_date.datetime,
end_date=max_date.datetime,
max_open_trades=max_open_trades,
position_stacking=self.config.get('position_stacking', False),
enable_protections=self.config.get('enable_protections', False),
)
backtest_end_time = datetime.now(timezone.utc)
self.all_results[self.strategy.get_strategy_name()] = {
'results': results,
'config': self.strategy.config,
'locks': PairLocks.get_all_locks(),
'final_balance': self.wallets.get_total(self.strategy.config['stake_currency']),
'backtest_start_time': int(backtest_start_time.timestamp()),
'backtest_end_time': int(backtest_end_time.timestamp()),
}
return min_date, max_date
def start(self) -> None: def start(self) -> None:
""" """
@@ -430,58 +476,16 @@ class Backtesting:
""" """
data: Dict[str, Any] = {} data: Dict[str, Any] = {}
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
position_stacking = self.config.get('position_stacking', False)
data, timerange = self.load_bt_data() data, timerange = self.load_bt_data()
all_results = {}
for strat in self.strategylist: for strat in self.strategylist:
logger.info("Running backtesting for Strategy %s", strat.get_strategy_name()) min_date, max_date = self.backtest_one_strategy(strat, data, timerange)
self._set_strategy(strat) if len(self.strategylist) > 0:
stats = generate_backtest_stats(data, self.all_results,
min_date=min_date, max_date=max_date)
# Use max_open_trades in backtesting, except --disable-max-market-positions is set if self.config.get('export', False):
if self.config.get('use_max_market_positions', True): store_backtest_stats(self.config['exportfilename'], stats)
# Must come from strategy config, as the strategy may modify this setting.
max_open_trades = self.strategy.config['max_open_trades']
else:
logger.info(
'Ignoring max_open_trades (--disable-max-market-positions was used) ...')
max_open_trades = 0
# need to reprocess data every time to populate signals # Show backtest results
preprocessed = self.strategy.ohlcvdata_to_dataframe(data) show_backtest_results(self.config, stats)
# Trim startup period from analyzed dataframe
for pair, df in preprocessed.items():
preprocessed[pair] = trim_dataframe(df, timerange)
min_date, max_date = history.get_timerange(preprocessed)
logger.info(f'Backtesting with data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
f'({(max_date - min_date).days} days)..')
# Execute backtest and print results
results = self.backtest(
processed=preprocessed,
stake_amount=self.config['stake_amount'],
start_date=min_date.datetime,
end_date=max_date.datetime,
max_open_trades=max_open_trades,
position_stacking=position_stacking,
enable_protections=self.config.get('enable_protections', False),
)
all_results[self.strategy.get_strategy_name()] = {
'results': results,
'config': self.strategy.config,
'locks': PairLocks.locks,
}
stats = generate_backtest_stats(data, all_results, min_date=min_date, max_date=max_date)
if self.config.get('export', False):
store_backtest_stats(self.config['exportfilename'], stats)
# Show backtest results
show_backtest_results(self.config, stats)

View File

@@ -42,7 +42,7 @@ class ShortTradeDurHyperOptLoss(IHyperOptLoss):
* 0.25: Avoiding trade loss * 0.25: Avoiding trade loss
* 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
""" """
total_profit = results['profit_percent'].sum() total_profit = results['profit_ratio'].sum()
trade_duration = results['trade_duration'].mean() trade_duration = results['trade_duration'].mean()
trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8) trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)

View File

@@ -4,36 +4,31 @@
This module contains the hyperopt logic This module contains the hyperopt logic
""" """
import io
import locale import locale
import logging import logging
import random import random
import warnings import warnings
from collections import OrderedDict
from datetime import datetime from datetime import datetime
from math import ceil from math import ceil
from operator import itemgetter from operator import itemgetter
from pathlib import Path from pathlib import Path
from pprint import pformat
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional
import progressbar import progressbar
import rapidjson
import tabulate
from colorama import Fore, Style from colorama import Fore, Style
from colorama import init as colorama_init from colorama import init as colorama_init
from joblib import Parallel, cpu_count, delayed, dump, load, wrap_non_picklable_objects from joblib import Parallel, cpu_count, delayed, dump, load, wrap_non_picklable_objects
from pandas import DataFrame, isna, json_normalize from pandas import DataFrame
from freqtrade.constants import DATETIME_PRINT_FORMAT, LAST_BT_RESULT_FN from freqtrade.constants import DATETIME_PRINT_FORMAT, LAST_BT_RESULT_FN
from freqtrade.data.converter import trim_dataframe from freqtrade.data.converter import trim_dataframe
from freqtrade.data.history import get_timerange from freqtrade.data.history import get_timerange
from freqtrade.exceptions import OperationalException from freqtrade.misc import file_dump_json, plural
from freqtrade.misc import file_dump_json, plural, round_dict
from freqtrade.optimize.backtesting import Backtesting from freqtrade.optimize.backtesting import Backtesting
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules # Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F401 from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F401
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F401 from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F401
from freqtrade.optimize.hyperopt_tools import HyperoptTools
from freqtrade.resolvers.hyperopt_resolver import HyperOptLossResolver, HyperOptResolver from freqtrade.resolvers.hyperopt_resolver import HyperOptLossResolver, HyperOptResolver
from freqtrade.strategy import IStrategy from freqtrade.strategy import IStrategy
@@ -73,12 +68,15 @@ class Hyperopt:
self.backtesting = Backtesting(self.config) self.backtesting = Backtesting(self.config)
self.custom_hyperopt = HyperOptResolver.load_hyperopt(self.config) self.custom_hyperopt = HyperOptResolver.load_hyperopt(self.config)
self.custom_hyperopt.__class__.strategy = self.backtesting.strategy
self.custom_hyperoptloss = HyperOptLossResolver.load_hyperoptloss(self.config) self.custom_hyperoptloss = HyperOptLossResolver.load_hyperoptloss(self.config)
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
time_now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") time_now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
strategy = str(self.config['strategy'])
self.results_file = (self.config['user_data_dir'] / self.results_file = (self.config['user_data_dir'] /
'hyperopt_results' / f'hyperopt_results_{time_now}.pickle') 'hyperopt_results' /
f'strategy_{strategy}_hyperopt_results_{time_now}.pickle')
self.data_pickle_file = (self.config['user_data_dir'] / self.data_pickle_file = (self.config['user_data_dir'] /
'hyperopt_results' / 'hyperopt_tickerdata.pkl') 'hyperopt_results' / 'hyperopt_tickerdata.pkl')
self.total_epochs = config.get('epochs', 0) self.total_epochs = config.get('epochs', 0)
@@ -166,15 +164,6 @@ class Hyperopt:
file_dump_json(latest_filename, {'latest_hyperopt': str(self.results_file.name)}, file_dump_json(latest_filename, {'latest_hyperopt': str(self.results_file.name)},
log=False) log=False)
@staticmethod
def _read_results(results_file: Path) -> List:
"""
Read hyperopt results from file
"""
logger.info("Reading epochs from '%s'", results_file)
data = load(results_file)
return data
def _get_params_details(self, params: Dict) -> Dict: def _get_params_details(self, params: Dict) -> Dict:
""" """
Return the params for each space Return the params for each space
@@ -197,102 +186,16 @@ class Hyperopt:
return result return result
@staticmethod
def print_epoch_details(results, total_epochs: int, print_json: bool,
no_header: bool = False, header_str: str = None) -> None:
"""
Display details of the hyperopt result
"""
params = results.get('params_details', {})
# Default header string
if header_str is None:
header_str = "Best result"
if not no_header:
explanation_str = Hyperopt._format_explanation_string(results, total_epochs)
print(f"\n{header_str}:\n\n{explanation_str}\n")
if print_json:
result_dict: Dict = {}
for s in ['buy', 'sell', 'roi', 'stoploss', 'trailing']:
Hyperopt._params_update_for_json(result_dict, params, s)
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE))
else:
Hyperopt._params_pretty_print(params, 'buy', "Buy hyperspace params:")
Hyperopt._params_pretty_print(params, 'sell', "Sell hyperspace params:")
Hyperopt._params_pretty_print(params, 'roi', "ROI table:")
Hyperopt._params_pretty_print(params, 'stoploss', "Stoploss:")
Hyperopt._params_pretty_print(params, 'trailing', "Trailing stop:")
@staticmethod
def _params_update_for_json(result_dict, params, space: str) -> None:
if space in params:
space_params = Hyperopt._space_params(params, space)
if space in ['buy', 'sell']:
result_dict.setdefault('params', {}).update(space_params)
elif space == 'roi':
# TODO: get rid of OrderedDict when support for python 3.6 will be
# dropped (dicts keep the order as the language feature)
# Convert keys in min_roi dict to strings because
# rapidjson cannot dump dicts with integer keys...
# OrderedDict is used to keep the numeric order of the items
# in the dict.
result_dict['minimal_roi'] = OrderedDict(
(str(k), v) for k, v in space_params.items()
)
else: # 'stoploss', 'trailing'
result_dict.update(space_params)
@staticmethod
def _params_pretty_print(params, space: str, header: str) -> None:
if space in params:
space_params = Hyperopt._space_params(params, space, 5)
params_result = f"\n# {header}\n"
if space == 'stoploss':
params_result += f"stoploss = {space_params.get('stoploss')}"
elif space == 'roi':
# TODO: get rid of OrderedDict when support for python 3.6 will be
# dropped (dicts keep the order as the language feature)
minimal_roi_result = rapidjson.dumps(
OrderedDict(
(str(k), v) for k, v in space_params.items()
),
default=str, indent=4, number_mode=rapidjson.NM_NATIVE)
params_result += f"minimal_roi = {minimal_roi_result}"
elif space == 'trailing':
for k, v in space_params.items():
params_result += f'{k} = {v}\n'
else:
params_result += f"{space}_params = {pformat(space_params, indent=4)}"
params_result = params_result.replace("}", "\n}").replace("{", "{\n ")
params_result = params_result.replace("\n", "\n ")
print(params_result)
@staticmethod
def _space_params(params, space: str, r: int = None) -> Dict:
d = params[space]
# Round floats to `r` digits after the decimal point if requested
return round_dict(d, r) if r else d
@staticmethod
def is_best_loss(results, current_best_loss: float) -> bool:
return results['loss'] < current_best_loss
def print_results(self, results) -> None: def print_results(self, results) -> None:
""" """
Log results if it is better than any previous evaluation Log results if it is better than any previous evaluation
TODO: this should be moved to HyperoptTools too
""" """
is_best = results['is_best'] is_best = results['is_best']
if self.print_all or is_best: if self.print_all or is_best:
print( print(
self.get_result_table( HyperoptTools.get_result_table(
self.config, results, self.total_epochs, self.config, results, self.total_epochs,
self.print_all, self.print_colorized, self.print_all, self.print_colorized,
self.hyperopt_table_header self.hyperopt_table_header
@@ -300,164 +203,6 @@ class Hyperopt:
) )
self.hyperopt_table_header = 2 self.hyperopt_table_header = 2
@staticmethod
def _format_explanation_string(results, total_epochs) -> str:
return (("*" if results['is_initial_point'] else " ") +
f"{results['current_epoch']:5d}/{total_epochs}: " +
f"{results['results_explanation']} " +
f"Objective: {results['loss']:.5f}")
@staticmethod
def get_result_table(config: dict, results: list, total_epochs: int, highlight_best: bool,
print_colorized: bool, remove_header: int) -> str:
"""
Log result table
"""
if not results:
return ''
tabulate.PRESERVE_WHITESPACE = True
trials = json_normalize(results, max_level=1)
trials['Best'] = ''
if 'results_metrics.winsdrawslosses' not in trials.columns:
# Ensure compatibility with older versions of hyperopt results
trials['results_metrics.winsdrawslosses'] = 'N/A'
trials = trials[['Best', 'current_epoch', 'results_metrics.trade_count',
'results_metrics.winsdrawslosses',
'results_metrics.avg_profit', 'results_metrics.total_profit',
'results_metrics.profit', 'results_metrics.duration',
'loss', 'is_initial_point', 'is_best']]
trials.columns = ['Best', 'Epoch', 'Trades', ' Win Draw Loss', 'Avg profit',
'Total profit', 'Profit', 'Avg duration', 'Objective',
'is_initial_point', 'is_best']
trials['is_profit'] = False
trials.loc[trials['is_initial_point'], 'Best'] = '* '
trials.loc[trials['is_best'], 'Best'] = 'Best'
trials.loc[trials['is_initial_point'] & trials['is_best'], 'Best'] = '* Best'
trials.loc[trials['Total profit'] > 0, 'is_profit'] = True
trials['Trades'] = trials['Trades'].astype(str)
trials['Epoch'] = trials['Epoch'].apply(
lambda x: '{}/{}'.format(str(x).rjust(len(str(total_epochs)), ' '), total_epochs)
)
trials['Avg profit'] = trials['Avg profit'].apply(
lambda x: '{:,.2f}%'.format(x).rjust(7, ' ') if not isna(x) else "--".rjust(7, ' ')
)
trials['Avg duration'] = trials['Avg duration'].apply(
lambda x: '{:,.1f} m'.format(x).rjust(7, ' ') if not isna(x) else "--".rjust(7, ' ')
)
trials['Objective'] = trials['Objective'].apply(
lambda x: '{:,.5f}'.format(x).rjust(8, ' ') if x != 100000 else "N/A".rjust(8, ' ')
)
trials['Profit'] = trials.apply(
lambda x: '{:,.8f} {} {}'.format(
x['Total profit'], config['stake_currency'],
'({:,.2f}%)'.format(x['Profit']).rjust(10, ' ')
).rjust(25+len(config['stake_currency']))
if x['Total profit'] != 0.0 else '--'.rjust(25+len(config['stake_currency'])),
axis=1
)
trials = trials.drop(columns=['Total profit'])
if print_colorized:
for i in range(len(trials)):
if trials.loc[i]['is_profit']:
for j in range(len(trials.loc[i])-3):
trials.iat[i, j] = "{}{}{}".format(Fore.GREEN,
str(trials.loc[i][j]), Fore.RESET)
if trials.loc[i]['is_best'] and highlight_best:
for j in range(len(trials.loc[i])-3):
trials.iat[i, j] = "{}{}{}".format(Style.BRIGHT,
str(trials.loc[i][j]), Style.RESET_ALL)
trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit'])
if remove_header > 0:
table = tabulate.tabulate(
trials.to_dict(orient='list'), tablefmt='orgtbl',
headers='keys', stralign="right"
)
table = table.split("\n", remove_header)[remove_header]
elif remove_header < 0:
table = tabulate.tabulate(
trials.to_dict(orient='list'), tablefmt='psql',
headers='keys', stralign="right"
)
table = "\n".join(table.split("\n")[0:remove_header])
else:
table = tabulate.tabulate(
trials.to_dict(orient='list'), tablefmt='psql',
headers='keys', stralign="right"
)
return table
@staticmethod
def export_csv_file(config: dict, results: list, total_epochs: int, highlight_best: bool,
csv_file: str) -> None:
"""
Log result to csv-file
"""
if not results:
return
# Verification for overwrite
if Path(csv_file).is_file():
logger.error(f"CSV file already exists: {csv_file}")
return
try:
io.open(csv_file, 'w+').close()
except IOError:
logger.error(f"Failed to create CSV file: {csv_file}")
return
trials = json_normalize(results, max_level=1)
trials['Best'] = ''
trials['Stake currency'] = config['stake_currency']
base_metrics = ['Best', 'current_epoch', 'results_metrics.trade_count',
'results_metrics.avg_profit', 'results_metrics.total_profit',
'Stake currency', 'results_metrics.profit', 'results_metrics.duration',
'loss', 'is_initial_point', 'is_best']
param_metrics = [("params_dict."+param) for param in results[0]['params_dict'].keys()]
trials = trials[base_metrics + param_metrics]
base_columns = ['Best', 'Epoch', 'Trades', 'Avg profit', 'Total profit', 'Stake currency',
'Profit', 'Avg duration', 'Objective', 'is_initial_point', 'is_best']
param_columns = list(results[0]['params_dict'].keys())
trials.columns = base_columns + param_columns
trials['is_profit'] = False
trials.loc[trials['is_initial_point'], 'Best'] = '*'
trials.loc[trials['is_best'], 'Best'] = 'Best'
trials.loc[trials['is_initial_point'] & trials['is_best'], 'Best'] = '* Best'
trials.loc[trials['Total profit'] > 0, 'is_profit'] = True
trials['Epoch'] = trials['Epoch'].astype(str)
trials['Trades'] = trials['Trades'].astype(str)
trials['Total profit'] = trials['Total profit'].apply(
lambda x: '{:,.8f}'.format(x) if x != 0.0 else ""
)
trials['Profit'] = trials['Profit'].apply(
lambda x: '{:,.2f}'.format(x) if not isna(x) else ""
)
trials['Avg profit'] = trials['Avg profit'].apply(
lambda x: '{:,.2f}%'.format(x) if not isna(x) else ""
)
trials['Avg duration'] = trials['Avg duration'].apply(
lambda x: '{:,.1f} m'.format(x) if not isna(x) else ""
)
trials['Objective'] = trials['Objective'].apply(
lambda x: '{:,.5f}'.format(x) if x != 100000 else ""
)
trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit'])
trials.to_csv(csv_file, index=False, header=True, mode='w', encoding='UTF-8')
logger.info(f"CSV file created: {csv_file}")
def has_space(self, space: str) -> bool: def has_space(self, space: str) -> bool:
""" """
Tell if the space value is contained in the configuration Tell if the space value is contained in the configuration
@@ -537,7 +282,6 @@ class Hyperopt:
backtesting_results = self.backtesting.backtest( backtesting_results = self.backtesting.backtest(
processed=processed, processed=processed,
stake_amount=self.config['stake_amount'],
start_date=min_date.datetime, start_date=min_date.datetime,
end_date=max_date.datetime, end_date=max_date.datetime,
max_open_trades=self.max_open_trades, max_open_trades=self.max_open_trades,
@@ -546,10 +290,11 @@ class Hyperopt:
) )
return self._get_results_dict(backtesting_results, min_date, max_date, return self._get_results_dict(backtesting_results, min_date, max_date,
params_dict, params_details) params_dict, params_details,
processed=processed)
def _get_results_dict(self, backtesting_results, min_date, max_date, def _get_results_dict(self, backtesting_results, min_date, max_date,
params_dict, params_details): params_dict, params_details, processed: Dict[str, DataFrame]):
results_metrics = self._calculate_results_metrics(backtesting_results) results_metrics = self._calculate_results_metrics(backtesting_results)
results_explanation = self._format_results_explanation_string(results_metrics) results_explanation = self._format_results_explanation_string(results_metrics)
@@ -563,7 +308,8 @@ class Hyperopt:
loss: float = MAX_LOSS loss: float = MAX_LOSS
if trade_count >= self.config['hyperopt_min_trades']: if trade_count >= self.config['hyperopt_min_trades']:
loss = self.calculate_loss(results=backtesting_results, trade_count=trade_count, loss = self.calculate_loss(results=backtesting_results, trade_count=trade_count,
min_date=min_date.datetime, max_date=max_date.datetime) min_date=min_date.datetime, max_date=max_date.datetime,
config=self.config, processed=processed)
return { return {
'loss': loss, 'loss': loss,
'params_dict': params_dict, 'params_dict': params_dict,
@@ -574,20 +320,20 @@ class Hyperopt:
} }
def _calculate_results_metrics(self, backtesting_results: DataFrame) -> Dict: def _calculate_results_metrics(self, backtesting_results: DataFrame) -> Dict:
wins = len(backtesting_results[backtesting_results.profit_percent > 0]) wins = len(backtesting_results[backtesting_results['profit_ratio'] > 0])
draws = len(backtesting_results[backtesting_results.profit_percent == 0]) draws = len(backtesting_results[backtesting_results['profit_ratio'] == 0])
losses = len(backtesting_results[backtesting_results.profit_percent < 0]) losses = len(backtesting_results[backtesting_results['profit_ratio'] < 0])
return { return {
'trade_count': len(backtesting_results.index), 'trade_count': len(backtesting_results.index),
'wins': wins, 'wins': wins,
'draws': draws, 'draws': draws,
'losses': losses, 'losses': losses,
'winsdrawslosses': f"{wins:>4} {draws:>4} {losses:>4}", 'winsdrawslosses': f"{wins:>4} {draws:>4} {losses:>4}",
'avg_profit': backtesting_results.profit_percent.mean() * 100.0, 'avg_profit': backtesting_results['profit_ratio'].mean() * 100.0,
'median_profit': backtesting_results.profit_percent.median() * 100.0, 'median_profit': backtesting_results['profit_ratio'].median() * 100.0,
'total_profit': backtesting_results.profit_abs.sum(), 'total_profit': backtesting_results['profit_abs'].sum(),
'profit': backtesting_results.profit_percent.sum() * 100.0, 'profit': backtesting_results['profit_ratio'].sum() * 100.0,
'duration': backtesting_results.trade_duration.mean(), 'duration': backtesting_results['trade_duration'].mean(),
} }
def _format_results_explanation_string(self, results_metrics: Dict) -> str: def _format_results_explanation_string(self, results_metrics: Dict) -> str:
@@ -620,22 +366,6 @@ class Hyperopt:
return parallel(delayed( return parallel(delayed(
wrap_non_picklable_objects(self.generate_optimizer))(v, i) for v in asked) wrap_non_picklable_objects(self.generate_optimizer))(v, i) for v in asked)
@staticmethod
def load_previous_results(results_file: Path) -> List:
"""
Load data for epochs from the file if we have one
"""
epochs: List = []
if results_file.is_file() and results_file.stat().st_size > 0:
epochs = Hyperopt._read_results(results_file)
# Detection of some old format, without 'is_best' field saved
if epochs[0].get('is_best') is None:
raise OperationalException(
"The file with Hyperopt results is incompatible with this version "
"of Freqtrade and cannot be loaded.")
logger.info(f"Loaded {len(epochs)} previous evaluations from disk.")
return epochs
def _set_random_state(self, random_state: Optional[int]) -> int: def _set_random_state(self, random_state: Optional[int]) -> int:
return random_state or random.randint(1, 2**16 - 1) return random_state or random.randint(1, 2**16 - 1)
@@ -650,7 +380,7 @@ class Hyperopt:
# Trim startup period from analyzed dataframe # Trim startup period from analyzed dataframe
for pair, df in preprocessed.items(): for pair, df in preprocessed.items():
preprocessed[pair] = trim_dataframe(df, timerange) preprocessed[pair] = trim_dataframe(df, timerange)
min_date, max_date = get_timerange(data) min_date, max_date = get_timerange(preprocessed)
logger.info(f'Hyperopting with data from {min_date.strftime(DATETIME_PRINT_FORMAT)} ' logger.info(f'Hyperopting with data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} ' f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
@@ -659,7 +389,10 @@ class Hyperopt:
dump(preprocessed, self.data_pickle_file) dump(preprocessed, self.data_pickle_file)
# We don't need exchange instance anymore while running hyperopt # We don't need exchange instance anymore while running hyperopt
self.backtesting.exchange = None # type: ignore self.backtesting.exchange.close()
self.backtesting.exchange._api = None # type: ignore
self.backtesting.exchange._api_async = None # type: ignore
# self.backtesting.exchange = None # type: ignore
self.backtesting.pairlists = None # type: ignore self.backtesting.pairlists = None # type: ignore
self.backtesting.strategy.dp = None # type: ignore self.backtesting.strategy.dp = None # type: ignore
IStrategy.dp = None # type: ignore IStrategy.dp = None # type: ignore
@@ -725,7 +458,7 @@ class Hyperopt:
logger.debug(f"Optimizer epoch evaluated: {val}") logger.debug(f"Optimizer epoch evaluated: {val}")
is_best = self.is_best_loss(val, self.current_best_loss) is_best = HyperoptTools.is_best_loss(val, self.current_best_loss)
# This value is assigned here and not in the optimization method # This value is assigned here and not in the optimization method
# to keep proper order in the list of results. That's because # to keep proper order in the list of results. That's because
# evaluations can take different time. Here they are aligned in the # evaluations can take different time. Here they are aligned in the
@@ -753,7 +486,7 @@ class Hyperopt:
if self.epochs: if self.epochs:
sorted_epochs = sorted(self.epochs, key=itemgetter('loss')) sorted_epochs = sorted(self.epochs, key=itemgetter('loss'))
best_epoch = sorted_epochs[0] best_epoch = sorted_epochs[0]
self.print_epoch_details(best_epoch, self.total_epochs, self.print_json) HyperoptTools.print_epoch_details(best_epoch, self.total_epochs, self.print_json)
else: else:
# This is printed when Ctrl+C is pressed quickly, before first epochs have # This is printed when Ctrl+C is pressed quickly, before first epochs have
# a chance to be evaluated. # a chance to be evaluated.

View File

@@ -12,6 +12,7 @@ from skopt.space import Categorical, Dimension, Integer, Real
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import timeframe_to_minutes
from freqtrade.misc import round_dict from freqtrade.misc import round_dict
from freqtrade.strategy import IStrategy
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -34,6 +35,7 @@ class IHyperOpt(ABC):
""" """
ticker_interval: str # DEPRECATED ticker_interval: str # DEPRECATED
timeframe: str timeframe: str
strategy: IStrategy
def __init__(self, config: dict) -> None: def __init__(self, config: dict) -> None:
self.config = config self.config = config

View File

@@ -5,6 +5,7 @@ This module defines the interface for the loss-function for hyperopt
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from datetime import datetime from datetime import datetime
from typing import Dict
from pandas import DataFrame from pandas import DataFrame
@@ -19,7 +20,9 @@ class IHyperOptLoss(ABC):
@staticmethod @staticmethod
@abstractmethod @abstractmethod
def hyperopt_loss_function(results: DataFrame, trade_count: int, def hyperopt_loss_function(results: DataFrame, trade_count: int,
min_date: datetime, max_date: datetime, *args, **kwargs) -> float: min_date: datetime, max_date: datetime,
config: Dict, processed: Dict[str, DataFrame],
*args, **kwargs) -> float:
""" """
Objective function, returns smaller number for better results Objective function, returns smaller number for better results
""" """

View File

@@ -34,5 +34,5 @@ class OnlyProfitHyperOptLoss(IHyperOptLoss):
""" """
Objective function, returns smaller number for better results. Objective function, returns smaller number for better results.
""" """
total_profit = results['profit_percent'].sum() total_profit = results['profit_ratio'].sum()
return 1 - total_profit / EXPECTED_MAX_PROFIT return 1 - total_profit / EXPECTED_MAX_PROFIT

View File

@@ -28,7 +28,7 @@ class SharpeHyperOptLoss(IHyperOptLoss):
Uses Sharpe Ratio calculation. Uses Sharpe Ratio calculation.
""" """
total_profit = results["profit_percent"] total_profit = results["profit_ratio"]
days_period = (max_date - min_date).days days_period = (max_date - min_date).days
# adding slippage of 0.1% per trade # adding slippage of 0.1% per trade

View File

@@ -34,9 +34,9 @@ class SharpeHyperOptLossDaily(IHyperOptLoss):
annual_risk_free_rate = 0.0 annual_risk_free_rate = 0.0
risk_free_rate = annual_risk_free_rate / days_in_year risk_free_rate = annual_risk_free_rate / days_in_year
# apply slippage per trade to profit_percent # apply slippage per trade to profit_ratio
results.loc[:, 'profit_percent_after_slippage'] = \ results.loc[:, 'profit_ratio_after_slippage'] = \
results['profit_percent'] - slippage_per_trade_ratio results['profit_ratio'] - slippage_per_trade_ratio
# create the index within the min_date and end max_date # create the index within the min_date and end max_date
t_index = date_range(start=min_date, end=max_date, freq=resample_freq, t_index = date_range(start=min_date, end=max_date, freq=resample_freq,
@@ -44,10 +44,10 @@ class SharpeHyperOptLossDaily(IHyperOptLoss):
sum_daily = ( sum_daily = (
results.resample(resample_freq, on='close_date').agg( results.resample(resample_freq, on='close_date').agg(
{"profit_percent_after_slippage": sum}).reindex(t_index).fillna(0) {"profit_ratio_after_slippage": sum}).reindex(t_index).fillna(0)
) )
total_profit = sum_daily["profit_percent_after_slippage"] - risk_free_rate total_profit = sum_daily["profit_ratio_after_slippage"] - risk_free_rate
expected_returns_mean = total_profit.mean() expected_returns_mean = total_profit.mean()
up_stdev = total_profit.std() up_stdev = total_profit.std()

View File

@@ -28,7 +28,7 @@ class SortinoHyperOptLoss(IHyperOptLoss):
Uses Sortino Ratio calculation. Uses Sortino Ratio calculation.
""" """
total_profit = results["profit_percent"] total_profit = results["profit_ratio"]
days_period = (max_date - min_date).days days_period = (max_date - min_date).days
# adding slippage of 0.1% per trade # adding slippage of 0.1% per trade
@@ -36,7 +36,7 @@ class SortinoHyperOptLoss(IHyperOptLoss):
expected_returns_mean = total_profit.sum() / days_period expected_returns_mean = total_profit.sum() / days_period
results['downside_returns'] = 0 results['downside_returns'] = 0
results.loc[total_profit < 0, 'downside_returns'] = results['profit_percent'] results.loc[total_profit < 0, 'downside_returns'] = results['profit_ratio']
down_stdev = np.std(results['downside_returns']) down_stdev = np.std(results['downside_returns'])
if down_stdev != 0: if down_stdev != 0:

View File

@@ -36,9 +36,9 @@ class SortinoHyperOptLossDaily(IHyperOptLoss):
days_in_year = 365 days_in_year = 365
minimum_acceptable_return = 0.0 minimum_acceptable_return = 0.0
# apply slippage per trade to profit_percent # apply slippage per trade to profit_ratio
results.loc[:, 'profit_percent_after_slippage'] = \ results.loc[:, 'profit_ratio_after_slippage'] = \
results['profit_percent'] - slippage_per_trade_ratio results['profit_ratio'] - slippage_per_trade_ratio
# create the index within the min_date and end max_date # create the index within the min_date and end max_date
t_index = date_range(start=min_date, end=max_date, freq=resample_freq, t_index = date_range(start=min_date, end=max_date, freq=resample_freq,
@@ -46,17 +46,17 @@ class SortinoHyperOptLossDaily(IHyperOptLoss):
sum_daily = ( sum_daily = (
results.resample(resample_freq, on='close_date').agg( results.resample(resample_freq, on='close_date').agg(
{"profit_percent_after_slippage": sum}).reindex(t_index).fillna(0) {"profit_ratio_after_slippage": sum}).reindex(t_index).fillna(0)
) )
total_profit = sum_daily["profit_percent_after_slippage"] - minimum_acceptable_return total_profit = sum_daily["profit_ratio_after_slippage"] - minimum_acceptable_return
expected_returns_mean = total_profit.mean() expected_returns_mean = total_profit.mean()
sum_daily['downside_returns'] = 0 sum_daily['downside_returns'] = 0
sum_daily.loc[total_profit < 0, 'downside_returns'] = total_profit sum_daily.loc[total_profit < 0, 'downside_returns'] = total_profit
total_downside = sum_daily['downside_returns'] total_downside = sum_daily['downside_returns']
# Here total_downside contains min(0, P - MAR) values, # Here total_downside contains min(0, P - MAR) values,
# where P = sum_daily["profit_percent_after_slippage"] # where P = sum_daily["profit_ratio_after_slippage"]
down_stdev = math.sqrt((total_downside**2).sum() / len(total_downside)) down_stdev = math.sqrt((total_downside**2).sum() / len(total_downside))
if down_stdev != 0: if down_stdev != 0:

View File

@@ -0,0 +1,294 @@
import io
import logging
from collections import OrderedDict
from pathlib import Path
from pprint import pformat
from typing import Dict, List
import rapidjson
import tabulate
from colorama import Fore, Style
from joblib import load
from pandas import isna, json_normalize
from freqtrade.exceptions import OperationalException
from freqtrade.misc import round_dict
logger = logging.getLogger(__name__)
class HyperoptTools():
@staticmethod
def _read_results(results_file: Path) -> List:
"""
Read hyperopt results from file
"""
logger.info("Reading epochs from '%s'", results_file)
data = load(results_file)
return data
@staticmethod
def load_previous_results(results_file: Path) -> List:
"""
Load data for epochs from the file if we have one
"""
epochs: List = []
if results_file.is_file() and results_file.stat().st_size > 0:
epochs = HyperoptTools._read_results(results_file)
# Detection of some old format, without 'is_best' field saved
if epochs[0].get('is_best') is None:
raise OperationalException(
"The file with HyperoptTools results is incompatible with this version "
"of Freqtrade and cannot be loaded.")
logger.info(f"Loaded {len(epochs)} previous evaluations from disk.")
return epochs
@staticmethod
def print_epoch_details(results, total_epochs: int, print_json: bool,
no_header: bool = False, header_str: str = None) -> None:
"""
Display details of the hyperopt result
"""
params = results.get('params_details', {})
# Default header string
if header_str is None:
header_str = "Best result"
if not no_header:
explanation_str = HyperoptTools._format_explanation_string(results, total_epochs)
print(f"\n{header_str}:\n\n{explanation_str}\n")
if print_json:
result_dict: Dict = {}
for s in ['buy', 'sell', 'roi', 'stoploss', 'trailing']:
HyperoptTools._params_update_for_json(result_dict, params, s)
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE))
else:
HyperoptTools._params_pretty_print(params, 'buy', "Buy hyperspace params:")
HyperoptTools._params_pretty_print(params, 'sell', "Sell hyperspace params:")
HyperoptTools._params_pretty_print(params, 'roi', "ROI table:")
HyperoptTools._params_pretty_print(params, 'stoploss', "Stoploss:")
HyperoptTools._params_pretty_print(params, 'trailing', "Trailing stop:")
@staticmethod
def _params_update_for_json(result_dict, params, space: str) -> None:
if space in params:
space_params = HyperoptTools._space_params(params, space)
if space in ['buy', 'sell']:
result_dict.setdefault('params', {}).update(space_params)
elif space == 'roi':
# TODO: get rid of OrderedDict when support for python 3.6 will be
# dropped (dicts keep the order as the language feature)
# Convert keys in min_roi dict to strings because
# rapidjson cannot dump dicts with integer keys...
# OrderedDict is used to keep the numeric order of the items
# in the dict.
result_dict['minimal_roi'] = OrderedDict(
(str(k), v) for k, v in space_params.items()
)
else: # 'stoploss', 'trailing'
result_dict.update(space_params)
@staticmethod
def _params_pretty_print(params, space: str, header: str) -> None:
if space in params:
space_params = HyperoptTools._space_params(params, space, 5)
params_result = f"\n# {header}\n"
if space == 'stoploss':
params_result += f"stoploss = {space_params.get('stoploss')}"
elif space == 'roi':
# TODO: get rid of OrderedDict when support for python 3.6 will be
# dropped (dicts keep the order as the language feature)
minimal_roi_result = rapidjson.dumps(
OrderedDict(
(str(k), v) for k, v in space_params.items()
),
default=str, indent=4, number_mode=rapidjson.NM_NATIVE)
params_result += f"minimal_roi = {minimal_roi_result}"
elif space == 'trailing':
for k, v in space_params.items():
params_result += f'{k} = {v}\n'
else:
params_result += f"{space}_params = {pformat(space_params, indent=4)}"
params_result = params_result.replace("}", "\n}").replace("{", "{\n ")
params_result = params_result.replace("\n", "\n ")
print(params_result)
@staticmethod
def _space_params(params, space: str, r: int = None) -> Dict:
d = params[space]
# Round floats to `r` digits after the decimal point if requested
return round_dict(d, r) if r else d
@staticmethod
def is_best_loss(results, current_best_loss: float) -> bool:
return results['loss'] < current_best_loss
@staticmethod
def _format_explanation_string(results, total_epochs) -> str:
return (("*" if results['is_initial_point'] else " ") +
f"{results['current_epoch']:5d}/{total_epochs}: " +
f"{results['results_explanation']} " +
f"Objective: {results['loss']:.5f}")
@staticmethod
def get_result_table(config: dict, results: list, total_epochs: int, highlight_best: bool,
print_colorized: bool, remove_header: int) -> str:
"""
Log result table
"""
if not results:
return ''
tabulate.PRESERVE_WHITESPACE = True
trials = json_normalize(results, max_level=1)
trials['Best'] = ''
if 'results_metrics.winsdrawslosses' not in trials.columns:
# Ensure compatibility with older versions of hyperopt results
trials['results_metrics.winsdrawslosses'] = 'N/A'
trials = trials[['Best', 'current_epoch', 'results_metrics.trade_count',
'results_metrics.winsdrawslosses',
'results_metrics.avg_profit', 'results_metrics.total_profit',
'results_metrics.profit', 'results_metrics.duration',
'loss', 'is_initial_point', 'is_best']]
trials.columns = ['Best', 'Epoch', 'Trades', ' Win Draw Loss', 'Avg profit',
'Total profit', 'Profit', 'Avg duration', 'Objective',
'is_initial_point', 'is_best']
trials['is_profit'] = False
trials.loc[trials['is_initial_point'], 'Best'] = '* '
trials.loc[trials['is_best'], 'Best'] = 'Best'
trials.loc[trials['is_initial_point'] & trials['is_best'], 'Best'] = '* Best'
trials.loc[trials['Total profit'] > 0, 'is_profit'] = True
trials['Trades'] = trials['Trades'].astype(str)
trials['Epoch'] = trials['Epoch'].apply(
lambda x: '{}/{}'.format(str(x).rjust(len(str(total_epochs)), ' '), total_epochs)
)
trials['Avg profit'] = trials['Avg profit'].apply(
lambda x: '{:,.2f}%'.format(x).rjust(7, ' ') if not isna(x) else "--".rjust(7, ' ')
)
trials['Avg duration'] = trials['Avg duration'].apply(
lambda x: '{:,.1f} m'.format(x).rjust(7, ' ') if not isna(x) else "--".rjust(7, ' ')
)
trials['Objective'] = trials['Objective'].apply(
lambda x: '{:,.5f}'.format(x).rjust(8, ' ') if x != 100000 else "N/A".rjust(8, ' ')
)
trials['Profit'] = trials.apply(
lambda x: '{:,.8f} {} {}'.format(
x['Total profit'], config['stake_currency'],
'({:,.2f}%)'.format(x['Profit']).rjust(10, ' ')
).rjust(25+len(config['stake_currency']))
if x['Total profit'] != 0.0 else '--'.rjust(25+len(config['stake_currency'])),
axis=1
)
trials = trials.drop(columns=['Total profit'])
if print_colorized:
for i in range(len(trials)):
if trials.loc[i]['is_profit']:
for j in range(len(trials.loc[i])-3):
trials.iat[i, j] = "{}{}{}".format(Fore.GREEN,
str(trials.loc[i][j]), Fore.RESET)
if trials.loc[i]['is_best'] and highlight_best:
for j in range(len(trials.loc[i])-3):
trials.iat[i, j] = "{}{}{}".format(Style.BRIGHT,
str(trials.loc[i][j]), Style.RESET_ALL)
trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit'])
if remove_header > 0:
table = tabulate.tabulate(
trials.to_dict(orient='list'), tablefmt='orgtbl',
headers='keys', stralign="right"
)
table = table.split("\n", remove_header)[remove_header]
elif remove_header < 0:
table = tabulate.tabulate(
trials.to_dict(orient='list'), tablefmt='psql',
headers='keys', stralign="right"
)
table = "\n".join(table.split("\n")[0:remove_header])
else:
table = tabulate.tabulate(
trials.to_dict(orient='list'), tablefmt='psql',
headers='keys', stralign="right"
)
return table
@staticmethod
def export_csv_file(config: dict, results: list, total_epochs: int, highlight_best: bool,
csv_file: str) -> None:
"""
Log result to csv-file
"""
if not results:
return
# Verification for overwrite
if Path(csv_file).is_file():
logger.error(f"CSV file already exists: {csv_file}")
return
try:
io.open(csv_file, 'w+').close()
except IOError:
logger.error(f"Failed to create CSV file: {csv_file}")
return
trials = json_normalize(results, max_level=1)
trials['Best'] = ''
trials['Stake currency'] = config['stake_currency']
base_metrics = ['Best', 'current_epoch', 'results_metrics.trade_count',
'results_metrics.avg_profit', 'results_metrics.median_profit',
'results_metrics.total_profit',
'Stake currency', 'results_metrics.profit', 'results_metrics.duration',
'loss', 'is_initial_point', 'is_best']
param_metrics = [("params_dict."+param) for param in results[0]['params_dict'].keys()]
trials = trials[base_metrics + param_metrics]
base_columns = ['Best', 'Epoch', 'Trades', 'Avg profit', 'Median profit', 'Total profit',
'Stake currency', 'Profit', 'Avg duration', 'Objective',
'is_initial_point', 'is_best']
param_columns = list(results[0]['params_dict'].keys())
trials.columns = base_columns + param_columns
trials['is_profit'] = False
trials.loc[trials['is_initial_point'], 'Best'] = '*'
trials.loc[trials['is_best'], 'Best'] = 'Best'
trials.loc[trials['is_initial_point'] & trials['is_best'], 'Best'] = '* Best'
trials.loc[trials['Total profit'] > 0, 'is_profit'] = True
trials['Epoch'] = trials['Epoch'].astype(str)
trials['Trades'] = trials['Trades'].astype(str)
trials['Total profit'] = trials['Total profit'].apply(
lambda x: '{:,.8f}'.format(x) if x != 0.0 else ""
)
trials['Profit'] = trials['Profit'].apply(
lambda x: '{:,.2f}'.format(x) if not isna(x) else ""
)
trials['Avg profit'] = trials['Avg profit'].apply(
lambda x: '{:,.2f}%'.format(x) if not isna(x) else ""
)
trials['Avg duration'] = trials['Avg duration'].apply(
lambda x: '{:,.1f} m'.format(x) if not isna(x) else ""
)
trials['Objective'] = trials['Objective'].apply(
lambda x: '{:,.5f}'.format(x) if x != 100000 else ""
)
trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit'])
trials.to_csv(csv_file, index=False, header=True, mode='w', encoding='UTF-8')
logger.info(f"CSV file created: {csv_file}")

View File

@@ -8,9 +8,10 @@ from numpy import int64
from pandas import DataFrame from pandas import DataFrame
from tabulate import tabulate from tabulate import tabulate
from freqtrade.constants import DATETIME_PRINT_FORMAT, LAST_BT_RESULT_FN from freqtrade.constants import DATETIME_PRINT_FORMAT, LAST_BT_RESULT_FN, UNLIMITED_STAKE_AMOUNT
from freqtrade.data.btanalysis import calculate_market_change, calculate_max_drawdown from freqtrade.data.btanalysis import (calculate_csum, calculate_market_change,
from freqtrade.misc import file_dump_json calculate_max_drawdown)
from freqtrade.misc import decimals_per_coin, file_dump_json, round_coin_value
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -38,11 +39,12 @@ def store_backtest_stats(recordfilename: Path, stats: Dict[str, DataFrame]) -> N
file_dump_json(latest_filename, {'latest_backtest': str(filename.name)}) file_dump_json(latest_filename, {'latest_backtest': str(filename.name)})
def _get_line_floatfmt() -> List[str]: def _get_line_floatfmt(stake_currency: str) -> List[str]:
""" """
Generate floatformat (goes in line with _generate_result_line()) Generate floatformat (goes in line with _generate_result_line())
""" """
return ['s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', 'd', 'd', 'd'] return ['s', 'd', '.2f', '.2f', f'.{decimals_per_coin(stake_currency)}f',
'.2f', 'd', 'd', 'd', 'd']
def _get_line_header(first_column: str, stake_currency: str) -> List[str]: def _get_line_header(first_column: str, stake_currency: str) -> List[str]:
@@ -54,18 +56,19 @@ def _get_line_header(first_column: str, stake_currency: str) -> List[str]:
'Wins', 'Draws', 'Losses'] 'Wins', 'Draws', 'Losses']
def _generate_result_line(result: DataFrame, max_open_trades: int, first_column: str) -> Dict: def _generate_result_line(result: DataFrame, starting_balance: int, first_column: str) -> Dict:
""" """
Generate one result dict, with "first_column" as key. Generate one result dict, with "first_column" as key.
""" """
profit_sum = result['profit_percent'].sum() profit_sum = result['profit_ratio'].sum()
profit_total = profit_sum / max_open_trades # (end-capital - starting capital) / starting capital
profit_total = result['profit_abs'].sum() / starting_balance
return { return {
'key': first_column, 'key': first_column,
'trades': len(result), 'trades': len(result),
'profit_mean': result['profit_percent'].mean() if len(result) > 0 else 0.0, 'profit_mean': result['profit_ratio'].mean() if len(result) > 0 else 0.0,
'profit_mean_pct': result['profit_percent'].mean() * 100.0 if len(result) > 0 else 0.0, 'profit_mean_pct': result['profit_ratio'].mean() * 100.0 if len(result) > 0 else 0.0,
'profit_sum': profit_sum, 'profit_sum': profit_sum,
'profit_sum_pct': round(profit_sum * 100.0, 2), 'profit_sum_pct': round(profit_sum * 100.0, 2),
'profit_total_abs': result['profit_abs'].sum(), 'profit_total_abs': result['profit_abs'].sum(),
@@ -86,13 +89,13 @@ def _generate_result_line(result: DataFrame, max_open_trades: int, first_column:
} }
def generate_pair_metrics(data: Dict[str, Dict], stake_currency: str, max_open_trades: int, def generate_pair_metrics(data: Dict[str, Dict], stake_currency: str, starting_balance: int,
results: DataFrame, skip_nan: bool = False) -> List[Dict]: results: DataFrame, skip_nan: bool = False) -> List[Dict]:
""" """
Generates and returns a list for the given backtest data and the results dataframe Generates and returns a list for the given backtest data and the results dataframe
:param data: Dict of <pair: dataframe> containing data that was used during backtesting. :param data: Dict of <pair: dataframe> containing data that was used during backtesting.
:param stake_currency: stake-currency - used to correctly name headers :param stake_currency: stake-currency - used to correctly name headers
:param max_open_trades: Maximum allowed open trades :param starting_balance: Starting balance
:param results: Dataframe containing the backtest results :param results: Dataframe containing the backtest results
:param skip_nan: Print "left open" open trades :param skip_nan: Print "left open" open trades
:return: List of Dicts containing the metrics per pair :return: List of Dicts containing the metrics per pair
@@ -105,10 +108,10 @@ def generate_pair_metrics(data: Dict[str, Dict], stake_currency: str, max_open_t
if skip_nan and result['profit_abs'].isnull().all(): if skip_nan and result['profit_abs'].isnull().all():
continue continue
tabular_data.append(_generate_result_line(result, max_open_trades, pair)) tabular_data.append(_generate_result_line(result, starting_balance, pair))
# Append Total # Append Total
tabular_data.append(_generate_result_line(results, max_open_trades, 'TOTAL')) tabular_data.append(_generate_result_line(results, starting_balance, 'TOTAL'))
return tabular_data return tabular_data
@@ -124,13 +127,13 @@ def generate_sell_reason_stats(max_open_trades: int, results: DataFrame) -> List
for reason, count in results['sell_reason'].value_counts().iteritems(): for reason, count in results['sell_reason'].value_counts().iteritems():
result = results.loc[results['sell_reason'] == reason] result = results.loc[results['sell_reason'] == reason]
profit_mean = result['profit_percent'].mean() profit_mean = result['profit_ratio'].mean()
profit_sum = result['profit_percent'].sum() profit_sum = result['profit_ratio'].sum()
profit_total = profit_sum / max_open_trades profit_total = profit_sum / max_open_trades
tabular_data.append( tabular_data.append(
{ {
'sell_reason': reason.value, 'sell_reason': reason,
'trades': count, 'trades': count,
'wins': len(result[result['profit_abs'] > 0]), 'wins': len(result[result['profit_abs'] > 0]),
'draws': len(result[result['profit_abs'] == 0]), 'draws': len(result[result['profit_abs'] == 0]),
@@ -150,14 +153,14 @@ def generate_sell_reason_stats(max_open_trades: int, results: DataFrame) -> List
def generate_strategy_metrics(all_results: Dict) -> List[Dict]: def generate_strategy_metrics(all_results: Dict) -> List[Dict]:
""" """
Generate summary per strategy Generate summary per strategy
:param all_results: Dict of <Strategyname: BacktestResult> containing results for all strategies :param all_results: Dict of <Strategyname: DataFrame> containing results for all strategies
:return: List of Dicts containing the metrics per Strategy :return: List of Dicts containing the metrics per Strategy
""" """
tabular_data = [] tabular_data = []
for strategy, results in all_results.items(): for strategy, results in all_results.items():
tabular_data.append(_generate_result_line( tabular_data.append(_generate_result_line(
results['results'], results['config']['max_open_trades'], strategy) results['results'], results['config']['dry_run_wallet'], strategy)
) )
return tabular_data return tabular_data
@@ -193,25 +196,32 @@ def generate_daily_stats(results: DataFrame) -> Dict[str, Any]:
return { return {
'backtest_best_day': 0, 'backtest_best_day': 0,
'backtest_worst_day': 0, 'backtest_worst_day': 0,
'backtest_best_day_abs': 0,
'backtest_worst_day_abs': 0,
'winning_days': 0, 'winning_days': 0,
'draw_days': 0, 'draw_days': 0,
'losing_days': 0, 'losing_days': 0,
'winner_holding_avg': timedelta(), 'winner_holding_avg': timedelta(),
'loser_holding_avg': timedelta(), 'loser_holding_avg': timedelta(),
} }
daily_profit = results.resample('1d', on='close_date')['profit_percent'].sum() daily_profit_rel = results.resample('1d', on='close_date')['profit_ratio'].sum()
daily_profit = results.resample('1d', on='close_date')['profit_abs'].sum().round(10)
worst_rel = min(daily_profit_rel)
best_rel = max(daily_profit_rel)
worst = min(daily_profit) worst = min(daily_profit)
best = max(daily_profit) best = max(daily_profit)
winning_days = sum(daily_profit > 0) winning_days = sum(daily_profit > 0)
draw_days = sum(daily_profit == 0) draw_days = sum(daily_profit == 0)
losing_days = sum(daily_profit < 0) losing_days = sum(daily_profit < 0)
winning_trades = results.loc[results['profit_percent'] > 0] winning_trades = results.loc[results['profit_ratio'] > 0]
losing_trades = results.loc[results['profit_percent'] < 0] losing_trades = results.loc[results['profit_ratio'] < 0]
return { return {
'backtest_best_day': best, 'backtest_best_day': best_rel,
'backtest_worst_day': worst, 'backtest_worst_day': worst_rel,
'backtest_best_day_abs': best,
'backtest_worst_day_abs': worst,
'winning_days': winning_days, 'winning_days': winning_days,
'draw_days': draw_days, 'draw_days': draw_days,
'losing_days': losing_days, 'losing_days': losing_days,
@@ -243,17 +253,18 @@ def generate_backtest_stats(btdata: Dict[str, DataFrame],
if not isinstance(results, DataFrame): if not isinstance(results, DataFrame):
continue continue
config = content['config'] config = content['config']
max_open_trades = config['max_open_trades'] max_open_trades = min(config['max_open_trades'], len(btdata.keys()))
starting_balance = config['dry_run_wallet']
stake_currency = config['stake_currency'] stake_currency = config['stake_currency']
pair_results = generate_pair_metrics(btdata, stake_currency=stake_currency, pair_results = generate_pair_metrics(btdata, stake_currency=stake_currency,
max_open_trades=max_open_trades, starting_balance=starting_balance,
results=results, skip_nan=False) results=results, skip_nan=False)
sell_reason_stats = generate_sell_reason_stats(max_open_trades=max_open_trades, sell_reason_stats = generate_sell_reason_stats(max_open_trades=max_open_trades,
results=results) results=results)
left_open_results = generate_pair_metrics(btdata, stake_currency=stake_currency, left_open_results = generate_pair_metrics(btdata, stake_currency=stake_currency,
max_open_trades=max_open_trades, starting_balance=starting_balance,
results=results.loc[results['open_at_end']], results=results.loc[results['is_open']],
skip_nan=True) skip_nan=True)
daily_stats = generate_daily_stats(results) daily_stats = generate_daily_stats(results)
best_pair = max([pair for pair in pair_results if pair['key'] != 'TOTAL'], best_pair = max([pair for pair in pair_results if pair['key'] != 'TOTAL'],
@@ -273,8 +284,10 @@ def generate_backtest_stats(btdata: Dict[str, DataFrame],
'sell_reason_summary': sell_reason_stats, 'sell_reason_summary': sell_reason_stats,
'left_open_trades': left_open_results, 'left_open_trades': left_open_results,
'total_trades': len(results), 'total_trades': len(results),
'profit_mean': results['profit_percent'].mean() if len(results) > 0 else 0, 'total_volume': float(results['stake_amount'].sum()),
'profit_total': results['profit_percent'].sum(), 'avg_stake_amount': results['stake_amount'].mean() if len(results) > 0 else 0,
'profit_mean': results['profit_ratio'].mean() if len(results) > 0 else 0,
'profit_total': results['profit_abs'].sum() / starting_balance,
'profit_total_abs': results['profit_abs'].sum(), 'profit_total_abs': results['profit_abs'].sum(),
'backtest_start': min_date.datetime, 'backtest_start': min_date.datetime,
'backtest_start_ts': min_date.int_timestamp * 1000, 'backtest_start_ts': min_date.int_timestamp * 1000,
@@ -282,45 +295,76 @@ def generate_backtest_stats(btdata: Dict[str, DataFrame],
'backtest_end_ts': max_date.int_timestamp * 1000, 'backtest_end_ts': max_date.int_timestamp * 1000,
'backtest_days': backtest_days, 'backtest_days': backtest_days,
'backtest_run_start_ts': content['backtest_start_time'],
'backtest_run_end_ts': content['backtest_end_time'],
'trades_per_day': round(len(results) / backtest_days, 2) if backtest_days > 0 else 0, 'trades_per_day': round(len(results) / backtest_days, 2) if backtest_days > 0 else 0,
'market_change': market_change, 'market_change': market_change,
'pairlist': list(btdata.keys()), 'pairlist': list(btdata.keys()),
'stake_amount': config['stake_amount'], 'stake_amount': config['stake_amount'],
'stake_currency': config['stake_currency'], 'stake_currency': config['stake_currency'],
'max_open_trades': (config['max_open_trades'] 'stake_currency_decimals': decimals_per_coin(config['stake_currency']),
if config['max_open_trades'] != float('inf') else -1), 'starting_balance': starting_balance,
'dry_run_wallet': starting_balance,
'final_balance': content['final_balance'],
'max_open_trades': max_open_trades,
'max_open_trades_setting': (config['max_open_trades']
if config['max_open_trades'] != float('inf') else -1),
'timeframe': config['timeframe'], 'timeframe': config['timeframe'],
'timerange': config.get('timerange', ''),
'enable_protections': config.get('enable_protections', False),
'strategy_name': strategy,
# Parameters relevant for backtesting # Parameters relevant for backtesting
'stoploss': config['stoploss'], 'stoploss': config['stoploss'],
'trailing_stop': config.get('trailing_stop', False), 'trailing_stop': config.get('trailing_stop', False),
'trailing_stop_positive': config.get('trailing_stop_positive'), 'trailing_stop_positive': config.get('trailing_stop_positive'),
'trailing_stop_positive_offset': config.get('trailing_stop_positive_offset', 0.0), 'trailing_stop_positive_offset': config.get('trailing_stop_positive_offset', 0.0),
'trailing_only_offset_is_reached': config.get('trailing_only_offset_is_reached', False), 'trailing_only_offset_is_reached': config.get('trailing_only_offset_is_reached', False),
'use_custom_stoploss': config.get('use_custom_stoploss', False),
'minimal_roi': config['minimal_roi'], 'minimal_roi': config['minimal_roi'],
'use_sell_signal': config['ask_strategy']['use_sell_signal'], 'use_sell_signal': config['ask_strategy']['use_sell_signal'],
'sell_profit_only': config['ask_strategy']['sell_profit_only'], 'sell_profit_only': config['ask_strategy']['sell_profit_only'],
'sell_profit_offset': config['ask_strategy']['sell_profit_offset'],
'ignore_roi_if_buy_signal': config['ask_strategy']['ignore_roi_if_buy_signal'], 'ignore_roi_if_buy_signal': config['ask_strategy']['ignore_roi_if_buy_signal'],
**daily_stats, **daily_stats,
} }
result['strategy'][strategy] = strat_stats result['strategy'][strategy] = strat_stats
try: try:
max_drawdown, drawdown_start, drawdown_end = calculate_max_drawdown( max_drawdown, _, _, _, _ = calculate_max_drawdown(
results, value_col='profit_percent') results, value_col='profit_ratio')
drawdown_abs, drawdown_start, drawdown_end, high_val, low_val = calculate_max_drawdown(
results, value_col='profit_abs')
strat_stats.update({ strat_stats.update({
'max_drawdown': max_drawdown, 'max_drawdown': max_drawdown,
'max_drawdown_abs': drawdown_abs,
'drawdown_start': drawdown_start, 'drawdown_start': drawdown_start,
'drawdown_start_ts': drawdown_start.timestamp() * 1000, 'drawdown_start_ts': drawdown_start.timestamp() * 1000,
'drawdown_end': drawdown_end, 'drawdown_end': drawdown_end,
'drawdown_end_ts': drawdown_end.timestamp() * 1000, 'drawdown_end_ts': drawdown_end.timestamp() * 1000,
'max_drawdown_low': low_val,
'max_drawdown_high': high_val,
}) })
csum_min, csum_max = calculate_csum(results, starting_balance)
strat_stats.update({
'csum_min': csum_min,
'csum_max': csum_max
})
except ValueError: except ValueError:
strat_stats.update({ strat_stats.update({
'max_drawdown': 0.0, 'max_drawdown': 0.0,
'max_drawdown_abs': 0.0,
'max_drawdown_low': 0.0,
'max_drawdown_high': 0.0,
'drawdown_start': datetime(1970, 1, 1, tzinfo=timezone.utc), 'drawdown_start': datetime(1970, 1, 1, tzinfo=timezone.utc),
'drawdown_start_ts': 0, 'drawdown_start_ts': 0,
'drawdown_end': datetime(1970, 1, 1, tzinfo=timezone.utc), 'drawdown_end': datetime(1970, 1, 1, tzinfo=timezone.utc),
'drawdown_end_ts': 0, 'drawdown_end_ts': 0,
'csum_min': 0,
'csum_max': 0
}) })
strategy_results = generate_strategy_metrics(all_results=all_results) strategy_results = generate_strategy_metrics(all_results=all_results)
@@ -343,7 +387,7 @@ def text_table_bt_results(pair_results: List[Dict[str, Any]], stake_currency: st
""" """
headers = _get_line_header('Pair', stake_currency) headers = _get_line_header('Pair', stake_currency)
floatfmt = _get_line_floatfmt() floatfmt = _get_line_floatfmt(stake_currency)
output = [[ output = [[
t['key'], t['trades'], t['profit_mean_pct'], t['profit_sum_pct'], t['profit_total_abs'], t['key'], t['trades'], t['profit_mean_pct'], t['profit_sum_pct'], t['profit_total_abs'],
t['profit_total_pct'], t['duration_avg'], t['wins'], t['draws'], t['losses'] t['profit_total_pct'], t['duration_avg'], t['wins'], t['draws'], t['losses']
@@ -374,7 +418,9 @@ def text_table_sell_reason(sell_reason_stats: List[Dict[str, Any]], stake_curren
output = [[ output = [[
t['sell_reason'], t['trades'], t['wins'], t['draws'], t['losses'], t['sell_reason'], t['trades'], t['wins'], t['draws'], t['losses'],
t['profit_mean_pct'], t['profit_sum_pct'], t['profit_total_abs'], t['profit_total_pct'], t['profit_mean_pct'], t['profit_sum_pct'],
round_coin_value(t['profit_total_abs'], stake_currency, False),
t['profit_total_pct'],
] for t in sell_reason_stats] ] for t in sell_reason_stats]
return tabulate(output, headers=headers, tablefmt="orgtbl", stralign="right") return tabulate(output, headers=headers, tablefmt="orgtbl", stralign="right")
@@ -384,10 +430,10 @@ def text_table_strategy(strategy_results, stake_currency: str) -> str:
Generate summary table per strategy Generate summary table per strategy
:param stake_currency: stake-currency - used to correctly name headers :param stake_currency: stake-currency - used to correctly name headers
:param max_open_trades: Maximum allowed open trades used for backtest :param max_open_trades: Maximum allowed open trades used for backtest
:param all_results: Dict of <Strategyname: BacktestResult> containing results for all strategies :param all_results: Dict of <Strategyname: DataFrame> containing results for all strategies
:return: pretty printed table with tabulate as string :return: pretty printed table with tabulate as string
""" """
floatfmt = _get_line_floatfmt() floatfmt = _get_line_floatfmt(stake_currency)
headers = _get_line_header('Strategy', stake_currency) headers = _get_line_header('Strategy', stake_currency)
output = [[ output = [[
@@ -401,33 +447,58 @@ def text_table_strategy(strategy_results, stake_currency: str) -> str:
def text_table_add_metrics(strat_results: Dict) -> str: def text_table_add_metrics(strat_results: Dict) -> str:
if len(strat_results['trades']) > 0: if len(strat_results['trades']) > 0:
best_trade = max(strat_results['trades'], key=lambda x: x['profit_percent']) best_trade = max(strat_results['trades'], key=lambda x: x['profit_ratio'])
worst_trade = min(strat_results['trades'], key=lambda x: x['profit_percent']) worst_trade = min(strat_results['trades'], key=lambda x: x['profit_ratio'])
metrics = [ metrics = [
('Backtesting from', strat_results['backtest_start'].strftime(DATETIME_PRINT_FORMAT)), ('Backtesting from', strat_results['backtest_start'].strftime(DATETIME_PRINT_FORMAT)),
('Backtesting to', strat_results['backtest_end'].strftime(DATETIME_PRINT_FORMAT)), ('Backtesting to', strat_results['backtest_end'].strftime(DATETIME_PRINT_FORMAT)),
('Max open trades', strat_results['max_open_trades']), ('Max open trades', strat_results['max_open_trades']),
('', ''), # Empty line to improve readability ('', ''), # Empty line to improve readability
('Total trades', strat_results['total_trades']), ('Total trades', strat_results['total_trades']),
('Total Profit %', f"{round(strat_results['profit_total'] * 100, 2)}%"), ('Starting balance', round_coin_value(strat_results['starting_balance'],
strat_results['stake_currency'])),
('Final balance', round_coin_value(strat_results['final_balance'],
strat_results['stake_currency'])),
('Absolute profit ', round_coin_value(strat_results['profit_total_abs'],
strat_results['stake_currency'])),
('Total profit %', f"{round(strat_results['profit_total'] * 100, 2)}%"),
('Trades per day', strat_results['trades_per_day']), ('Trades per day', strat_results['trades_per_day']),
('Avg. stake amount', round_coin_value(strat_results['avg_stake_amount'],
strat_results['stake_currency'])),
('Total trade volume', round_coin_value(strat_results['total_volume'],
strat_results['stake_currency'])),
('', ''), # Empty line to improve readability ('', ''), # Empty line to improve readability
('Best Pair', f"{strat_results['best_pair']['key']} " ('Best Pair', f"{strat_results['best_pair']['key']} "
f"{round(strat_results['best_pair']['profit_sum_pct'], 2)}%"), f"{round(strat_results['best_pair']['profit_sum_pct'], 2)}%"),
('Worst Pair', f"{strat_results['worst_pair']['key']} " ('Worst Pair', f"{strat_results['worst_pair']['key']} "
f"{round(strat_results['worst_pair']['profit_sum_pct'], 2)}%"), f"{round(strat_results['worst_pair']['profit_sum_pct'], 2)}%"),
('Best trade', f"{best_trade['pair']} {round(best_trade['profit_percent'] * 100, 2)}%"), ('Best trade', f"{best_trade['pair']} {round(best_trade['profit_ratio'] * 100, 2)}%"),
('Worst trade', f"{worst_trade['pair']} " ('Worst trade', f"{worst_trade['pair']} "
f"{round(worst_trade['profit_percent'] * 100, 2)}%"), f"{round(worst_trade['profit_ratio'] * 100, 2)}%"),
('Best day', f"{round(strat_results['backtest_best_day'] * 100, 2)}%"), ('Best day', round_coin_value(strat_results['backtest_best_day_abs'],
('Worst day', f"{round(strat_results['backtest_worst_day'] * 100, 2)}%"), strat_results['stake_currency'])),
('Worst day', round_coin_value(strat_results['backtest_worst_day_abs'],
strat_results['stake_currency'])),
('Days win/draw/lose', f"{strat_results['winning_days']} / " ('Days win/draw/lose', f"{strat_results['winning_days']} / "
f"{strat_results['draw_days']} / {strat_results['losing_days']}"), f"{strat_results['draw_days']} / {strat_results['losing_days']}"),
('Avg. Duration Winners', f"{strat_results['winner_holding_avg']}"), ('Avg. Duration Winners', f"{strat_results['winner_holding_avg']}"),
('Avg. Duration Loser', f"{strat_results['loser_holding_avg']}"), ('Avg. Duration Loser', f"{strat_results['loser_holding_avg']}"),
('', ''), # Empty line to improve readability ('', ''), # Empty line to improve readability
('Max Drawdown', f"{round(strat_results['max_drawdown'] * 100, 2)}%"),
('Min balance', round_coin_value(strat_results['csum_min'],
strat_results['stake_currency'])),
('Max balance', round_coin_value(strat_results['csum_max'],
strat_results['stake_currency'])),
('Drawdown', f"{round(strat_results['max_drawdown'] * 100, 2)}%"),
('Drawdown', round_coin_value(strat_results['max_drawdown_abs'],
strat_results['stake_currency'])),
('Drawdown high', round_coin_value(strat_results['max_drawdown_high'],
strat_results['stake_currency'])),
('Drawdown low', round_coin_value(strat_results['max_drawdown_low'],
strat_results['stake_currency'])),
('Drawdown Start', strat_results['drawdown_start'].strftime(DATETIME_PRINT_FORMAT)), ('Drawdown Start', strat_results['drawdown_start'].strftime(DATETIME_PRINT_FORMAT)),
('Drawdown End', strat_results['drawdown_end'].strftime(DATETIME_PRINT_FORMAT)), ('Drawdown End', strat_results['drawdown_end'].strftime(DATETIME_PRINT_FORMAT)),
('Market change', f"{round(strat_results['market_change'] * 100, 2)}%"), ('Market change', f"{round(strat_results['market_change'] * 100, 2)}%"),
@@ -435,7 +506,17 @@ def text_table_add_metrics(strat_results: Dict) -> str:
return tabulate(metrics, headers=["Metric", "Value"], tablefmt="orgtbl") return tabulate(metrics, headers=["Metric", "Value"], tablefmt="orgtbl")
else: else:
return '' start_balance = round_coin_value(strat_results['starting_balance'],
strat_results['stake_currency'])
stake_amount = round_coin_value(
strat_results['stake_amount'], strat_results['stake_currency']
) if strat_results['stake_amount'] != UNLIMITED_STAKE_AMOUNT else 'unlimited'
message = ("No trades made. "
f"Your starting balance was {start_balance}, "
f"and your stake was {stake_amount}."
)
return message
def show_backtest_results(config: Dict, backtest_stats: Dict): def show_backtest_results(config: Dict, backtest_stats: Dict):

View File

@@ -1,4 +1,5 @@
# flake8: noqa: F401 # flake8: noqa: F401
from freqtrade.persistence.models import Order, Trade, clean_dry_run_db, cleanup_db, init_db from freqtrade.persistence.models import (LocalTrade, Order, Trade, clean_dry_run_db, cleanup_db,
init_db)
from freqtrade.persistence.pairlock_middleware import PairLocks from freqtrade.persistence.pairlock_middleware import PairLocks

View File

@@ -141,7 +141,7 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
inspector = inspect(engine) inspector = inspect(engine)
cols = inspector.get_columns('trades') cols = inspector.get_columns('trades')
if 'orders' not in previous_tables: if 'orders' not in previous_tables and 'trades' in previous_tables:
logger.info('Moving open orders to Orders table.') logger.info('Moving open orders to Orders table.')
migrate_open_orders_to_trades(engine) migrate_open_orders_to_trades(engine)
else: else:

View File

@@ -171,6 +171,10 @@ class Order(_DECL_BASE):
""" """
Get all non-closed orders - useful when trying to batch-update orders Get all non-closed orders - useful when trying to batch-update orders
""" """
if not isinstance(order, dict):
logger.warning(f"{order} is not a valid response object.")
return
filtered_orders = [o for o in orders if o.order_id == order.get('id')] filtered_orders = [o for o in orders if o.order_id == order.get('id')]
if filtered_orders: if filtered_orders:
oobj = filtered_orders[0] oobj = filtered_orders[0]
@@ -195,67 +199,69 @@ class Order(_DECL_BASE):
return Order.query.filter(Order.ft_is_open.is_(True)).all() return Order.query.filter(Order.ft_is_open.is_(True)).all()
class Trade(_DECL_BASE): class LocalTrade():
""" """
Trade database model. Trade database model.
Also handles updating and querying trades Used in backtesting - must be aligned to Trade model!
""" """
__tablename__ = 'trades' use_db: bool = False
use_db: bool = True
# Trades container for backtesting # Trades container for backtesting
trades: List['Trade'] = [] trades: List['LocalTrade'] = []
trades_open: List['LocalTrade'] = []
total_profit: float = 0
id = Column(Integer, primary_key=True) id: int = 0
orders = relationship("Order", order_by="Order.id", cascade="all, delete-orphan") orders: List[Order] = []
exchange = Column(String, nullable=False) exchange: str = ''
pair = Column(String, nullable=False, index=True) pair: str = ''
is_open = Column(Boolean, nullable=False, default=True, index=True) is_open: bool = True
fee_open = Column(Float, nullable=False, default=0.0) fee_open: float = 0.0
fee_open_cost = Column(Float, nullable=True) fee_open_cost: Optional[float] = None
fee_open_currency = Column(String, nullable=True) fee_open_currency: str = ''
fee_close = Column(Float, nullable=False, default=0.0) fee_close: float = 0.0
fee_close_cost = Column(Float, nullable=True) fee_close_cost: Optional[float] = None
fee_close_currency = Column(String, nullable=True) fee_close_currency: str = ''
open_rate = Column(Float) open_rate: float = 0.0
open_rate_requested = Column(Float) open_rate_requested: Optional[float] = None
# open_trade_value - calculated via _calc_open_trade_value # open_trade_value - calculated via _calc_open_trade_value
open_trade_value = Column(Float) open_trade_value: float = 0.0
close_rate = Column(Float) close_rate: Optional[float] = None
close_rate_requested = Column(Float) close_rate_requested: Optional[float] = None
close_profit = Column(Float) close_profit: Optional[float] = None
close_profit_abs = Column(Float) close_profit_abs: Optional[float] = None
stake_amount = Column(Float, nullable=False) stake_amount: float = 0.0
amount = Column(Float) amount: float = 0.0
amount_requested = Column(Float) amount_requested: Optional[float] = None
open_date = Column(DateTime, nullable=False, default=datetime.utcnow) open_date: datetime
close_date = Column(DateTime) close_date: Optional[datetime] = None
open_order_id = Column(String) open_order_id: Optional[str] = None
# absolute value of the stop loss # absolute value of the stop loss
stop_loss = Column(Float, nullable=True, default=0.0) stop_loss: float = 0.0
# percentage value of the stop loss # percentage value of the stop loss
stop_loss_pct = Column(Float, nullable=True) stop_loss_pct: float = 0.0
# absolute value of the initial stop loss # absolute value of the initial stop loss
initial_stop_loss = Column(Float, nullable=True, default=0.0) initial_stop_loss: float = 0.0
# percentage value of the initial stop loss # percentage value of the initial stop loss
initial_stop_loss_pct = Column(Float, nullable=True) initial_stop_loss_pct: float = 0.0
# stoploss order id which is on exchange # stoploss order id which is on exchange
stoploss_order_id = Column(String, nullable=True, index=True) stoploss_order_id: Optional[str] = None
# last update time of the stoploss order on exchange # last update time of the stoploss order on exchange
stoploss_last_update = Column(DateTime, nullable=True) stoploss_last_update: Optional[datetime] = None
# absolute value of the highest reached price # absolute value of the highest reached price
max_rate = Column(Float, nullable=True, default=0.0) max_rate: float = 0.0
# Lowest price reached # Lowest price reached
min_rate = Column(Float, nullable=True) min_rate: float = 0.0
sell_reason = Column(String, nullable=True) sell_reason: str = ''
sell_order_status = Column(String, nullable=True) sell_order_status: str = ''
strategy = Column(String, nullable=True) strategy: str = ''
timeframe = Column(Integer, nullable=True) timeframe: Optional[int] = None
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) for key in kwargs:
setattr(self, key, kwargs[key])
self.recalc_open_trade_value() self.recalc_open_trade_value()
def __repr__(self): def __repr__(self):
@@ -264,6 +270,14 @@ class Trade(_DECL_BASE):
return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, ' return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, '
f'open_rate={self.open_rate:.8f}, open_since={open_since})') f'open_rate={self.open_rate:.8f}, open_since={open_since})')
@property
def open_date_utc(self):
return self.open_date.replace(tzinfo=timezone.utc)
@property
def close_date_utc(self):
return self.close_date.replace(tzinfo=timezone.utc)
def to_json(self) -> Dict[str, Any]: def to_json(self) -> Dict[str, Any]:
return { return {
'trade_id': self.id, 'trade_id': self.id,
@@ -302,6 +316,11 @@ class Trade(_DECL_BASE):
'close_profit_pct': round(self.close_profit * 100, 2) if self.close_profit else None, 'close_profit_pct': round(self.close_profit * 100, 2) if self.close_profit else None,
'close_profit_abs': self.close_profit_abs, # Deprecated 'close_profit_abs': self.close_profit_abs, # Deprecated
'trade_duration_s': (int((self.close_date_utc - self.open_date_utc).total_seconds())
if self.close_date else None),
'trade_duration': (int((self.close_date_utc - self.open_date_utc).total_seconds() // 60)
if self.close_date else None),
'profit_ratio': self.close_profit, 'profit_ratio': self.close_profit,
'profit_pct': round(self.close_profit * 100, 2) if self.close_profit else None, 'profit_pct': round(self.close_profit * 100, 2) if self.close_profit else None,
'profit_abs': self.close_profit_abs, 'profit_abs': self.close_profit_abs,
@@ -332,8 +351,9 @@ class Trade(_DECL_BASE):
""" """
Resets all trades. Only active for backtesting mode. Resets all trades. Only active for backtesting mode.
""" """
if not Trade.use_db: LocalTrade.trades = []
Trade.trades = [] LocalTrade.trades_open = []
LocalTrade.total_profit = 0
def adjust_min_max_rates(self, current_price: float) -> None: def adjust_min_max_rates(self, current_price: float) -> None:
""" """
@@ -342,6 +362,12 @@ class Trade(_DECL_BASE):
self.max_rate = max(current_price, self.max_rate or self.open_rate) self.max_rate = max(current_price, self.max_rate or self.open_rate)
self.min_rate = min(current_price, self.min_rate or self.open_rate) self.min_rate = min(current_price, self.min_rate or self.open_rate)
def _set_new_stoploss(self, new_loss: float, stoploss: float):
"""Assign new stop value"""
self.stop_loss = new_loss
self.stop_loss_pct = -1 * abs(stoploss)
self.stoploss_last_update = datetime.utcnow()
def adjust_stop_loss(self, current_price: float, stoploss: float, def adjust_stop_loss(self, current_price: float, stoploss: float,
initial: bool = False) -> None: initial: bool = False) -> None:
""" """
@@ -360,19 +386,15 @@ class Trade(_DECL_BASE):
# no stop loss assigned yet # no stop loss assigned yet
if not self.stop_loss: if not self.stop_loss:
logger.debug(f"{self.pair} - Assigning new stoploss...") logger.debug(f"{self.pair} - Assigning new stoploss...")
self.stop_loss = new_loss self._set_new_stoploss(new_loss, stoploss)
self.stop_loss_pct = -1 * abs(stoploss)
self.initial_stop_loss = new_loss self.initial_stop_loss = new_loss
self.initial_stop_loss_pct = -1 * abs(stoploss) self.initial_stop_loss_pct = -1 * abs(stoploss)
self.stoploss_last_update = datetime.utcnow()
# evaluate if the stop loss needs to be updated # evaluate if the stop loss needs to be updated
else: else:
if new_loss > self.stop_loss: # stop losses only walk up, never down! if new_loss > self.stop_loss: # stop losses only walk up, never down!
logger.debug(f"{self.pair} - Adjusting stoploss...") logger.debug(f"{self.pair} - Adjusting stoploss...")
self.stop_loss = new_loss self._set_new_stoploss(new_loss, stoploss)
self.stop_loss_pct = -1 * abs(stoploss)
self.stoploss_last_update = datetime.utcnow()
else: else:
logger.debug(f"{self.pair} - Keeping current stoploss...") logger.debug(f"{self.pair} - Keeping current stoploss...")
@@ -399,8 +421,8 @@ class Trade(_DECL_BASE):
if order_type in ('market', 'limit') and order['side'] == 'buy': if order_type in ('market', 'limit') and order['side'] == 'buy':
# Update open rate and actual amount # Update open rate and actual amount
self.open_rate = Decimal(safe_value_fallback(order, 'average', 'price')) self.open_rate = float(safe_value_fallback(order, 'average', 'price'))
self.amount = Decimal(safe_value_fallback(order, 'filled', 'amount')) self.amount = float(safe_value_fallback(order, 'filled', 'amount'))
self.recalc_open_trade_value() self.recalc_open_trade_value()
if self.is_open: if self.is_open:
logger.info(f'{order_type.upper()}_BUY has been fulfilled for {self}.') logger.info(f'{order_type.upper()}_BUY has been fulfilled for {self}.')
@@ -414,7 +436,7 @@ class Trade(_DECL_BASE):
self.close_rate_requested = self.stop_loss self.close_rate_requested = self.stop_loss
if self.is_open: if self.is_open:
logger.info(f'{order_type.upper()} is hit for {self}.') logger.info(f'{order_type.upper()} is hit for {self}.')
self.close(order['average']) self.close(safe_value_fallback(order, 'average', 'price'))
else: else:
raise ValueError(f'Unknown order type: {order_type}') raise ValueError(f'Unknown order type: {order_type}')
cleanup_db() cleanup_db()
@@ -424,7 +446,7 @@ class Trade(_DECL_BASE):
Sets close_rate to the given rate, calculates total profit Sets close_rate to the given rate, calculates total profit
and marks trade as closed and marks trade as closed
""" """
self.close_rate = Decimal(rate) self.close_rate = rate
self.close_profit = self.calc_profit_ratio() self.close_profit = self.calc_profit_ratio()
self.close_profit_abs = self.calc_profit() self.close_profit_abs = self.calc_profit()
self.close_date = self.close_date or datetime.utcnow() self.close_date = self.close_date or datetime.utcnow()
@@ -469,14 +491,6 @@ class Trade(_DECL_BASE):
def update_order(self, order: Dict) -> None: def update_order(self, order: Dict) -> None:
Order.update_orders(self.orders, order) Order.update_orders(self.orders, order)
def delete(self) -> None:
for order in self.orders:
Order.session.delete(order)
Trade.session.delete(self)
Trade.session.flush()
def _calc_open_trade_value(self) -> float: def _calc_open_trade_value(self) -> float:
""" """
Calculate the open_rate including open_fee. Calculate the open_rate including open_fee.
@@ -506,7 +520,7 @@ class Trade(_DECL_BASE):
if rate is None and not self.close_rate: if rate is None and not self.close_rate:
return 0.0 return 0.0
sell_trade = Decimal(self.amount) * Decimal(rate or self.close_rate) sell_trade = Decimal(self.amount) * Decimal(rate or self.close_rate) # type: ignore
fees = sell_trade * Decimal(fee or self.fee_close) fees = sell_trade * Decimal(fee or self.fee_close)
return float(sell_trade - fees) return float(sell_trade - fees)
@@ -578,7 +592,7 @@ class Trade(_DECL_BASE):
@staticmethod @staticmethod
def get_trades_proxy(*, pair: str = None, is_open: bool = None, def get_trades_proxy(*, pair: str = None, is_open: bool = None,
open_date: datetime = None, close_date: datetime = None, open_date: datetime = None, close_date: datetime = None,
) -> List['Trade']: ) -> List['LocalTrade']:
""" """
Helper function to query Trades. Helper function to query Trades.
Returns a List of trades, filtered on the parameters given. Returns a List of trades, filtered on the parameters given.
@@ -587,30 +601,40 @@ class Trade(_DECL_BASE):
:return: unsorted List[Trade] :return: unsorted List[Trade]
""" """
if Trade.use_db:
trade_filter = [] # Offline mode - without database
if pair: if is_open is not None:
trade_filter.append(Trade.pair == pair) if is_open:
if open_date: sel_trades = LocalTrade.trades_open
trade_filter.append(Trade.open_date > open_date) else:
if close_date: sel_trades = LocalTrade.trades
trade_filter.append(Trade.close_date > close_date)
if is_open is not None:
trade_filter.append(Trade.is_open.is_(is_open))
return Trade.get_trades(trade_filter).all()
else: else:
# Offline mode - without database # Not used during backtesting, but might be used by a strategy
sel_trades = [trade for trade in Trade.trades] sel_trades = [trade for trade in LocalTrade.trades + LocalTrade.trades_open]
if pair:
sel_trades = [trade for trade in sel_trades if trade.pair == pair] if pair:
if open_date: sel_trades = [trade for trade in sel_trades if trade.pair == pair]
sel_trades = [trade for trade in sel_trades if trade.open_date > open_date] if open_date:
if close_date: sel_trades = [trade for trade in sel_trades if trade.open_date > open_date]
sel_trades = [trade for trade in sel_trades if trade.close_date if close_date:
and trade.close_date > close_date] sel_trades = [trade for trade in sel_trades if trade.close_date
if is_open is not None: and trade.close_date > close_date]
sel_trades = [trade for trade in sel_trades if trade.is_open == is_open]
return sel_trades return sel_trades
@staticmethod
def close_bt_trade(trade):
LocalTrade.trades_open.remove(trade)
LocalTrade.trades.append(trade)
LocalTrade.total_profit += trade.close_profit_abs
@staticmethod
def add_bt_trade(trade):
if trade.is_open:
LocalTrade.trades_open.append(trade)
else:
LocalTrade.trades.append(trade)
@staticmethod @staticmethod
def get_open_trades() -> List[Any]: def get_open_trades() -> List[Any]:
@@ -652,9 +676,12 @@ class Trade(_DECL_BASE):
Calculates total invested amount in open trades Calculates total invested amount in open trades
in stake currency in stake currency
""" """
total_open_stake_amount = Trade.session.query(func.sum(Trade.stake_amount))\ if Trade.use_db:
.filter(Trade.is_open.is_(True))\ total_open_stake_amount = Trade.session.query(
.scalar() func.sum(Trade.stake_amount)).filter(Trade.is_open.is_(True)).scalar()
else:
total_open_stake_amount = sum(
t.stake_amount for t in Trade.get_trades_proxy(is_open=True))
return total_open_stake_amount or 0 return total_open_stake_amount or 0
@staticmethod @staticmethod
@@ -712,6 +739,108 @@ class Trade(_DECL_BASE):
logger.info(f"New stoploss: {trade.stop_loss}.") logger.info(f"New stoploss: {trade.stop_loss}.")
class Trade(_DECL_BASE, LocalTrade):
"""
Trade database model.
Also handles updating and querying trades
Note: Fields must be aligned with LocalTrade class
"""
__tablename__ = 'trades'
use_db: bool = True
id = Column(Integer, primary_key=True)
orders = relationship("Order", order_by="Order.id", cascade="all, delete-orphan")
exchange = Column(String, nullable=False)
pair = Column(String, nullable=False, index=True)
is_open = Column(Boolean, nullable=False, default=True, index=True)
fee_open = Column(Float, nullable=False, default=0.0)
fee_open_cost = Column(Float, nullable=True)
fee_open_currency = Column(String, nullable=True)
fee_close = Column(Float, nullable=False, default=0.0)
fee_close_cost = Column(Float, nullable=True)
fee_close_currency = Column(String, nullable=True)
open_rate = Column(Float)
open_rate_requested = Column(Float)
# open_trade_value - calculated via _calc_open_trade_value
open_trade_value = Column(Float)
close_rate = Column(Float)
close_rate_requested = Column(Float)
close_profit = Column(Float)
close_profit_abs = Column(Float)
stake_amount = Column(Float, nullable=False)
amount = Column(Float)
amount_requested = Column(Float)
open_date = Column(DateTime, nullable=False, default=datetime.utcnow)
close_date = Column(DateTime)
open_order_id = Column(String)
# absolute value of the stop loss
stop_loss = Column(Float, nullable=True, default=0.0)
# percentage value of the stop loss
stop_loss_pct = Column(Float, nullable=True)
# absolute value of the initial stop loss
initial_stop_loss = Column(Float, nullable=True, default=0.0)
# percentage value of the initial stop loss
initial_stop_loss_pct = Column(Float, nullable=True)
# stoploss order id which is on exchange
stoploss_order_id = Column(String, nullable=True, index=True)
# last update time of the stoploss order on exchange
stoploss_last_update = Column(DateTime, nullable=True)
# absolute value of the highest reached price
max_rate = Column(Float, nullable=True, default=0.0)
# Lowest price reached
min_rate = Column(Float, nullable=True)
sell_reason = Column(String, nullable=True)
sell_order_status = Column(String, nullable=True)
strategy = Column(String, nullable=True)
timeframe = Column(Integer, nullable=True)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.recalc_open_trade_value()
def delete(self) -> None:
for order in self.orders:
Order.session.delete(order)
Trade.session.delete(self)
Trade.session.flush()
@staticmethod
def get_trades_proxy(*, pair: str = None, is_open: bool = None,
open_date: datetime = None, close_date: datetime = None,
) -> List['LocalTrade']:
"""
Helper function to query Trades.
Returns a List of trades, filtered on the parameters given.
In live mode, converts the filter to a database query and returns all rows
In Backtest mode, uses filters on Trade.trades to get the result.
:return: unsorted List[Trade]
"""
if Trade.use_db:
trade_filter = []
if pair:
trade_filter.append(Trade.pair == pair)
if open_date:
trade_filter.append(Trade.open_date > open_date)
if close_date:
trade_filter.append(Trade.close_date > close_date)
if is_open is not None:
trade_filter.append(Trade.is_open.is_(is_open))
return Trade.get_trades(trade_filter).all()
else:
return LocalTrade.get_trades_proxy(
pair=pair, is_open=is_open,
open_date=open_date,
close_date=close_date
)
class PairLock(_DECL_BASE): class PairLock(_DECL_BASE):
""" """
Pair Locks database model. Pair Locks database model.
@@ -754,6 +883,7 @@ class PairLock(_DECL_BASE):
def to_json(self) -> Dict[str, Any]: def to_json(self) -> Dict[str, Any]:
return { return {
'id': self.id,
'pair': self.pair, 'pair': self.pair,
'lock_time': self.lock_time.strftime(DATETIME_PRINT_FORMAT), 'lock_time': self.lock_time.strftime(DATETIME_PRINT_FORMAT),
'lock_timestamp': int(self.lock_time.replace(tzinfo=timezone.utc).timestamp() * 1000), 'lock_timestamp': int(self.lock_time.replace(tzinfo=timezone.utc).timestamp() * 1000),

View File

@@ -123,3 +123,11 @@ class PairLocks():
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
return len(PairLocks.get_pair_locks(pair, now)) > 0 or PairLocks.is_global_lock(now) return len(PairLocks.get_pair_locks(pair, now)) > 0 or PairLocks.is_global_lock(now)
@staticmethod
def get_all_locks() -> List[PairLock]:
if PairLocks.use_db:
return PairLock.query.all()
else:
return PairLocks.locks

View File

@@ -13,6 +13,7 @@ from freqtrade.data.history import get_timerange, load_data
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_prev_date, timeframe_to_seconds from freqtrade.exchange import timeframe_to_prev_date, timeframe_to_seconds
from freqtrade.misc import pair_to_filename from freqtrade.misc import pair_to_filename
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.resolvers import ExchangeResolver, StrategyResolver from freqtrade.resolvers import ExchangeResolver, StrategyResolver
from freqtrade.strategy import IStrategy from freqtrade.strategy import IStrategy
@@ -29,16 +30,16 @@ except ImportError:
exit(1) exit(1)
def init_plotscript(config, startup_candles: int = 0): def init_plotscript(config, markets: List, startup_candles: int = 0):
""" """
Initialize objects needed for plotting Initialize objects needed for plotting
:return: Dict with candle (OHLCV) data, trades and pairs :return: Dict with candle (OHLCV) data, trades and pairs
""" """
if "pairs" in config: if "pairs" in config:
pairs = config['pairs'] pairs = expand_pairlist(config['pairs'], markets)
else: else:
pairs = config['exchange']['pair_whitelist'] pairs = expand_pairlist(config['exchange']['pair_whitelist'], markets)
# Set timerange to use # Set timerange to use
timerange = TimeRange.parse_timerange(config.get('timerange')) timerange = TimeRange.parse_timerange(config.get('timerange'))
@@ -52,7 +53,7 @@ def init_plotscript(config, startup_candles: int = 0):
data_format=config.get('dataformat_ohlcv', 'json'), data_format=config.get('dataformat_ohlcv', 'json'),
) )
if startup_candles: if startup_candles and data:
min_date, max_date = get_timerange(data) min_date, max_date = get_timerange(data)
logger.info(f"Loading data from {min_date} to {max_date}") logger.info(f"Loading data from {min_date} to {max_date}")
timerange.adjust_start_if_necessary(timeframe_to_seconds(config.get('timeframe', '5m')), timerange.adjust_start_if_necessary(timeframe_to_seconds(config.get('timeframe', '5m')),
@@ -66,14 +67,16 @@ def init_plotscript(config, startup_candles: int = 0):
if not filename.is_dir() and not filename.is_file(): if not filename.is_dir() and not filename.is_file():
logger.warning("Backtest file is missing skipping trades.") logger.warning("Backtest file is missing skipping trades.")
no_trades = True no_trades = True
try:
trades = load_trades( trades = load_trades(
config['trade_source'], config['trade_source'],
db_url=config.get('db_url'), db_url=config.get('db_url'),
exportfilename=filename, exportfilename=filename,
no_trades=no_trades, no_trades=no_trades,
strategy=config.get('strategy'), strategy=config.get('strategy'),
) )
except ValueError as e:
raise OperationalException(e) from e
trades = trim_dataframe(trades, timerange, 'open_date') trades = trim_dataframe(trades, timerange, 'open_date')
return {"ohlcv": data, return {"ohlcv": data,
@@ -142,7 +145,7 @@ def add_max_drawdown(fig, row, trades: pd.DataFrame, df_comb: pd.DataFrame,
Add scatter points indicating max drawdown Add scatter points indicating max drawdown
""" """
try: try:
max_drawdown, highdate, lowdate = calculate_max_drawdown(trades) max_drawdown, highdate, lowdate, _, _ = calculate_max_drawdown(trades)
drawdown = go.Scatter( drawdown = go.Scatter(
x=[highdate, lowdate], x=[highdate, lowdate],
@@ -174,10 +177,10 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
# Trades can be empty # Trades can be empty
if trades is not None and len(trades) > 0: if trades is not None and len(trades) > 0:
# Create description for sell summarizing the trade # Create description for sell summarizing the trade
trades['desc'] = trades.apply(lambda row: f"{round(row['profit_percent'] * 100, 1)}%, " trades['desc'] = trades.apply(lambda row: f"{round(row['profit_ratio'] * 100, 1)}%, "
f"{row['sell_reason']}, " f"{row['sell_reason']}, "
f"{row['trade_duration']} min", f"{row['trade_duration']} min",
axis=1) axis=1)
trade_buys = go.Scatter( trade_buys = go.Scatter(
x=trades["open_date"], x=trades["open_date"],
y=trades["open_rate"], y=trades["open_rate"],
@@ -194,9 +197,9 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
) )
trade_sells = go.Scatter( trade_sells = go.Scatter(
x=trades.loc[trades['profit_percent'] > 0, "close_date"], x=trades.loc[trades['profit_ratio'] > 0, "close_date"],
y=trades.loc[trades['profit_percent'] > 0, "close_rate"], y=trades.loc[trades['profit_ratio'] > 0, "close_rate"],
text=trades.loc[trades['profit_percent'] > 0, "desc"], text=trades.loc[trades['profit_ratio'] > 0, "desc"],
mode='markers', mode='markers',
name='Sell - Profit', name='Sell - Profit',
marker=dict( marker=dict(
@@ -207,9 +210,9 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
) )
) )
trade_sells_loss = go.Scatter( trade_sells_loss = go.Scatter(
x=trades.loc[trades['profit_percent'] <= 0, "close_date"], x=trades.loc[trades['profit_ratio'] <= 0, "close_date"],
y=trades.loc[trades['profit_percent'] <= 0, "close_rate"], y=trades.loc[trades['profit_ratio'] <= 0, "close_rate"],
text=trades.loc[trades['profit_percent'] <= 0, "desc"], text=trades.loc[trades['profit_ratio'] <= 0, "desc"],
mode='markers', mode='markers',
name='Sell - Loss', name='Sell - Loss',
marker=dict( marker=dict(
@@ -444,6 +447,8 @@ def generate_profit_graph(pairs: str, data: Dict[str, pd.DataFrame],
# Trim trades to available OHLCV data # Trim trades to available OHLCV data
trades = extract_trades_of_period(df_comb, trades, date_index=True) trades = extract_trades_of_period(df_comb, trades, date_index=True)
if len(trades) == 0:
raise OperationalException('No trades found in selected timerange.')
# Add combined cumulative profit # Add combined cumulative profit
df_comb = create_cum_profit(df_comb, trades, 'cum_profit', timeframe) df_comb = create_cum_profit(df_comb, trades, 'cum_profit', timeframe)
@@ -525,7 +530,7 @@ def load_and_plot_trades(config: Dict[str, Any]):
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config) exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config)
IStrategy.dp = DataProvider(config, exchange) IStrategy.dp = DataProvider(config, exchange)
plot_elements = init_plotscript(config, strategy.startup_candle_count) plot_elements = init_plotscript(config, list(exchange.markets), strategy.startup_candle_count)
timerange = plot_elements['timerange'] timerange = plot_elements['timerange']
trades = plot_elements['trades'] trades = plot_elements['trades']
pair_counter = 0 pair_counter = 0
@@ -560,7 +565,8 @@ def plot_profit(config: Dict[str, Any]) -> None:
But should be somewhat proportional, and therefor useful But should be somewhat proportional, and therefor useful
in helping out to find a good algorithm. in helping out to find a good algorithm.
""" """
plot_elements = init_plotscript(config) exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config)
plot_elements = init_plotscript(config, list(exchange.markets))
trades = plot_elements['trades'] trades = plot_elements['trades']
# Filter trades to relevant pairs # Filter trades to relevant pairs
# Remove open pairs - we don't know the profit yet so can't calculate profit for these. # Remove open pairs - we don't know the profit yet so can't calculate profit for these.

View File

@@ -30,10 +30,10 @@ class AgeFilter(IPairList):
if self._min_days_listed < 1: if self._min_days_listed < 1:
raise OperationalException("AgeFilter requires min_days_listed to be >= 1") raise OperationalException("AgeFilter requires min_days_listed to be >= 1")
if self._min_days_listed > exchange.ohlcv_candle_limit: if self._min_days_listed > exchange.ohlcv_candle_limit('1d'):
raise OperationalException("AgeFilter requires min_days_listed to not exceed " raise OperationalException("AgeFilter requires min_days_listed to not exceed "
"exchange max request size " "exchange max request size "
f"({exchange.ohlcv_candle_limit})") f"({exchange.ohlcv_candle_limit('1d')})")
@property @property
def needstickers(self) -> bool: def needstickers(self) -> bool:

View File

@@ -124,10 +124,21 @@ class IPairList(LoggingMixin, ABC):
""" """
return self._pairlistmanager.verify_blacklist(pairlist, logmethod) return self._pairlistmanager.verify_blacklist(pairlist, logmethod)
def verify_whitelist(self, pairlist: List[str], logmethod,
keep_invalid: bool = False) -> List[str]:
"""
Proxy method to verify_whitelist for easy access for child classes.
:param pairlist: Pairlist to validate
:param logmethod: Function that'll be called, `logger.info` or `logger.warning`
:param keep_invalid: If sets to True, drops invalid pairs silently while expanding regexes.
:return: pairlist - whitelisted pairs
"""
return self._pairlistmanager.verify_whitelist(pairlist, logmethod, keep_invalid)
def _whitelist_for_active_markets(self, pairlist: List[str]) -> List[str]: def _whitelist_for_active_markets(self, pairlist: List[str]) -> List[str]:
""" """
Check available markets and remove pair from whitelist if necessary Check available markets and remove pair from whitelist if necessary
:param whitelist: the sorted list of pairs the user might want to trade :param pairlist: the sorted list of pairs the user might want to trade
:return: the list of pairs the user wants to trade without those unavailable or :return: the list of pairs the user wants to trade without those unavailable or
black_listed black_listed
""" """
@@ -157,7 +168,7 @@ class IPairList(LoggingMixin, ABC):
# Check if market is active # Check if market is active
market = markets[pair] market = markets[pair]
if not market_is_active(market): if not market_is_active(market):
logger.info(f"Ignoring {pair} from whitelist. Market is not active.") self.log_once(f"Ignoring {pair} from whitelist. Market is not active.", logger.info)
continue continue
if pair not in sanitized_whitelist: if pair not in sanitized_whitelist:
sanitized_whitelist.append(pair) sanitized_whitelist.append(pair)

View File

@@ -64,7 +64,7 @@ class PriceFilter(IPairList):
:param ticker: ticker dict as returned from ccxt.load_markets() :param ticker: ticker dict as returned from ccxt.load_markets()
:return: True if the pair can stay, false if it should be removed :return: True if the pair can stay, false if it should be removed
""" """
if ticker['last'] is None or ticker['last'] == 0: if ticker.get('last', None) is None or ticker.get('last') == 0:
self.log_once(f"Removed {pair} from whitelist, because " self.log_once(f"Removed {pair} from whitelist, because "
"ticker['last'] is empty (Usually no trade in the last 24h).", "ticker['last'] is empty (Usually no trade in the last 24h).",
logger.info) logger.info)

View File

@@ -43,7 +43,7 @@ class SpreadFilter(IPairList):
:param ticker: ticker dict as returned from ccxt.load_markets() :param ticker: ticker dict as returned from ccxt.load_markets()
:return: True if the pair can stay, false if it should be removed :return: True if the pair can stay, false if it should be removed
""" """
if 'bid' in ticker and 'ask' in ticker: if 'bid' in ticker and 'ask' in ticker and ticker['ask']:
spread = 1 - ticker['bid'] / ticker['ask'] spread = 1 - ticker['bid'] / ticker['ask']
if spread > self._max_spread_ratio: if spread > self._max_spread_ratio:
self.log_once(f"Removed {pair} from whitelist, because spread " self.log_once(f"Removed {pair} from whitelist, because spread "
@@ -52,4 +52,6 @@ class SpreadFilter(IPairList):
return False return False
else: else:
return True return True
self.log_once(f"Removed {pair} from whitelist due to invalid ticker data: {ticker}",
logger.info)
return False return False

View File

@@ -50,9 +50,12 @@ class StaticPairList(IPairList):
:return: List of pairs :return: List of pairs
""" """
if self._allow_inactive: if self._allow_inactive:
return self._config['exchange']['pair_whitelist'] return self.verify_whitelist(
self._config['exchange']['pair_whitelist'], logger.info, keep_invalid=True
)
else: else:
return self._whitelist_for_active_markets(self._config['exchange']['pair_whitelist']) return self._whitelist_for_active_markets(
self.verify_whitelist(self._config['exchange']['pair_whitelist'], logger.info))
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
""" """

View File

@@ -0,0 +1,42 @@
import re
from typing import List
def expand_pairlist(wildcardpl: List[str], available_pairs: List[str],
keep_invalid: bool = False) -> List[str]:
"""
Expand pairlist potentially containing wildcards based on available markets.
This will implicitly filter all pairs in the wildcard-list which are not in available_pairs.
:param wildcardpl: List of Pairlists, which may contain regex
:param available_pairs: List of all available pairs (`exchange.get_markets().keys()`)
:param keep_invalid: If sets to True, drops invalid pairs silently while expanding regexes
:return expanded pairlist, with Regexes from wildcardpl applied to match all available pairs.
:raises: ValueError if a wildcard is invalid (like '*/BTC' - which should be `.*/BTC`)
"""
result = []
if keep_invalid:
for pair_wc in wildcardpl:
try:
comp = re.compile(pair_wc)
result_partial = [
pair for pair in available_pairs if re.fullmatch(comp, pair)
]
# Add all matching pairs.
# If there are no matching pairs (Pair not on exchange) keep it.
result += result_partial or [pair_wc]
except re.error as err:
raise ValueError(f"Wildcard error in {pair_wc}, {err}")
for element in result:
if not re.fullmatch(r'^[A-Za-z0-9/-]+$', element):
result.remove(element)
else:
for pair_wc in wildcardpl:
try:
comp = re.compile(pair_wc)
result += [
pair for pair in available_pairs if re.fullmatch(comp, pair)
]
except re.error as err:
raise ValueError(f"Wildcard error in {pair_wc}, {err}")
return result

View File

@@ -28,14 +28,14 @@ class RangeStabilityFilter(IPairList):
self._min_rate_of_change = pairlistconfig.get('min_rate_of_change', 0.01) self._min_rate_of_change = pairlistconfig.get('min_rate_of_change', 0.01)
self._refresh_period = pairlistconfig.get('refresh_period', 1440) self._refresh_period = pairlistconfig.get('refresh_period', 1440)
self._pair_cache: TTLCache = TTLCache(maxsize=100, ttl=self._refresh_period) self._pair_cache: TTLCache = TTLCache(maxsize=1000, ttl=self._refresh_period)
if self._days < 1: if self._days < 1:
raise OperationalException("RangeStabilityFilter requires lookback_days to be >= 1") raise OperationalException("RangeStabilityFilter requires lookback_days to be >= 1")
if self._days > exchange.ohlcv_candle_limit: if self._days > exchange.ohlcv_candle_limit('1d'):
raise OperationalException("RangeStabilityFilter requires lookback_days to not " raise OperationalException("RangeStabilityFilter requires lookback_days to not "
"exceed exchange max request size " "exceed exchange max request size "
f"({exchange.ohlcv_candle_limit})") f"({exchange.ohlcv_candle_limit('1d')})")
@property @property
def needstickers(self) -> bool: def needstickers(self) -> bool:

View File

@@ -10,6 +10,7 @@ from cachetools import TTLCache, cached
from freqtrade.constants import ListPairsWithTimeframes from freqtrade.constants import ListPairsWithTimeframes
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.plugins.pairlist.IPairList import IPairList from freqtrade.plugins.pairlist.IPairList import IPairList
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.resolvers import PairListResolver from freqtrade.resolvers import PairListResolver
@@ -42,30 +43,29 @@ class PairListManager():
@property @property
def whitelist(self) -> List[str]: def whitelist(self) -> List[str]:
""" """The current whitelist"""
Has the current whitelist
"""
return self._whitelist return self._whitelist
@property @property
def blacklist(self) -> List[str]: def blacklist(self) -> List[str]:
""" """
Has the current blacklist The current blacklist
-> no need to overwrite in subclasses -> no need to overwrite in subclasses
""" """
return self._blacklist return self._blacklist
@property
def expanded_blacklist(self) -> List[str]:
"""The expanded blacklist (including wildcard expansion)"""
return expand_pairlist(self._blacklist, self._exchange.get_markets().keys())
@property @property
def name_list(self) -> List[str]: def name_list(self) -> List[str]:
""" """Get list of loaded Pairlist Handler names"""
Get list of loaded Pairlist Handler names
"""
return [p.name for p in self._pairlist_handlers] return [p.name for p in self._pairlist_handlers]
def short_desc(self) -> List[Dict]: def short_desc(self) -> List[Dict]:
""" """List of short_desc for each Pairlist Handler"""
List of short_desc for each Pairlist Handler
"""
return [{p.name: p.short_desc()} for p in self._pairlist_handlers] return [{p.name: p.short_desc()} for p in self._pairlist_handlers]
@cached(TTLCache(maxsize=1, ttl=1800)) @cached(TTLCache(maxsize=1, ttl=1800))
@@ -73,9 +73,7 @@ class PairListManager():
return self._exchange.get_tickers() return self._exchange.get_tickers()
def refresh_pairlist(self) -> None: def refresh_pairlist(self) -> None:
""" """Run pairlist through all configured Pairlist Handlers."""
Run pairlist through all configured Pairlist Handlers.
"""
# Tickers should be cached to avoid calling the exchange on each call. # Tickers should be cached to avoid calling the exchange on each call.
tickers: Dict = {} tickers: Dict = {}
if self._tickers_needed: if self._tickers_needed:
@@ -120,12 +118,37 @@ class PairListManager():
:param logmethod: Function that'll be called, `logger.info` or `logger.warning`. :param logmethod: Function that'll be called, `logger.info` or `logger.warning`.
:return: pairlist - blacklisted pairs :return: pairlist - blacklisted pairs
""" """
try:
blacklist = self.expanded_blacklist
except ValueError as err:
logger.error(f"Pair blacklist contains an invalid Wildcard: {err}")
return []
for pair in deepcopy(pairlist): for pair in deepcopy(pairlist):
if pair in self._blacklist: if pair in blacklist:
logmethod(f"Pair {pair} in your blacklist. Removing it from whitelist...") logmethod(f"Pair {pair} in your blacklist. Removing it from whitelist...")
pairlist.remove(pair) pairlist.remove(pair)
return pairlist return pairlist
def verify_whitelist(self, pairlist: List[str], logmethod,
keep_invalid: bool = False) -> List[str]:
"""
Verify and remove items from pairlist - returning a filtered pairlist.
Logs a warning or info depending on `aswarning`.
Pairlist Handlers explicitly using this method shall use
`logmethod=logger.info` to avoid spamming with warning messages
:param pairlist: Pairlist to validate
:param logmethod: Function that'll be called, `logger.info` or `logger.warning`
:param keep_invalid: If sets to True, drops invalid pairs silently while expanding regexes.
:return: pairlist - whitelisted pairs
"""
try:
whitelist = expand_pairlist(pairlist, self._exchange.get_markets().keys(), keep_invalid)
except ValueError as err:
logger.error(f"Pair whitelist contains an invalid Wildcard: {err}")
return []
return whitelist
def create_pair_list(self, pairs: List[str], timeframe: str = None) -> ListPairsWithTimeframes: def create_pair_list(self, pairs: List[str], timeframe: str = None) -> ListPairsWithTimeframes:
""" """
Create list of pair tuples with (pair, timeframe) Create list of pair tuples with (pair, timeframe)

View File

@@ -44,7 +44,8 @@ class CooldownPeriod(IProtection):
trades = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until) trades = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until)
if trades: if trades:
# Get latest trade # Get latest trade
trade = sorted(trades, key=lambda t: t.close_date)[-1] # Ignore type error as we know we only get closed trades.
trade = sorted(trades, key=lambda t: t.close_date)[-1] # type: ignore
self.log_once(f"Cooldown for {pair} for {self.stop_duration_str}.", logger.info) self.log_once(f"Cooldown for {pair} for {self.stop_duration_str}.", logger.info)
until = self.calculate_lock_end([trade], self._stop_duration) until = self.calculate_lock_end([trade], self._stop_duration)

View File

@@ -7,7 +7,7 @@ from typing import Any, Dict, List, Optional, Tuple
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import timeframe_to_minutes
from freqtrade.misc import plural from freqtrade.misc import plural
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.persistence import Trade from freqtrade.persistence import LocalTrade
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -93,11 +93,11 @@ class IProtection(LoggingMixin, ABC):
""" """
@staticmethod @staticmethod
def calculate_lock_end(trades: List[Trade], stop_minutes: int) -> datetime: def calculate_lock_end(trades: List[LocalTrade], stop_minutes: int) -> datetime:
""" """
Get lock end time Get lock end time
""" """
max_date: datetime = max([trade.close_date for trade in trades]) max_date: datetime = max([trade.close_date for trade in trades if trade.close_date])
# comming from Database, tzinfo is not set. # comming from Database, tzinfo is not set.
if max_date.tzinfo is None: if max_date.tzinfo is None:
max_date = max_date.replace(tzinfo=timezone.utc) max_date = max_date.replace(tzinfo=timezone.utc)

View File

@@ -53,7 +53,7 @@ class LowProfitPairs(IProtection):
# Not enough trades in the relevant period # Not enough trades in the relevant period
return False, None, None return False, None, None
profit = sum(trade.close_profit for trade in trades) profit = sum(trade.close_profit for trade in trades if trade.close_profit)
if profit < self._required_profit: if profit < self._required_profit:
self.log_once( self.log_once(
f"Trading for {pair} stopped due to {profit:.2f} < {self._required_profit} " f"Trading for {pair} stopped due to {profit:.2f} < {self._required_profit} "

View File

@@ -55,7 +55,7 @@ class MaxDrawdown(IProtection):
# Drawdown is always positive # Drawdown is always positive
try: try:
drawdown, _, _ = calculate_max_drawdown(trades_df, value_col='close_profit') drawdown, _, _, _, _ = calculate_max_drawdown(trades_df, value_col='close_profit')
except ValueError: except ValueError:
return False, None, None return False, None, None

Some files were not shown because too many files have changed in this diff Show More