Compare commits
3 Commits
2022.11
...
feat/freqa
Author | SHA1 | Date | |
---|---|---|---|
|
755041c134 | ||
|
98c62dad91 | ||
|
52ee7fc981 |
@@ -11,14 +11,12 @@
|
|||||||
"mounts": [
|
"mounts": [
|
||||||
"source=freqtrade-bashhistory,target=/home/ftuser/commandhistory,type=volume"
|
"source=freqtrade-bashhistory,target=/home/ftuser/commandhistory,type=volume"
|
||||||
],
|
],
|
||||||
"workspaceMount": "source=${localWorkspaceFolder},target=/workspaces/freqtrade,type=bind,consistency=cached",
|
|
||||||
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
|
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
|
||||||
"remoteUser": "ftuser",
|
"remoteUser": "ftuser",
|
||||||
|
|
||||||
"onCreateCommand": "pip install --user -e .",
|
|
||||||
"postCreateCommand": "freqtrade create-userdir --userdir user_data/",
|
"postCreateCommand": "freqtrade create-userdir --userdir user_data/",
|
||||||
|
|
||||||
"workspaceFolder": "/workspaces/freqtrade",
|
"workspaceFolder": "/freqtrade/",
|
||||||
|
|
||||||
"settings": {
|
"settings": {
|
||||||
"terminal.integrated.shell.linux": "/bin/bash",
|
"terminal.integrated.shell.linux": "/bin/bash",
|
||||||
|
41
.github/workflows/ci.yml
vendored
@@ -74,7 +74,7 @@ jobs:
|
|||||||
if: matrix.python-version == '3.9' && matrix.os == 'ubuntu-22.04'
|
if: matrix.python-version == '3.9' && matrix.os == 'ubuntu-22.04'
|
||||||
|
|
||||||
- name: Coveralls
|
- name: Coveralls
|
||||||
if: (runner.os == 'Linux' && matrix.python-version == '3.10' && matrix.os == 'ubuntu-22.04')
|
if: (runner.os == 'Linux' && matrix.python-version == '3.9')
|
||||||
env:
|
env:
|
||||||
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||||
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||||
@@ -258,7 +258,7 @@ jobs:
|
|||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
mypy_version_check:
|
mypy_version_check:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
@@ -272,18 +272,8 @@ jobs:
|
|||||||
pip install pyaml
|
pip install pyaml
|
||||||
python build_helpers/pre_commit_update.py
|
python build_helpers/pre_commit_update.py
|
||||||
|
|
||||||
pre-commit:
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
|
||||||
with:
|
|
||||||
python-version: "3.10"
|
|
||||||
- uses: pre-commit/action@v3.0.0
|
|
||||||
|
|
||||||
docs_check:
|
docs_check:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
@@ -312,8 +302,8 @@ jobs:
|
|||||||
|
|
||||||
# Notify only once - when CI completes (and after deploy) in case it's successfull
|
# Notify only once - when CI completes (and after deploy) in case it's successfull
|
||||||
notify-complete:
|
notify-complete:
|
||||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check, pre-commit ]
|
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check ]
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-20.04
|
||||||
# Discord notification can't handle schedule events
|
# Discord notification can't handle schedule events
|
||||||
if: (github.event_name != 'schedule')
|
if: (github.event_name != 'schedule')
|
||||||
permissions:
|
permissions:
|
||||||
@@ -337,8 +327,8 @@ jobs:
|
|||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
deploy:
|
deploy:
|
||||||
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check, pre-commit ]
|
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check ]
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
||||||
|
|
||||||
@@ -407,6 +397,15 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
build_helpers/publish_docker_multi.sh
|
build_helpers/publish_docker_multi.sh
|
||||||
|
|
||||||
|
- name: Discord notification
|
||||||
|
uses: rjstone/discord-webhook-notify@v1
|
||||||
|
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) && (github.event_name != 'schedule')
|
||||||
|
with:
|
||||||
|
severity: info
|
||||||
|
details: Deploy Succeeded!
|
||||||
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
|
|
||||||
deploy_arm:
|
deploy_arm:
|
||||||
needs: [ deploy ]
|
needs: [ deploy ]
|
||||||
# Only run on 64bit machines
|
# Only run on 64bit machines
|
||||||
@@ -434,11 +433,3 @@ jobs:
|
|||||||
BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
|
BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
|
||||||
run: |
|
run: |
|
||||||
build_helpers/publish_docker_arm64.sh
|
build_helpers/publish_docker_arm64.sh
|
||||||
|
|
||||||
- name: Discord notification
|
|
||||||
uses: rjstone/discord-webhook-notify@v1
|
|
||||||
if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) && (github.event_name != 'schedule')
|
|
||||||
with:
|
|
||||||
severity: info
|
|
||||||
details: Deploy Succeeded!
|
|
||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
|
||||||
|
1
.gitignore
vendored
@@ -109,6 +109,7 @@ target/
|
|||||||
!*.gitkeep
|
!*.gitkeep
|
||||||
!config_examples/config_binance.example.json
|
!config_examples/config_binance.example.json
|
||||||
!config_examples/config_bittrex.example.json
|
!config_examples/config_bittrex.example.json
|
||||||
|
!config_examples/config_ftx.example.json
|
||||||
!config_examples/config_full.example.json
|
!config_examples/config_full.example.json
|
||||||
!config_examples/config_kraken.example.json
|
!config_examples/config_kraken.example.json
|
||||||
!config_examples/config_freqai.example.json
|
!config_examples/config_freqai.example.json
|
||||||
|
@@ -15,9 +15,9 @@ repos:
|
|||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- types-cachetools==5.2.1
|
- types-cachetools==5.2.1
|
||||||
- types-filelock==3.2.7
|
- types-filelock==3.2.7
|
||||||
- types-requests==2.28.11.5
|
- types-requests==2.28.8
|
||||||
- types-tabulate==0.9.0.0
|
- types-tabulate==0.8.11
|
||||||
- types-python-dateutil==2.8.19.4
|
- types-python-dateutil==2.8.19
|
||||||
# stages: [push]
|
# stages: [push]
|
||||||
|
|
||||||
- repo: https://github.com/pycqa/isort
|
- repo: https://github.com/pycqa/isort
|
||||||
@@ -34,9 +34,7 @@ repos:
|
|||||||
exclude: |
|
exclude: |
|
||||||
(?x)^(
|
(?x)^(
|
||||||
tests/.*|
|
tests/.*|
|
||||||
.*\.svg|
|
.*\.svg
|
||||||
.*\.yml|
|
|
||||||
.*\.json
|
|
||||||
)$
|
)$
|
||||||
- id: mixed-line-ending
|
- id: mixed-line-ending
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
FROM python:3.10.7-slim-bullseye as base
|
FROM python:3.10.6-slim-bullseye as base
|
||||||
|
|
||||||
# Setup env
|
# Setup env
|
||||||
ENV LANG C.UTF-8
|
ENV LANG C.UTF-8
|
||||||
@@ -11,7 +11,7 @@ ENV FT_APP_ENV="docker"
|
|||||||
# Prepare environment
|
# Prepare environment
|
||||||
RUN mkdir /freqtrade \
|
RUN mkdir /freqtrade \
|
||||||
&& apt-get update \
|
&& apt-get update \
|
||||||
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev libgomp1 \
|
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& useradd -u 1000 -G sudo -U -m -s /bin/bash ftuser \
|
&& useradd -u 1000 -G sudo -U -m -s /bin/bash ftuser \
|
||||||
&& chown ftuser:ftuser /freqtrade \
|
&& chown ftuser:ftuser /freqtrade \
|
||||||
|
@@ -28,6 +28,7 @@ Please read the [exchange specific notes](docs/exchanges.md) to learn about even
|
|||||||
|
|
||||||
- [X] [Binance](https://www.binance.com/)
|
- [X] [Binance](https://www.binance.com/)
|
||||||
- [X] [Bittrex](https://bittrex.com/)
|
- [X] [Bittrex](https://bittrex.com/)
|
||||||
|
- [X] [FTX](https://ftx.com/#a=2258149)
|
||||||
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
- [X] [Huobi](http://huobi.com/)
|
- [X] [Huobi](http://huobi.com/)
|
||||||
- [X] [Kraken](https://kraken.com/)
|
- [X] [Kraken](https://kraken.com/)
|
||||||
@@ -38,7 +39,7 @@ Please read the [exchange specific notes](docs/exchanges.md) to learn about even
|
|||||||
|
|
||||||
- [X] [Binance](https://www.binance.com/)
|
- [X] [Binance](https://www.binance.com/)
|
||||||
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
- [X] [OKX](https://okx.com/)
|
- [X] [OKX](https://okx.com/).
|
||||||
|
|
||||||
Please make sure to read the [exchange specific notes](docs/exchanges.md), as well as the [trading with leverage](docs/leverage.md) documentation before diving in.
|
Please make sure to read the [exchange specific notes](docs/exchanges.md), as well as the [trading with leverage](docs/leverage.md) documentation before diving in.
|
||||||
|
|
||||||
@@ -129,7 +130,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.
|
||||||
- `/stopentry`: Stop entering new trades.
|
- `/stopbuy`: Stop entering new trades.
|
||||||
- `/status <trade_id>|[table]`: Lists all or specific open trades.
|
- `/status <trade_id>|[table]`: Lists all or specific open trades.
|
||||||
- `/profit [<n>]`: Lists cumulative profit from all finished trades, over the last n days.
|
- `/profit [<n>]`: Lists cumulative profit from all finished trades, over the last n days.
|
||||||
- `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`).
|
- `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`).
|
||||||
|
BIN
build_helpers/TA_Lib-0.4.24-cp310-cp310-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.24-cp38-cp38-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.24-cp39-cp39-win_amd64.whl
Normal file
@@ -6,13 +6,13 @@ python -m pip install --upgrade pip wheel
|
|||||||
$pyv = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
|
$pyv = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
|
||||||
|
|
||||||
if ($pyv -eq '3.8') {
|
if ($pyv -eq '3.8') {
|
||||||
pip install build_helpers\TA_Lib-0.4.25-cp38-cp38-win_amd64.whl
|
pip install build_helpers\TA_Lib-0.4.24-cp38-cp38-win_amd64.whl
|
||||||
}
|
}
|
||||||
if ($pyv -eq '3.9') {
|
if ($pyv -eq '3.9') {
|
||||||
pip install build_helpers\TA_Lib-0.4.25-cp39-cp39-win_amd64.whl
|
pip install build_helpers\TA_Lib-0.4.24-cp39-cp39-win_amd64.whl
|
||||||
}
|
}
|
||||||
if ($pyv -eq '3.10') {
|
if ($pyv -eq '3.10') {
|
||||||
pip install build_helpers\TA_Lib-0.4.25-cp310-cp310-win_amd64.whl
|
pip install build_helpers\TA_Lib-0.4.24-cp310-cp310-win_amd64.whl
|
||||||
}
|
}
|
||||||
pip install -r requirements-dev.txt
|
pip install -r requirements-dev.txt
|
||||||
pip install -e .
|
pip install -e .
|
||||||
|
@@ -53,7 +53,7 @@
|
|||||||
"XTZ/BTC"
|
"XTZ/BTC"
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
"BNB/.*"
|
"BNB/BTC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"pairlists": [
|
"pairlists": [
|
||||||
|
@@ -18,8 +18,13 @@
|
|||||||
"name": "binance",
|
"name": "binance",
|
||||||
"key": "",
|
"key": "",
|
||||||
"secret": "",
|
"secret": "",
|
||||||
"ccxt_config": {},
|
"ccxt_config": {
|
||||||
"ccxt_async_config": {},
|
"enableRateLimit": true
|
||||||
|
},
|
||||||
|
"ccxt_async_config": {
|
||||||
|
"enableRateLimit": true,
|
||||||
|
"rateLimit": 200
|
||||||
|
},
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"1INCH/USDT",
|
"1INCH/USDT",
|
||||||
"ALGO/USDT"
|
"ALGO/USDT"
|
||||||
@@ -48,6 +53,7 @@
|
|||||||
],
|
],
|
||||||
"freqai": {
|
"freqai": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
|
"startup_candles": 10000,
|
||||||
"purge_old_models": true,
|
"purge_old_models": true,
|
||||||
"train_period_days": 15,
|
"train_period_days": 15,
|
||||||
"backtest_period_days": 7,
|
"backtest_period_days": 7,
|
||||||
@@ -69,11 +75,9 @@
|
|||||||
"weight_factor": 0.9,
|
"weight_factor": 0.9,
|
||||||
"principal_component_analysis": false,
|
"principal_component_analysis": false,
|
||||||
"use_SVM_to_remove_outliers": true,
|
"use_SVM_to_remove_outliers": true,
|
||||||
"indicator_periods_candles": [
|
"stratify_training_data": 0,
|
||||||
10,
|
"indicator_max_period_candles": 20,
|
||||||
20
|
"indicator_periods_candles": [10, 20]
|
||||||
],
|
|
||||||
"plot_feature_importances": 0
|
|
||||||
},
|
},
|
||||||
"data_split_parameters": {
|
"data_split_parameters": {
|
||||||
"test_size": 0.33,
|
"test_size": 0.33,
|
||||||
|
96
config_examples/config_ftx.example.json
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
{
|
||||||
|
"max_open_trades": 3,
|
||||||
|
"stake_currency": "USD",
|
||||||
|
"stake_amount": 50,
|
||||||
|
"tradable_balance_ratio": 0.99,
|
||||||
|
"fiat_display_currency": "USD",
|
||||||
|
"timeframe": "5m",
|
||||||
|
"dry_run": true,
|
||||||
|
"cancel_open_orders_on_exit": false,
|
||||||
|
"unfilledtimeout": {
|
||||||
|
"entry": 10,
|
||||||
|
"exit": 10,
|
||||||
|
"exit_timeout_count": 0,
|
||||||
|
"unit": "minutes"
|
||||||
|
},
|
||||||
|
"entry_pricing": {
|
||||||
|
"price_side": "same",
|
||||||
|
"use_order_book": true,
|
||||||
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0,
|
||||||
|
"check_depth_of_market": {
|
||||||
|
"enabled": false,
|
||||||
|
"bids_to_ask_delta": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"exit_pricing": {
|
||||||
|
"price_side": "same",
|
||||||
|
"use_order_book": true,
|
||||||
|
"order_book_top": 1
|
||||||
|
},
|
||||||
|
"exchange": {
|
||||||
|
"name": "ftx",
|
||||||
|
"key": "your_exchange_key",
|
||||||
|
"secret": "your_exchange_secret",
|
||||||
|
"ccxt_config": {},
|
||||||
|
"ccxt_async_config": {},
|
||||||
|
"pair_whitelist": [
|
||||||
|
"BTC/USD",
|
||||||
|
"ETH/USD",
|
||||||
|
"BNB/USD",
|
||||||
|
"USDT/USD",
|
||||||
|
"LTC/USD",
|
||||||
|
"SRM/USD",
|
||||||
|
"SXP/USD",
|
||||||
|
"XRP/USD",
|
||||||
|
"DOGE/USD",
|
||||||
|
"1INCH/USD",
|
||||||
|
"CHZ/USD",
|
||||||
|
"MATIC/USD",
|
||||||
|
"LINK/USD",
|
||||||
|
"OXY/USD",
|
||||||
|
"SUSHI/USD"
|
||||||
|
],
|
||||||
|
"pair_blacklist": [
|
||||||
|
"FTT/USD"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"}
|
||||||
|
],
|
||||||
|
"edge": {
|
||||||
|
"enabled": false,
|
||||||
|
"process_throttle_secs": 3600,
|
||||||
|
"calculate_since_number_of_days": 7,
|
||||||
|
"allowed_risk": 0.01,
|
||||||
|
"stoploss_range_min": -0.01,
|
||||||
|
"stoploss_range_max": -0.1,
|
||||||
|
"stoploss_range_step": -0.01,
|
||||||
|
"minimum_winrate": 0.60,
|
||||||
|
"minimum_expectancy": 0.20,
|
||||||
|
"min_trade_number": 10,
|
||||||
|
"max_trade_duration_minute": 1440,
|
||||||
|
"remove_pumps": false
|
||||||
|
},
|
||||||
|
"telegram": {
|
||||||
|
"enabled": false,
|
||||||
|
"token": "your_telegram_token",
|
||||||
|
"chat_id": "your_telegram_chat_id"
|
||||||
|
},
|
||||||
|
"api_server": {
|
||||||
|
"enabled": false,
|
||||||
|
"listen_ip_address": "127.0.0.1",
|
||||||
|
"listen_port": 8080,
|
||||||
|
"verbosity": "error",
|
||||||
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": [],
|
||||||
|
"username": "freqtrader",
|
||||||
|
"password": "SuperSecurePassword"
|
||||||
|
},
|
||||||
|
"bot_name": "freqtrade",
|
||||||
|
"initial_state": "running",
|
||||||
|
"force_entry_enable": false,
|
||||||
|
"internals": {
|
||||||
|
"process_throttle_secs": 5
|
||||||
|
}
|
||||||
|
}
|
@@ -64,8 +64,8 @@
|
|||||||
"stoploss_on_exchange_limit_ratio": 0.99
|
"stoploss_on_exchange_limit_ratio": 0.99
|
||||||
},
|
},
|
||||||
"order_time_in_force": {
|
"order_time_in_force": {
|
||||||
"entry": "GTC",
|
"entry": "gtc",
|
||||||
"exit": "GTC"
|
"exit": "gtc"
|
||||||
},
|
},
|
||||||
"pairlists": [
|
"pairlists": [
|
||||||
{"method": "StaticPairList"},
|
{"method": "StaticPairList"},
|
||||||
@@ -172,24 +172,7 @@
|
|||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
"CORS_origins": [],
|
"CORS_origins": [],
|
||||||
"username": "freqtrader",
|
"username": "freqtrader",
|
||||||
"password": "SuperSecurePassword",
|
"password": "SuperSecurePassword"
|
||||||
"ws_token": "secret_ws_t0ken."
|
|
||||||
},
|
|
||||||
"external_message_consumer": {
|
|
||||||
"enabled": false,
|
|
||||||
"producers": [
|
|
||||||
{
|
|
||||||
"name": "default",
|
|
||||||
"host": "127.0.0.2",
|
|
||||||
"port": 8080,
|
|
||||||
"ws_token": "secret_ws_t0ken."
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"wait_timeout": 300,
|
|
||||||
"ping_timeout": 10,
|
|
||||||
"sleep_time": 10,
|
|
||||||
"remove_entry_exit_signals": false,
|
|
||||||
"message_size_limit": 8
|
|
||||||
},
|
},
|
||||||
"bot_name": "freqtrade",
|
"bot_name": "freqtrade",
|
||||||
"db_url": "sqlite:///tradesv3.sqlite",
|
"db_url": "sqlite:///tradesv3.sqlite",
|
||||||
@@ -204,7 +187,6 @@
|
|||||||
"strategy_path": "user_data/strategies/",
|
"strategy_path": "user_data/strategies/",
|
||||||
"recursive_strategy_search": false,
|
"recursive_strategy_search": false,
|
||||||
"add_config_files": [],
|
"add_config_files": [],
|
||||||
"reduce_df_footprint": false,
|
|
||||||
"dataformat_ohlcv": "json",
|
"dataformat_ohlcv": "json",
|
||||||
"dataformat_trades": "jsongz"
|
"dataformat_trades": "jsongz"
|
||||||
}
|
}
|
||||||
|
@@ -11,7 +11,7 @@ ENV FT_APP_ENV="docker"
|
|||||||
# Prepare environment
|
# Prepare environment
|
||||||
RUN mkdir /freqtrade \
|
RUN mkdir /freqtrade \
|
||||||
&& apt-get update \
|
&& apt-get update \
|
||||||
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-dev libutf8proc-dev libsnappy-dev \
|
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-dev \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& useradd -u 1000 -G sudo -U -m ftuser \
|
&& useradd -u 1000 -G sudo -U -m ftuser \
|
||||||
&& chown ftuser:ftuser /freqtrade \
|
&& chown ftuser:ftuser /freqtrade \
|
||||||
@@ -37,7 +37,6 @@ ENV LD_LIBRARY_PATH /usr/local/lib
|
|||||||
COPY --chown=ftuser:ftuser requirements.txt /freqtrade/
|
COPY --chown=ftuser:ftuser requirements.txt /freqtrade/
|
||||||
USER ftuser
|
USER ftuser
|
||||||
RUN pip install --user --no-cache-dir numpy \
|
RUN pip install --user --no-cache-dir numpy \
|
||||||
&& pip install --user /tmp/pyarrow-*.whl \
|
|
||||||
&& pip install --user --no-cache-dir -r requirements.txt
|
&& pip install --user --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Copy dependencies to runtime-image
|
# Copy dependencies to runtime-image
|
||||||
|
@@ -6,3 +6,4 @@ FROM ${sourceimage}:${sourcetag}
|
|||||||
COPY requirements-freqai.txt /freqtrade/
|
COPY requirements-freqai.txt /freqtrade/
|
||||||
|
|
||||||
RUN pip install -r requirements-freqai.txt --user --no-cache-dir
|
RUN pip install -r requirements-freqai.txt --user --no-cache-dir
|
||||||
|
|
||||||
|
@@ -1,8 +1,7 @@
|
|||||||
FROM freqtradeorg/freqtrade:develop_plot
|
FROM freqtradeorg/freqtrade:develop_plot
|
||||||
|
|
||||||
|
|
||||||
# Pin jupyter-client to avoid tornado version conflict
|
RUN pip install jupyterlab --user --no-cache-dir
|
||||||
RUN pip install jupyterlab jupyter-client==7.3.4 --user --no-cache-dir
|
|
||||||
|
|
||||||
# Empty the ENTRYPOINT to allow all commands
|
# Empty the ENTRYPOINT to allow all commands
|
||||||
ENTRYPOINT []
|
ENTRYPOINT []
|
||||||
|
@@ -10,7 +10,7 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8888:8888"
|
- "127.0.0.1:8888:8888"
|
||||||
volumes:
|
volumes:
|
||||||
- "../user_data:/freqtrade/user_data"
|
- "./user_data:/freqtrade/user_data"
|
||||||
# Default command used when running `docker compose up`
|
# Default command used when running `docker compose up`
|
||||||
command: >
|
command: >
|
||||||
jupyter lab --port=8888 --ip 0.0.0.0 --allow-root
|
jupyter lab --port=8888 --ip 0.0.0.0 --allow-root
|
||||||
|
@@ -17,7 +17,6 @@ from typing import Any, Dict
|
|||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.constants import Config
|
|
||||||
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
TARGET_TRADES = 600
|
TARGET_TRADES = 600
|
||||||
@@ -32,7 +31,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: Config, processed: Dict[str, DataFrame],
|
config: Dict, processed: Dict[str, DataFrame],
|
||||||
backtest_stats: Dict[str, Any],
|
backtest_stats: Dict[str, Any],
|
||||||
*args, **kwargs) -> float:
|
*args, **kwargs) -> float:
|
||||||
"""
|
"""
|
||||||
@@ -78,8 +77,6 @@ This function needs to return a floating point number (`float`). Smaller numbers
|
|||||||
To override a pre-defined space (`roi_space`, `generate_roi_table`, `stoploss_space`, `trailing_space`), define a nested class called Hyperopt and define the required spaces as follows:
|
To override a pre-defined space (`roi_space`, `generate_roi_table`, `stoploss_space`, `trailing_space`), define a nested class called Hyperopt and define the required spaces as follows:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from freqtrade.optimize.space import Categorical, Dimension, Integer, SKDecimal
|
|
||||||
|
|
||||||
class MyAwesomeStrategy(IStrategy):
|
class MyAwesomeStrategy(IStrategy):
|
||||||
class HyperOpt:
|
class HyperOpt:
|
||||||
# Define a custom stoploss space.
|
# Define a custom stoploss space.
|
||||||
@@ -96,33 +93,6 @@ class MyAwesomeStrategy(IStrategy):
|
|||||||
SKDecimal(0.01, 0.07, decimals=3, name='roi_p2'),
|
SKDecimal(0.01, 0.07, decimals=3, name='roi_p2'),
|
||||||
SKDecimal(0.01, 0.20, decimals=3, name='roi_p3'),
|
SKDecimal(0.01, 0.20, decimals=3, name='roi_p3'),
|
||||||
]
|
]
|
||||||
|
|
||||||
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
|
||||||
|
|
||||||
roi_table = {}
|
|
||||||
roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3']
|
|
||||||
roi_table[params['roi_t3']] = params['roi_p1'] + params['roi_p2']
|
|
||||||
roi_table[params['roi_t3'] + params['roi_t2']] = params['roi_p1']
|
|
||||||
roi_table[params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0
|
|
||||||
|
|
||||||
return roi_table
|
|
||||||
|
|
||||||
def trailing_space() -> List[Dimension]:
|
|
||||||
# All parameters here are mandatory, you can only modify their type or the range.
|
|
||||||
return [
|
|
||||||
# Fixed to true, if optimizing trailing_stop we assume to use trailing stop at all times.
|
|
||||||
Categorical([True], name='trailing_stop'),
|
|
||||||
|
|
||||||
SKDecimal(0.01, 0.35, decimals=3, name='trailing_stop_positive'),
|
|
||||||
# 'trailing_stop_positive_offset' should be greater than 'trailing_stop_positive',
|
|
||||||
# so this intermediate parameter is used as the value of the difference between
|
|
||||||
# them. The value of the 'trailing_stop_positive_offset' is constructed in the
|
|
||||||
# generate_trailing_params() method.
|
|
||||||
# This is similar to the hyperspace dimensions used for constructing the ROI tables.
|
|
||||||
SKDecimal(0.001, 0.1, decimals=3, name='trailing_stop_positive_offset_p1'),
|
|
||||||
|
|
||||||
Categorical([True, False], name='trailing_only_offset_is_reached'),
|
|
||||||
]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
|
Before Width: | Height: | Size: 80 KiB |
Before Width: | Height: | Size: 307 KiB |
Before Width: | Height: | Size: 345 KiB |
BIN
docs/assets/freqai_algo.png
Normal file
After Width: | Height: | Size: 995 KiB |
Before Width: | Height: | Size: 490 KiB |
Before Width: | Height: | Size: 66 KiB |
Before Width: | Height: | Size: 458 KiB |
Before Width: | Height: | Size: 270 KiB |
Before Width: | Height: | Size: 185 KiB |
Before Width: | Height: | Size: 362 KiB |
BIN
docs/assets/weights_factor.png
Normal file
After Width: | Height: | Size: 126 KiB |
@@ -107,7 +107,7 @@ Strategy arguments:
|
|||||||
|
|
||||||
## Test your strategy with Backtesting
|
## Test your strategy with Backtesting
|
||||||
|
|
||||||
Now you have good Entry and exit 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 [backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
real data. This is what we call [backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||||
|
|
||||||
Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHLCV) data from `user_data/data/<exchange>` by default.
|
Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHLCV) data from `user_data/data/<exchange>` by default.
|
||||||
@@ -215,7 +215,7 @@ Sometimes your account has certain fee rebates (fee reductions starting with a c
|
|||||||
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.
|
||||||
This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit).
|
This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit).
|
||||||
|
|
||||||
For example, if the commission fee per order is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:
|
For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --fee 0.001
|
freqtrade backtesting --fee 0.001
|
||||||
@@ -252,41 +252,41 @@ The most important in the backtesting is to understand the result.
|
|||||||
A backtesting result will look like that:
|
A backtesting result will look like that:
|
||||||
|
|
||||||
```
|
```
|
||||||
========================================================= BACKTESTING REPORT =========================================================
|
========================================================= BACKTESTING REPORT ==========================================================
|
||||||
| Pair | Entries | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% |
|
| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% |
|
||||||
|:---------|--------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:|
|
|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:|
|
||||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 |
|
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 |
|
||||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 |
|
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 |
|
||||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 |
|
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 |
|
||||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 |
|
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 |
|
||||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 |
|
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 |
|
||||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 |
|
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 |
|
||||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 |
|
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 |
|
||||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 |
|
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 |
|
||||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 |
|
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 |
|
||||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 |
|
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 |
|
||||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 |
|
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 |
|
||||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 |
|
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 |
|
||||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 |
|
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 |
|
||||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 |
|
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 |
|
||||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 |
|
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 |
|
||||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 |
|
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 |
|
||||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 |
|
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 |
|
||||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 |
|
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 |
|
||||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 |
|
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 |
|
||||||
========================================================= EXIT REASON STATS ==========================================================
|
========================================================= EXIT REASON STATS ==========================================================
|
||||||
| Exit Reason | Exits | Wins | Draws | Losses |
|
| Exit Reason | Sells | Wins | Draws | Losses |
|
||||||
|:-------------------|--------:|------:|-------:|--------:|
|
|:-------------------|--------:|------:|-------:|--------:|
|
||||||
| trailing_stop_loss | 205 | 150 | 0 | 55 |
|
| trailing_stop_loss | 205 | 150 | 0 | 55 |
|
||||||
| stop_loss | 166 | 0 | 0 | 166 |
|
| stop_loss | 166 | 0 | 0 | 166 |
|
||||||
| exit_signal | 56 | 36 | 0 | 20 |
|
| exit_signal | 56 | 36 | 0 | 20 |
|
||||||
| force_exit | 2 | 0 | 0 | 2 |
|
| force_exit | 2 | 0 | 0 | 2 |
|
||||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||||
| Pair | Entries | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% |
|
| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% |
|
||||||
|:---------|---------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:|
|
|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:|
|
||||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 |
|
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 |
|
||||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 |
|
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 |
|
||||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 |
|
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 |
|
||||||
================== SUMMARY METRICS ==================
|
================== SUMMARY METRICS ==================
|
||||||
| Metric | Value |
|
| Metric | Value |
|
||||||
|-----------------------------+---------------------|
|
|-----------------------------+---------------------|
|
||||||
@@ -356,7 +356,7 @@ The column `Avg Profit %` shows the average profit for all trades made while the
|
|||||||
The column `Tot Profit %` shows instead the total profit % in relation to the starting balance.
|
The column `Tot Profit %` shows instead the total profit % in relation to the starting balance.
|
||||||
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%`.
|
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 entry strategy, your exit strategy, and also by the `minimal_roi` and `stop_loss` you have set.
|
Your strategy performance is influenced by your buy strategy, your exit strategy, and also by the `minimal_roi` and `stop_loss` you have set.
|
||||||
|
|
||||||
For example, if your `minimal_roi` is only `"0": 0.01` you cannot expect the bot to make more profit than 1% (because it will exit every time a trade reaches 1%).
|
For example, if your `minimal_roi` is only `"0": 0.01` you cannot expect the bot to make more profit than 1% (because it will exit every time a trade reaches 1%).
|
||||||
|
|
||||||
@@ -515,20 +515,20 @@ You can then load the trades to perform further analysis as shown in the [data a
|
|||||||
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
||||||
|
|
||||||
- Exchange [trading limits](#trading-limits-in-backtesting) are respected
|
- Exchange [trading limits](#trading-limits-in-backtesting) are respected
|
||||||
- Entries happen at open-price
|
- Buys happen at open-price
|
||||||
- All orders are filled at the requested price (no slippage, no unfilled orders)
|
- All orders are filled at the requested price (no slippage, no unfilled orders)
|
||||||
- Exit-signal exits happen at open-price of the consecutive candle
|
- Exit-signal exits happen at open-price of the consecutive candle
|
||||||
- Exit-signal is favored over Stoploss, because exit-signals are assumed to trigger on candle's open
|
- Exit-signal is favored over Stoploss, because exit-signals are assumed to trigger on candle's open
|
||||||
- ROI
|
- ROI
|
||||||
- exits are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the exit will be at 2%)
|
- exits are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the exit will be at 2%)
|
||||||
- exits are never "below the candle", so a ROI of 2% may result in a exit at 2.4% if low was at 2.4% profit
|
- exits are never "below the candle", so a ROI of 2% may result in a exit at 2.4% if low was at 2.4% profit
|
||||||
- Force-exits caused by `<N>=-1` ROI entries use low as exit value, unless N falls on the candle open (e.g. `120: -1` for 1h candles)
|
- Forceexits caused by `<N>=-1` ROI entries use low as exit value, unless N falls on the candle open (e.g. `120: -1` for 1h candles)
|
||||||
- Stoploss exits happen exactly at stoploss price, even if low was lower, but the loss will be `2 * fees` higher than the stoploss price
|
- Stoploss exits happen exactly at stoploss price, even if low was lower, but the loss will be `2 * fees` higher than the stoploss price
|
||||||
- Stoploss is evaluated before ROI within one candle. So you can often see more trades with the `stoploss` exit reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes
|
- Stoploss is evaluated before ROI within one candle. So you can often see more trades with the `stoploss` exit reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes
|
||||||
- Low happens before high for stoploss, protecting capital first
|
- Low happens before high for stoploss, protecting capital first
|
||||||
- Trailing stoploss
|
- Trailing stoploss
|
||||||
- Trailing Stoploss is only adjusted if it's below the candle's low (otherwise it would be triggered)
|
- Trailing Stoploss is only adjusted if it's below the candle's low (otherwise it would be triggered)
|
||||||
- On trade entry candles that trigger trailing stoploss, the "minimum offset" (`stop_positive_offset`) is assumed (instead of high) - and the stop is calculated from this point. This rule is NOT applicable to custom-stoploss scenarios, since there's no information about the stoploss logic available.
|
- On trade entry candles that trigger trailing stoploss, the "minimum offset" (`stop_positive_offset`) is assumed (instead of high) - and the stop is calculated from this point
|
||||||
- High happens first - adjusting stoploss
|
- High happens first - adjusting stoploss
|
||||||
- Low uses the adjusted stoploss (so exits with large high-low difference are backtested correctly)
|
- Low uses the adjusted stoploss (so exits with large high-low difference are backtested correctly)
|
||||||
- ROI applies before trailing-stop, ensuring profits are "top-capped" at ROI if both ROI and trailing stop applies
|
- ROI applies before trailing-stop, ensuring profits are "top-capped" at ROI if both ROI and trailing stop applies
|
||||||
@@ -546,8 +546,8 @@ In addition to the above assumptions, strategy authors should carefully read the
|
|||||||
|
|
||||||
### Trading limits in backtesting
|
### Trading limits in backtesting
|
||||||
|
|
||||||
Exchanges have certain trading limits, like minimum (and maximum) base currency, or minimum/maximum stake (quote) currency.
|
Exchanges have certain trading limits, like minimum base currency, or minimum stake (quote) currency.
|
||||||
These limits are usually listed in the exchange documentation as "trading rules" or similar and can be quite different between different pairs.
|
These limits are usually listed in the exchange documentation as "trading rules" or similar.
|
||||||
|
|
||||||
Backtesting (as well as live and dry-run) does honor these limits, and will ensure that a stoploss can be placed below this value - so the value will be slightly higher than what the exchange specifies.
|
Backtesting (as well as live and dry-run) does honor these limits, and will ensure that a stoploss can be placed below this value - so the value will be slightly higher than what the exchange specifies.
|
||||||
Freqtrade has however no information about historic limits.
|
Freqtrade has however no information about historic limits.
|
||||||
@@ -561,14 +561,6 @@ BTC trades at 22.000\$ today (0.001 BTC is related to this) - but the backtestin
|
|||||||
Today's minimum would be `0.001 * 22_000` - or 22\$.
|
Today's minimum would be `0.001 * 22_000` - or 22\$.
|
||||||
However the limit could also be 50$ - based on `0.001 * 50_000` in some historic setting.
|
However the limit could also be 50$ - based on `0.001 * 50_000` in some historic setting.
|
||||||
|
|
||||||
#### Trading precision limits
|
|
||||||
|
|
||||||
Most exchanges pose precision limits on both price and amounts, so you cannot buy 1.0020401 of a pair, or at a price of 1.24567123123.
|
|
||||||
Instead, these prices and amounts will be rounded or truncated (based on the exchange definition) to the defined trading precision.
|
|
||||||
The above values may for example be rounded to an amount of 1.002, and a price of 1.24567.
|
|
||||||
|
|
||||||
These precision values are based on current exchange limits (as described in the [above section](#trading-limits-in-backtesting)), as historic precision limits are not available.
|
|
||||||
|
|
||||||
## Improved backtest accuracy
|
## Improved backtest accuracy
|
||||||
|
|
||||||
One big limitation of backtesting is it's inability to know how prices moved intra-candle (was high before close, or viceversa?).
|
One big limitation of backtesting is it's inability to know how prices moved intra-candle (was high before close, or viceversa?).
|
||||||
@@ -612,11 +604,11 @@ There will be an additional table comparing win/losses of the different strategi
|
|||||||
Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
|
Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
|
||||||
|
|
||||||
```
|
```
|
||||||
=========================================================== STRATEGY SUMMARY ===========================================================================
|
=========================================================== STRATEGY SUMMARY =========================================================================
|
||||||
| Strategy | Entries | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % |
|
| Strategy | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % |
|
||||||
|:------------|---------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:|
|
|:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:|
|
||||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 |
|
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 |
|
||||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 |
|
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 |
|
||||||
```
|
```
|
||||||
|
|
||||||
## Next step
|
## Next step
|
||||||
|
@@ -70,7 +70,7 @@ This loop will be repeated again and again until the bot is stopped.
|
|||||||
* Determine stake size by calling the `custom_stake_amount()` callback.
|
* Determine stake size by calling the `custom_stake_amount()` callback.
|
||||||
* Check position adjustments for open trades if enabled and call `adjust_trade_position()` to determine if an additional order is requested.
|
* Check position adjustments for open trades if enabled and call `adjust_trade_position()` to determine if an additional order is requested.
|
||||||
* Call `custom_stoploss()` and `custom_exit()` to find custom exit points.
|
* Call `custom_stoploss()` and `custom_exit()` to find custom exit points.
|
||||||
* For exits based on exit-signal, custom-exit and partial exits: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
|
* For exits based on exit-signal and custom-exit: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
|
||||||
* Generate backtest report output
|
* Generate backtest report output
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
|
@@ -58,20 +58,9 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
|
|||||||
|
|
||||||
!!! Tip "Use multiple configuration files to keep secrets secret"
|
!!! Tip "Use multiple configuration files to keep secrets secret"
|
||||||
You can use a 2nd configuration file containing your secrets. That way you can share your "primary" configuration file, while still keeping your API keys for yourself.
|
You can use a 2nd configuration file containing your secrets. That way you can share your "primary" configuration file, while still keeping your API keys for yourself.
|
||||||
The 2nd file should only specify what you intend to override.
|
|
||||||
If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, `config-private.json`).
|
|
||||||
|
|
||||||
For one-off commands, you can also use the below syntax by specifying multiple "--config" parameters.
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
freqtrade trade --config user_data/config1.json --config user_data/config-private.json <...>
|
|
||||||
```
|
|
||||||
|
|
||||||
The below is equivalent to the example above - but having 2 configuration files in the configuration, for easier reuse.
|
|
||||||
|
|
||||||
``` json title="user_data/config.json"
|
``` json title="user_data/config.json"
|
||||||
"add_config_files": [
|
"add_config_files": [
|
||||||
"config1.json",
|
|
||||||
"config-private.json"
|
"config-private.json"
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
@@ -80,6 +69,17 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
|
|||||||
freqtrade trade --config user_data/config.json <...>
|
freqtrade trade --config user_data/config.json <...>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The 2nd file should only specify what you intend to override.
|
||||||
|
If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, `config-private.json`).
|
||||||
|
|
||||||
|
For one-off commands, you can also use the below syntax by specifying multiple "--config" parameters.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade trade --config user_data/config.json --config user_data/config-private.json <...>
|
||||||
|
```
|
||||||
|
|
||||||
|
This is equivalent to the example above - but `config-private.json` is specified as cli argument.
|
||||||
|
|
||||||
??? Note "config collision handling"
|
??? Note "config collision handling"
|
||||||
If the same configuration setting takes place in both `config.json` and `config-import.json`, then the parent configuration wins.
|
If the same configuration setting takes place in both `config.json` and `config-import.json`, then the parent configuration wins.
|
||||||
In the below case, `max_open_trades` would be 3 after the merging - as the reusable "import" configuration has this key overwritten.
|
In the below case, `max_open_trades` would be 3 after the merging - as the reusable "import" configuration has this key overwritten.
|
||||||
@@ -111,8 +111,6 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
If multiple files are in the `add_config_files` section, then they will be assumed to be at identical levels, having the last occurrence override the earlier config (unless a parent already defined such a key).
|
|
||||||
|
|
||||||
## Configuration parameters
|
## Configuration parameters
|
||||||
|
|
||||||
The table below will list all configuration parameters available.
|
The table below will list all configuration parameters available.
|
||||||
@@ -215,28 +213,24 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `telegram.balance_dust_level` | Dust-level (in stake currency) - currencies with a balance below this will not be shown by `/balance`. <br> **Datatype:** float
|
| `telegram.balance_dust_level` | Dust-level (in stake currency) - currencies with a balance below this will not be shown by `/balance`. <br> **Datatype:** float
|
||||||
| `telegram.reload` | Allow "reload" buttons on telegram messages. <br>*Defaults to `True`.<br> **Datatype:** boolean
|
| `telegram.reload` | Allow "reload" buttons on telegram messages. <br>*Defaults to `True`.<br> **Datatype:** boolean
|
||||||
| `telegram.notification_settings.*` | Detailed notification settings. Refer to the [telegram documentation](telegram-usage.md) for details.<br> **Datatype:** dictionary
|
| `telegram.notification_settings.*` | Detailed notification settings. Refer to the [telegram documentation](telegram-usage.md) for details.<br> **Datatype:** dictionary
|
||||||
| `telegram.allow_custom_messages` | Enable the sending of Telegram messages from strategies via the dataprovider.send_msg() function. <br> **Datatype:** Boolean
|
|
||||||
| | **Webhook**
|
| | **Webhook**
|
||||||
| `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.entry` | Payload to send on entry. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookentry` | Payload to send on entry. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.entry_cancel` | Payload to send on entry order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookentrycancel` | Payload to send on entry order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.entry_fill` | Payload to send on entry order filled. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookentryfill` | Payload to send on entry order filled. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.exit` | Payload to send on exit. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookexit` | Payload to send on exit. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.exit_cancel` | Payload to send on exit order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookexitcancel` | Payload to send on exit order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.exit_fill` | Payload to send on exit order filled. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookexitfill` | Payload to send on exit order filled. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.status` | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.webhookstatus` | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.allow_custom_messages` | Enable the sending of Webhook messages from strategies via the dataprovider.send_msg() function. <br> **Datatype:** Boolean
|
| | **Rest API / FreqUI**
|
||||||
| | **Rest API / FreqUI / Producer-Consumer**
|
|
||||||
| `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details. <br> **Datatype:** Boolean
|
| `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details. <br> **Datatype:** Boolean
|
||||||
| `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details. <br> **Datatype:** IPv4
|
| `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details. <br> **Datatype:** IPv4
|
||||||
| `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details. <br>**Datatype:** Integer between 1024 and 65535
|
| `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details. <br>**Datatype:** Integer between 1024 and 65535
|
||||||
| `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
|
||||||
| `api_server.ws_token` | API token for the Message WebSocket. 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
|
| `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
|
||||||
| `external_message_consumer` | Enable [Producer/Consumer mode](producer-consumer.md) for more details. <br> **Datatype:** Dict
|
|
||||||
| | **Other**
|
| | **Other**
|
||||||
| `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`
|
| `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`
|
||||||
| `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below. <br> **Datatype:** Boolean
|
| `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below. <br> **Datatype:** Boolean
|
||||||
@@ -253,7 +247,6 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `add_config_files` | Additional config files. These files will be loaded and merged with the current config file. The files are resolved relative to the initial file.<br> *Defaults to `[]`*. <br> **Datatype:** List of strings
|
| `add_config_files` | Additional config files. These files will be loaded and merged with the current config file. The files are resolved relative to the initial file.<br> *Defaults to `[]`*. <br> **Datatype:** List of strings
|
||||||
| `dataformat_ohlcv` | Data format to use to store historical candle (OHLCV) data. <br> *Defaults to `json`*. <br> **Datatype:** String
|
| `dataformat_ohlcv` | Data format to use to store historical candle (OHLCV) data. <br> *Defaults to `json`*. <br> **Datatype:** String
|
||||||
| `dataformat_trades` | Data format to use to store historical trades data. <br> *Defaults to `jsongz`*. <br> **Datatype:** String
|
| `dataformat_trades` | Data format to use to store historical trades data. <br> *Defaults to `jsongz`*. <br> **Datatype:** String
|
||||||
| `reduce_df_footprint` | Recast all numeric columns to float32/int32, with the objective of reducing ram/disk usage (and decreasing train/inference timing in FreqAI). (Currently only affects FreqAI use-cases) <br> **Datatype:** Boolean. <br> Default: `False`.
|
|
||||||
|
|
||||||
### Parameters in the strategy
|
### Parameters in the strategy
|
||||||
|
|
||||||
@@ -532,28 +525,21 @@ It means if the order is not executed immediately AND fully then it is cancelled
|
|||||||
It is the same as FOK (above) except it can be partially fulfilled. The remaining part
|
It is the same as FOK (above) except it can be partially fulfilled. The remaining part
|
||||||
is automatically cancelled by the exchange.
|
is automatically cancelled by the exchange.
|
||||||
|
|
||||||
**PO (Post only):**
|
The `order_time_in_force` parameter contains a dict with buy and sell time in force policy values.
|
||||||
|
|
||||||
Post only order. The order is either placed as a maker order, or it is canceled.
|
|
||||||
This means the order must be placed on orderbook for at at least time in an unfilled state.
|
|
||||||
|
|
||||||
#### time_in_force config
|
|
||||||
|
|
||||||
The `order_time_in_force` parameter contains a dict with entry and exit time in force policy values.
|
|
||||||
This can be set in the configuration file or in the strategy.
|
This can be set in the configuration file or in the strategy.
|
||||||
Values set in the configuration file overwrites values set in the strategy.
|
Values set in the configuration file overwrites values set in the strategy.
|
||||||
|
|
||||||
The possible values are: `GTC` (default), `FOK` or `IOC`.
|
The possible values are: `gtc` (default), `fok` or `ioc`.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
"order_time_in_force": {
|
"order_time_in_force": {
|
||||||
"entry": "GTC",
|
"entry": "gtc",
|
||||||
"exit": "GTC"
|
"exit": "gtc"
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
This is ongoing work. For now, it is supported only for binance, gate and kucoin.
|
This is ongoing work. For now, it is supported only for binance and kucoin.
|
||||||
Please don't change the default value unless you know what you are doing and have researched the impact of using different values for your particular exchange.
|
Please don't change the default value unless you know what you are doing and have researched the impact of using different values for your particular exchange.
|
||||||
|
|
||||||
### What values can be used for fiat_display_currency?
|
### What values can be used for fiat_display_currency?
|
||||||
@@ -664,8 +650,17 @@ You should also make sure to read the [Exchanges](exchanges.md) section of the d
|
|||||||
|
|
||||||
### Using proxy with Freqtrade
|
### Using proxy with Freqtrade
|
||||||
|
|
||||||
To use a proxy with freqtrade, export your proxy settings using the variables `"HTTP_PROXY"` and `"HTTPS_PROXY"` set to the appropriate values.
|
To use a proxy with freqtrade, add the kwarg `"aiohttp_trust_env"=true` to the `"ccxt_async_kwargs"` dict in the exchange section of the configuration.
|
||||||
This will have the proxy settings applied to everything (telegram, coingecko, ...) except exchange requests.
|
|
||||||
|
An example for this can be found in `config_examples/config_full.example.json`
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"ccxt_async_config": {
|
||||||
|
"aiohttp_trust_env": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, export your proxy settings using the variables `"HTTP_PROXY"` and `"HTTPS_PROXY"` set to the appropriate values
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
export HTTP_PROXY="http://addr:port"
|
export HTTP_PROXY="http://addr:port"
|
||||||
@@ -673,23 +668,6 @@ export HTTPS_PROXY="http://addr:port"
|
|||||||
freqtrade
|
freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Proxy exchange requests
|
|
||||||
|
|
||||||
To use a proxy for exchange connections - you will have to define the proxies as part of the ccxt configuration.
|
|
||||||
|
|
||||||
``` json
|
|
||||||
{
|
|
||||||
"exchange": {
|
|
||||||
"ccxt_config": {
|
|
||||||
"aiohttp_proxy": "http://addr:port",
|
|
||||||
"proxies": {
|
|
||||||
"http": "http://addr:port",
|
|
||||||
"https": "http://addr:port"
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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).
|
||||||
|
@@ -25,8 +25,9 @@ usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[--include-inactive-pairs]
|
[--include-inactive-pairs]
|
||||||
[--timerange TIMERANGE] [--dl-trades]
|
[--timerange TIMERANGE] [--dl-trades]
|
||||||
[--exchange EXCHANGE]
|
[--exchange EXCHANGE]
|
||||||
[-t TIMEFRAMES [TIMEFRAMES ...]] [--erase]
|
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]
|
||||||
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
[--erase]
|
||||||
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[--data-format-trades {json,jsongz,hdf5}]
|
[--data-format-trades {json,jsongz,hdf5}]
|
||||||
[--trading-mode {spot,margin,futures}]
|
[--trading-mode {spot,margin,futures}]
|
||||||
[--prepend]
|
[--prepend]
|
||||||
@@ -36,8 +37,7 @@ optional arguments:
|
|||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
Limit command to these pairs. Pairs are space-
|
Limit command to these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--pairs-file FILE File containing a list of pairs. Takes precedence over
|
--pairs-file FILE File containing a list of pairs to download.
|
||||||
--pairs or pairs configured in the configuration.
|
|
||||||
--days INT Download data for given number of days.
|
--days INT Download data for given number of days.
|
||||||
--new-pairs-days INT Download data of new pairs for given number of days.
|
--new-pairs-days INT Download data of new pairs for given number of days.
|
||||||
Default: `None`.
|
Default: `None`.
|
||||||
@@ -50,20 +50,20 @@ optional arguments:
|
|||||||
as --timeframes/-t.
|
as --timeframes/-t.
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
config is provided.
|
config is provided.
|
||||||
-t TIMEFRAMES [TIMEFRAMES ...], --timeframes TIMEFRAMES [TIMEFRAMES ...]
|
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]
|
||||||
Specify which tickers to download. Space-separated
|
Specify which tickers to download. Space-separated
|
||||||
list. Default: `1m 5m`.
|
list. Default: `1m 5m`.
|
||||||
--erase Clean all existing data for the selected
|
--erase Clean all existing data for the selected
|
||||||
exchange/pairs/timeframes.
|
exchange/pairs/timeframes.
|
||||||
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
Storage format for downloaded candle (OHLCV) data.
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
(default: `json`).
|
(default: `json`).
|
||||||
--data-format-trades {json,jsongz,hdf5}
|
--data-format-trades {json,jsongz,hdf5}
|
||||||
Storage format for downloaded trades data. (default:
|
Storage format for downloaded trades data. (default:
|
||||||
`jsongz`).
|
`jsongz`).
|
||||||
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
--trading-mode {spot,margin,futures}
|
||||||
Select Trading mode
|
Select Trading mode
|
||||||
--prepend Allow data prepending. (Data-appending is disabled)
|
--prepend Allow data prepending.
|
||||||
|
|
||||||
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).
|
||||||
@@ -76,7 +76,7 @@ Common arguments:
|
|||||||
`userdir/config.json` or `config.json` whichever
|
`userdir/config.json` or `config.json` whichever
|
||||||
exists). Multiple --config options may be used. Can be
|
exists). Multiple --config options may be used. Can be
|
||||||
set to `-` to read config from stdin.
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH, --data-dir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
@@ -177,18 +177,16 @@ freqtrade download-data --exchange binance --pairs ETH/USDT XRP/USDT BTC/USDT --
|
|||||||
|
|
||||||
### Data format
|
### Data format
|
||||||
|
|
||||||
Freqtrade currently supports the following data-formats:
|
Freqtrade currently supports 3 data-formats for both OHLCV and trades data:
|
||||||
|
|
||||||
* `json` - plain "text" json files
|
* `json` (plain "text" json files)
|
||||||
* `jsongz` - a gzip-zipped version of json files
|
* `jsongz` (a gzip-zipped version of json files)
|
||||||
* `hdf5` - a high performance datastore
|
* `hdf5` (a high performance datastore)
|
||||||
* `feather` - a dataformat based on Apache Arrow (OHLCV only)
|
|
||||||
* `parquet` - columnar datastore (OHLCV only)
|
|
||||||
|
|
||||||
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
||||||
|
|
||||||
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
|
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
|
||||||
To persist this change, you should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
||||||
|
|
||||||
``` jsonc
|
``` jsonc
|
||||||
// ...
|
// ...
|
||||||
@@ -202,74 +200,38 @@ If the default data-format has been changed during download, then the keys `data
|
|||||||
!!! Note
|
!!! Note
|
||||||
You can convert between data-formats using the [convert-data](#sub-command-convert-data) and [convert-trade-data](#sub-command-convert-trade-data) methods.
|
You can convert between data-formats using the [convert-data](#sub-command-convert-data) and [convert-trade-data](#sub-command-convert-trade-data) methods.
|
||||||
|
|
||||||
#### Dataformat comparison
|
|
||||||
|
|
||||||
The following comparisons have been made with the following data, and by using the linux `time` command.
|
|
||||||
|
|
||||||
```
|
|
||||||
Found 6 pair / timeframe combinations.
|
|
||||||
+----------+-------------+--------+---------------------+---------------------+
|
|
||||||
| Pair | Timeframe | Type | From | To |
|
|
||||||
|----------+-------------+--------+---------------------+---------------------|
|
|
||||||
| BTC/USDT | 5m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:25:00 |
|
|
||||||
| ETH/USDT | 1m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:26:00 |
|
|
||||||
| BTC/USDT | 1m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:30:00 |
|
|
||||||
| XRP/USDT | 5m | spot | 2018-05-04 08:10:00 | 2022-09-13 19:15:00 |
|
|
||||||
| XRP/USDT | 1m | spot | 2018-05-04 08:11:00 | 2022-09-13 19:22:00 |
|
|
||||||
| ETH/USDT | 5m | spot | 2017-08-17 04:00:00 | 2022-09-13 19:20:00 |
|
|
||||||
+----------+-------------+--------+---------------------+---------------------+
|
|
||||||
```
|
|
||||||
|
|
||||||
Timings have been taken in a not very scientific way with the following command, which forces reading the data into memory.
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
time freqtrade list-data --show-timerange --data-format-ohlcv <dataformat>
|
|
||||||
```
|
|
||||||
|
|
||||||
| Format | Size | timing |
|
|
||||||
|------------|-------------|-------------|
|
|
||||||
| `json` | 149Mb | 25.6s |
|
|
||||||
| `jsongz` | 39Mb | 27s |
|
|
||||||
| `hdf5` | 145Mb | 3.9s |
|
|
||||||
| `feather` | 72Mb | 3.5s |
|
|
||||||
| `parquet` | 83Mb | 3.8s |
|
|
||||||
|
|
||||||
Size has been taken from the BTC/USDT 1m spot combination for the timerange specified above.
|
|
||||||
|
|
||||||
To have a best performance/size mix, we recommend the use of either feather or parquet.
|
|
||||||
|
|
||||||
#### Sub-command convert data
|
#### Sub-command convert data
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH]
|
[-d PATH] [--userdir PATH]
|
||||||
[-p PAIRS [PAIRS ...]] --format-from
|
[-p PAIRS [PAIRS ...]] --format-from
|
||||||
{json,jsongz,hdf5,feather,parquet} --format-to
|
{json,jsongz,hdf5} --format-to
|
||||||
{json,jsongz,hdf5,feather,parquet} [--erase]
|
{json,jsongz,hdf5} [--erase]
|
||||||
|
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]
|
||||||
[--exchange EXCHANGE]
|
[--exchange EXCHANGE]
|
||||||
[-t TIMEFRAMES [TIMEFRAMES ...]]
|
|
||||||
[--trading-mode {spot,margin,futures}]
|
[--trading-mode {spot,margin,futures}]
|
||||||
[--candle-types {spot,futures,mark,index,premiumIndex,funding_rate} [{spot,futures,mark,index,premiumIndex,funding_rate} ...]]
|
[--candle-types {spot,,futures,mark,index,premiumIndex,funding_rate} [{spot,,futures,mark,index,premiumIndex,funding_rate} ...]]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
Limit command to these pairs. Pairs are space-
|
Limit command to these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--format-from {json,jsongz,hdf5,feather,parquet}
|
--format-from {json,jsongz,hdf5}
|
||||||
Source format for data conversion.
|
Source format for data conversion.
|
||||||
--format-to {json,jsongz,hdf5,feather,parquet}
|
--format-to {json,jsongz,hdf5}
|
||||||
Destination format for data conversion.
|
Destination format for data conversion.
|
||||||
--erase Clean all existing data for the selected
|
--erase Clean all existing data for the selected
|
||||||
exchange/pairs/timeframes.
|
exchange/pairs/timeframes.
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]
|
||||||
config is provided.
|
|
||||||
-t TIMEFRAMES [TIMEFRAMES ...], --timeframes TIMEFRAMES [TIMEFRAMES ...]
|
|
||||||
Specify which tickers to download. Space-separated
|
Specify which tickers to download. Space-separated
|
||||||
list. Default: `1m 5m`.
|
list. Default: `1m 5m`.
|
||||||
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
--trading-mode {spot,margin,futures}
|
||||||
Select Trading mode
|
Select Trading mode
|
||||||
--candle-types {spot,futures,mark,index,premiumIndex,funding_rate} [{spot,futures,mark,index,premiumIndex,funding_rate} ...]
|
--candle-types {spot,,futures,mark,index,premiumIndex,funding_rate} [{spot,,futures,mark,index,premiumIndex,funding_rate} ...]
|
||||||
Select candle type to use
|
Select candle type to use
|
||||||
|
|
||||||
Common arguments:
|
Common arguments:
|
||||||
@@ -283,7 +245,7 @@ Common arguments:
|
|||||||
`userdir/config.json` or `config.json` whichever
|
`userdir/config.json` or `config.json` whichever
|
||||||
exists). Multiple --config options may be used. Can be
|
exists). Multiple --config options may be used. Can be
|
||||||
set to `-` to read config from stdin.
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH, --data-dir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
@@ -305,24 +267,20 @@ freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtr
|
|||||||
usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH]
|
[-d PATH] [--userdir PATH]
|
||||||
[-p PAIRS [PAIRS ...]] --format-from
|
[-p PAIRS [PAIRS ...]] --format-from
|
||||||
{json,jsongz,hdf5,feather,parquet}
|
{json,jsongz,hdf5} --format-to
|
||||||
--format-to
|
{json,jsongz,hdf5} [--erase]
|
||||||
{json,jsongz,hdf5,feather,parquet}
|
|
||||||
[--erase] [--exchange EXCHANGE]
|
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
Limit command to these pairs. Pairs are space-
|
Show profits for only these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--format-from {json,jsongz,hdf5,feather,parquet}
|
--format-from {json,jsongz,hdf5}
|
||||||
Source format for data conversion.
|
Source format for data conversion.
|
||||||
--format-to {json,jsongz,hdf5,feather,parquet}
|
--format-to {json,jsongz,hdf5}
|
||||||
Destination format for data conversion.
|
Destination format for data conversion.
|
||||||
--erase Clean all existing data for the selected
|
--erase Clean all existing data for the selected
|
||||||
exchange/pairs/timeframes.
|
exchange/pairs/timeframes.
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
|
||||||
config is provided.
|
|
||||||
|
|
||||||
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).
|
||||||
@@ -335,7 +293,7 @@ Common arguments:
|
|||||||
`userdir/config.json` or `config.json` whichever
|
`userdir/config.json` or `config.json` whichever
|
||||||
exists). Multiple --config options may be used. Can be
|
exists). Multiple --config options may be used. Can be
|
||||||
set to `-` to read config from stdin.
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH, --data-dir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
@@ -360,9 +318,9 @@ This command will allow you to repeat this last step for additional timeframes w
|
|||||||
usage: freqtrade trades-to-ohlcv [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade trades-to-ohlcv [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH]
|
[-d PATH] [--userdir PATH]
|
||||||
[-p PAIRS [PAIRS ...]]
|
[-p PAIRS [PAIRS ...]]
|
||||||
[-t TIMEFRAMES [TIMEFRAMES ...]]
|
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]
|
||||||
[--exchange EXCHANGE]
|
[--exchange EXCHANGE]
|
||||||
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[--data-format-trades {json,jsongz,hdf5}]
|
[--data-format-trades {json,jsongz,hdf5}]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
@@ -370,12 +328,12 @@ optional arguments:
|
|||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
Limit command to these pairs. Pairs are space-
|
Limit command to these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
-t TIMEFRAMES [TIMEFRAMES ...], --timeframes TIMEFRAMES [TIMEFRAMES ...]
|
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]
|
||||||
Specify which tickers to download. Space-separated
|
Specify which tickers to download. Space-separated
|
||||||
list. Default: `1m 5m`.
|
list. Default: `1m 5m`.
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
config is provided.
|
config is provided.
|
||||||
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
Storage format for downloaded candle (OHLCV) data.
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
(default: `json`).
|
(default: `json`).
|
||||||
--data-format-trades {json,jsongz,hdf5}
|
--data-format-trades {json,jsongz,hdf5}
|
||||||
@@ -393,7 +351,7 @@ Common arguments:
|
|||||||
`userdir/config.json` or `config.json` whichever
|
`userdir/config.json` or `config.json` whichever
|
||||||
exists). Multiple --config options may be used. Can be
|
exists). Multiple --config options may be used. Can be
|
||||||
set to `-` to read config from stdin.
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH, --data-dir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
@@ -413,25 +371,22 @@ You can get a list of downloaded data using the `list-data` sub-command.
|
|||||||
```
|
```
|
||||||
usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--userdir PATH] [--exchange EXCHANGE]
|
[--userdir PATH] [--exchange EXCHANGE]
|
||||||
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[-p PAIRS [PAIRS ...]]
|
[-p PAIRS [PAIRS ...]]
|
||||||
[--trading-mode {spot,margin,futures}]
|
[--trading-mode {spot,margin,futures}]
|
||||||
[--show-timerange]
|
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
config is provided.
|
config is provided.
|
||||||
--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
Storage format for downloaded candle (OHLCV) data.
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
(default: `json`).
|
(default: `json`).
|
||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
Limit command to these pairs. Pairs are space-
|
Limit command to these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--trading-mode {spot,margin,futures}, --tradingmode {spot,margin,futures}
|
--trading-mode {spot,margin,futures}
|
||||||
Select Trading mode
|
Select Trading mode
|
||||||
--show-timerange Show timerange available for available data. (May take
|
|
||||||
a while to calculate).
|
|
||||||
|
|
||||||
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).
|
||||||
@@ -444,7 +399,7 @@ Common arguments:
|
|||||||
`userdir/config.json` or `config.json` whichever
|
`userdir/config.json` or `config.json` whichever
|
||||||
exists). Multiple --config options may be used. Can be
|
exists). Multiple --config options may be used. Can be
|
||||||
set to `-` to read config from stdin.
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH, --data-dir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
|
@@ -66,11 +66,11 @@ We will keep a compatibility layer for 1-2 versions (so both `buy_tag` and `ente
|
|||||||
|
|
||||||
#### Naming changes
|
#### Naming changes
|
||||||
|
|
||||||
Webhook terminology changed from "sell" to "exit", and from "buy" to "entry", removing "webhook" in the process.
|
Webhook terminology changed from "sell" to "exit", and from "buy" to "entry".
|
||||||
|
|
||||||
* `webhookbuy`, `webhookentry` -> `entry`
|
* `webhookbuy` -> `webhookentry`
|
||||||
* `webhookbuyfill`, `webhookentryfill` -> `entry_fill`
|
* `webhookbuyfill` -> `webhookentryfill`
|
||||||
* `webhookbuycancel`, `webhookentrycancel` -> `entry_cancel`
|
* `webhookbuycancel` -> `webhookentrycancel`
|
||||||
* `webhooksell`, `webhookexit` -> `exit`
|
* `webhooksell` -> `webhookexit`
|
||||||
* `webhooksellfill`, `webhookexitfill` -> `exit_fill`
|
* `webhooksellfill` -> `webhookexitfill`
|
||||||
* `webhooksellcancel`, `webhookexitcancel` -> `exit_cancel`
|
* `webhooksellcancel` -> `webhookexitcancel`
|
||||||
|
@@ -409,9 +409,8 @@ Determine if crucial bugfixes have been made between this commit and the current
|
|||||||
|
|
||||||
* Merge the release branch (stable) into this branch.
|
* Merge the release branch (stable) into this branch.
|
||||||
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
||||||
* Commit this part.
|
* Commit this part
|
||||||
* push that branch to the remote and create a PR against the stable branch.
|
* push that branch to the remote and create a PR against the stable branch
|
||||||
* Update develop version to next version following the pattern `2019.8-dev`.
|
|
||||||
|
|
||||||
### Create changelog from git commits
|
### Create changelog from git commits
|
||||||
|
|
||||||
@@ -434,11 +433,6 @@ To keep the release-log short, best wrap the full git changelog into a collapsib
|
|||||||
</details>
|
</details>
|
||||||
```
|
```
|
||||||
|
|
||||||
### FreqUI release
|
|
||||||
|
|
||||||
If FreqUI has been updated substantially, make sure to create a release before merging the release branch.
|
|
||||||
Make sure that freqUI CI on the release is finished and passed before merging the release.
|
|
||||||
|
|
||||||
### Create github release / tag
|
### Create github release / tag
|
||||||
|
|
||||||
Once the PR against stable is merged (best right after merging):
|
Once the PR against stable is merged (best right after merging):
|
||||||
|
@@ -57,20 +57,12 @@ This configuration enables kraken, as well as rate-limiting to avoid bans from t
|
|||||||
Binance supports [time_in_force](configuration.md#understand-order_time_in_force).
|
Binance supports [time_in_force](configuration.md#understand-order_time_in_force).
|
||||||
|
|
||||||
!!! Tip "Stoploss on Exchange"
|
!!! Tip "Stoploss on Exchange"
|
||||||
Binance supports `stoploss_on_exchange` and uses `stop-loss-limit` orders. It provides great advantages, so we recommend to benefit from it by enabling stoploss on exchange.
|
Binance supports `stoploss_on_exchange` and uses `stop-loss-limit` orders. It provides great advantages, so we recommend to benefit from it by enabling stoploss on exchange..
|
||||||
On futures, Binance supports both `stop-limit` as well as `stop-market` orders. You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type to use.
|
|
||||||
|
|
||||||
### Binance Blacklist recommendation
|
### Binance Blacklist
|
||||||
|
|
||||||
For Binance, it is suggested to add `"BNB/<STAKE>"` to your blacklist to avoid issues, unless you are willing to maintain enough extra `BNB` on the account or unless you're willing to disable using `BNB` for fees.
|
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
||||||
Binance accounts may use `BNB` for fees, and if a trade happens to be on `BNB`, further trades may consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore.
|
Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on `BNB`, further trades will consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore.
|
||||||
|
|
||||||
### Binance sites
|
|
||||||
|
|
||||||
Binance has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
|
|
||||||
|
|
||||||
* [binance.com](https://www.binance.com/) - International users. Use exchange id: `binance`.
|
|
||||||
* [binance.us](https://www.binance.us/) - US based users. Use exchange id: `binanceus`.
|
|
||||||
|
|
||||||
### Binance Futures
|
### Binance Futures
|
||||||
|
|
||||||
@@ -94,14 +86,12 @@ When trading on Binance Futures market, orderbook must be used because there is
|
|||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Binance futures settings
|
### Binance sites
|
||||||
|
|
||||||
Users will also have to have the futures-setting "Position Mode" set to "One-way Mode", and "Asset Mode" set to "Single-Asset Mode".
|
Binance has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
|
||||||
These settings will be checked on startup, and freqtrade will show an error if this setting is wrong.
|
|
||||||
|
|
||||||

|
* [binance.com](https://www.binance.com/) - International users. Use exchange id: `binance`.
|
||||||
|
* [binance.us](https://www.binance.us/) - US based users. Use exchange id: `binanceus`.
|
||||||
Freqtrade will not attempt to change these settings.
|
|
||||||
|
|
||||||
## Kraken
|
## Kraken
|
||||||
|
|
||||||
@@ -173,6 +163,26 @@ res = [p for p, x in lm.items() if 'US' in x['info']['prohibitedIn']]
|
|||||||
print(res)
|
print(res)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## FTX
|
||||||
|
|
||||||
|
!!! Tip "Stoploss on Exchange"
|
||||||
|
FTX supports `stoploss_on_exchange` and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
|
||||||
|
You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type of stoploss shall be used.
|
||||||
|
|
||||||
|
### Using subaccounts
|
||||||
|
|
||||||
|
To use subaccounts with FTX, you need to edit the configuration and add the following:
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"exchange": {
|
||||||
|
"ccxt_config": {
|
||||||
|
"headers": {
|
||||||
|
"FTX-SUBACCOUNT": "name"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Kucoin
|
## Kucoin
|
||||||
|
|
||||||
Kucoin requires a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows:
|
Kucoin requires a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows:
|
||||||
@@ -195,8 +205,8 @@ Kucoin supports [time_in_force](configuration.md#understand-order_time_in_force)
|
|||||||
|
|
||||||
### Kucoin Blacklists
|
### Kucoin Blacklists
|
||||||
|
|
||||||
For Kucoin, it is suggested to add `"KCS/<STAKE>"` to your blacklist to avoid issues, unless you are willing to maintain enough extra `KCS` on the account or unless you're willing to disable using `KCS` for fees.
|
For Kucoin, please add `"KCS/<STAKE>"` to your blacklist to avoid issues.
|
||||||
Kucoin accounts may use `KCS` for fees, and if a trade happens to be on `KCS`, further trades may consume this position and make the initial `KCS` trade unsellable as the expected amount is not there anymore.
|
Accounts having KCS accounts use this to pay for fees - if your first trade happens to be on `KCS`, further trades will consume this position and make the initial KCS trade unsellable as the expected amount is not there anymore.
|
||||||
|
|
||||||
## Huobi
|
## Huobi
|
||||||
|
|
||||||
@@ -222,7 +232,7 @@ OKX requires a passphrase for each api key, you will therefore need to add this
|
|||||||
|
|
||||||
!!! Warning "Futures"
|
!!! Warning "Futures"
|
||||||
OKX Futures has the concept of "position mode" - which can be Net or long/short (hedge mode).
|
OKX Futures has the concept of "position mode" - which can be Net or long/short (hedge mode).
|
||||||
Freqtrade supports both modes (we recommend to use net mode) - but changing the mode mid-trading is not supported and will lead to exceptions and failures to place trades.
|
Freqtrade supports both modes - but changing the mode mid-trading is not supported and will lead to exceptions and failures to place trades.
|
||||||
OKX also only provides MARK candles for the past ~3 months. Backtesting futures prior to that date will therefore lead to slight deviations, as funding-fees cannot be calculated correctly without this data.
|
OKX also only provides MARK candles for the past ~3 months. Backtesting futures prior to that date will therefore lead to slight deviations, as funding-fees cannot be calculated correctly without this data.
|
||||||
|
|
||||||
## Gate.io
|
## Gate.io
|
||||||
@@ -268,7 +278,7 @@ For example, to test the order type `FOK` with Kraken, and modify candle limit t
|
|||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "kraken",
|
"name": "kraken",
|
||||||
"_ft_has_params": {
|
"_ft_has_params": {
|
||||||
"order_time_in_force": ["GTC", "FOK"],
|
"order_time_in_force": ["gtc", "fok"],
|
||||||
"ohlcv_candle_limit": 200
|
"ohlcv_candle_limit": 200
|
||||||
}
|
}
|
||||||
//...
|
//...
|
||||||
|
37
docs/faq.md
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
Freqtrade supports spot trading only.
|
Freqtrade supports spot trading only.
|
||||||
|
|
||||||
### Can my bot open short positions?
|
### Can I open short positions?
|
||||||
|
|
||||||
Freqtrade can open short positions in futures markets.
|
Freqtrade can open short positions in futures markets.
|
||||||
This requires the strategy to be made for this - and `"trading_mode": "futures"` in the configuration.
|
This requires the strategy to be made for this - and `"trading_mode": "futures"` in the configuration.
|
||||||
@@ -12,9 +12,9 @@ Please make sure to read the [relevant documentation page](leverage.md) first.
|
|||||||
|
|
||||||
In spot markets, you can in some cases use leveraged spot tokens, which reflect an inverted pair (eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD,...) which can be traded with Freqtrade.
|
In spot markets, you can in some cases use leveraged spot tokens, which reflect an inverted pair (eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD,...) which can be traded with Freqtrade.
|
||||||
|
|
||||||
### Can my bot trade options or futures?
|
### Can I trade options or futures?
|
||||||
|
|
||||||
Futures trading is supported for selected exchanges. Please refer to the [documentation start page](index.md#supported-futures-exchanges-experimental) for an uptodate list of supported exchanges.
|
Futures trading is supported for selected exchanges.
|
||||||
|
|
||||||
## Beginner Tips & Tricks
|
## Beginner Tips & Tricks
|
||||||
|
|
||||||
@@ -22,13 +22,6 @@ Futures trading is supported for selected exchanges. Please refer to the [docume
|
|||||||
|
|
||||||
## Freqtrade common issues
|
## Freqtrade common issues
|
||||||
|
|
||||||
### Can freqtrade open multiple positions on the same pair in parallel?
|
|
||||||
|
|
||||||
No. Freqtrade will only open one position per pair at a time.
|
|
||||||
You can however use the [`adjust_trade_position()` callback](strategy-callbacks.md#adjust-trade-position) to adjust an open position.
|
|
||||||
|
|
||||||
Backtesting provides an option for this in `--eps` - however this is only there to highlight "hidden" signals, and will not work in live.
|
|
||||||
|
|
||||||
### The bot does not start
|
### The bot does not start
|
||||||
|
|
||||||
Running the bot with `freqtrade trade --config config.json` shows the output `freqtrade: command not found`.
|
Running the bot with `freqtrade trade --config config.json` shows the output `freqtrade: command not found`.
|
||||||
@@ -37,7 +30,7 @@ This could be caused by the following reasons:
|
|||||||
|
|
||||||
* The virtual environment is not active.
|
* The virtual environment is not active.
|
||||||
* Run `source .env/bin/activate` to activate the virtual environment.
|
* Run `source .env/bin/activate` to activate the virtual environment.
|
||||||
* The installation did not complete successfully.
|
* The installation did not work correctly.
|
||||||
* Please check the [Installation documentation](installation.md).
|
* Please check the [Installation documentation](installation.md).
|
||||||
|
|
||||||
### I have waited 5 minutes, why hasn't the bot made any trades yet?
|
### I have waited 5 minutes, why hasn't the bot made any trades yet?
|
||||||
@@ -74,7 +67,7 @@ This is not a bot-problem, but will also happen while manual trading.
|
|||||||
While freqtrade can handle this (it'll sell 99 COIN), fees are often below the minimum tradable lot-size (you can only trade full COIN, not 0.9 COIN).
|
While freqtrade can handle this (it'll sell 99 COIN), fees are often below the minimum tradable lot-size (you can only trade full COIN, not 0.9 COIN).
|
||||||
Leaving the dust (0.9 COIN) on the exchange makes usually sense, as the next time freqtrade buys COIN, it'll eat into the remaining small balance, this time selling everything it bought, and therefore slowly declining the dust balance (although it most likely will never reach exactly 0).
|
Leaving the dust (0.9 COIN) on the exchange makes usually sense, as the next time freqtrade buys COIN, it'll eat into the remaining small balance, this time selling everything it bought, and therefore slowly declining the dust balance (although it most likely will never reach exactly 0).
|
||||||
|
|
||||||
Where possible (e.g. on binance), the use of the exchange's dedicated fee currency will fix this.
|
Where possible (e.g. on binance), the use of the exchange's dedicated fee currency will fix this.
|
||||||
On binance, it's sufficient to have BNB in your account, and have "Pay fees in BNB" enabled in your profile. Your BNB balance will slowly decline (as it's used to pay fees) - but you'll no longer encounter dust (Freqtrade will include the fees in the profit calculations).
|
On binance, it's sufficient to have BNB in your account, and have "Pay fees in BNB" enabled in your profile. Your BNB balance will slowly decline (as it's used to pay fees) - but you'll no longer encounter dust (Freqtrade will include the fees in the profit calculations).
|
||||||
Other exchanges don't offer such possibilities, where it's simply something you'll have to accept or move to a different exchange.
|
Other exchanges don't offer such possibilities, where it's simply something you'll have to accept or move to a different exchange.
|
||||||
|
|
||||||
@@ -84,9 +77,9 @@ Freqtrade will not provide incomplete candles to strategies. Using incomplete ca
|
|||||||
|
|
||||||
You can use "current" market data by using the [dataprovider](strategy-customization.md#orderbookpair-maximum)'s orderbook or ticker methods - which however cannot be used during backtesting.
|
You can use "current" market data by using the [dataprovider](strategy-customization.md#orderbookpair-maximum)'s orderbook or ticker methods - which however cannot be used during backtesting.
|
||||||
|
|
||||||
### Is there a setting to only Exit the trades being held and not perform any new Entries?
|
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||||
|
|
||||||
You can use the `/stopentry` command in Telegram to prevent future trade entry, followed by `/forceexit all` (sell all open trades).
|
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forceexit all` (sell all open trades).
|
||||||
|
|
||||||
### I want to run multiple bots on the same machine
|
### I want to run multiple bots on the same machine
|
||||||
|
|
||||||
@@ -102,12 +95,6 @@ If this happens for all pairs in the pairlist, this might indicate a recent exch
|
|||||||
|
|
||||||
Irrespectively of the reason, Freqtrade will fill up these candles with "empty" candles, where open, high, low and close are set to the previous candle close - and volume is empty. In a chart, this will look like a `_` - and is aligned with how exchanges usually represent 0 volume candles.
|
Irrespectively of the reason, Freqtrade will fill up these candles with "empty" candles, where open, high, low and close are set to the previous candle close - and volume is empty. In a chart, this will look like a `_` - and is aligned with how exchanges usually represent 0 volume candles.
|
||||||
|
|
||||||
### I'm getting "Price jump between 2 candles detected"
|
|
||||||
|
|
||||||
This message is a warning that the candles had a price jump of > 30%.
|
|
||||||
This might be a sign that the pair stopped trading, and some token exchange took place (e.g. COCOS in 2021 - where price jumped from 0.0000154 to 0.01621).
|
|
||||||
This message is often accompanied by ["Missing data fillup"](#im-getting-missing-data-fillup-messages-in-the-log) - as trading on such pairs is often stopped for some time.
|
|
||||||
|
|
||||||
### I'm getting "Outdated history for pair xxx" in the log
|
### I'm getting "Outdated history for pair xxx" in the log
|
||||||
|
|
||||||
The bot is trying to tell you that it got an outdated last candle (not the last complete candle).
|
The bot is trying to tell you that it got an outdated last candle (not the last complete candle).
|
||||||
@@ -122,7 +109,7 @@ This warning can point to one of the below problems:
|
|||||||
|
|
||||||
### I'm getting the "RESTRICTED_MARKET" message in the log
|
### I'm getting the "RESTRICTED_MARKET" message in the log
|
||||||
|
|
||||||
Currently known to happen for US Bittrex users.
|
Currently known to happen for US Bittrex users.
|
||||||
|
|
||||||
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
||||||
|
|
||||||
@@ -190,8 +177,8 @@ The GPU improvements would only apply to pandas-native calculations - or ones wr
|
|||||||
For hyperopt, freqtrade is using scikit-optimize, which is built on top of scikit-learn.
|
For hyperopt, freqtrade is using scikit-optimize, which is built on top of scikit-learn.
|
||||||
Their statement about GPU support is [pretty clear](https://scikit-learn.org/stable/faq.html#will-you-add-gpu-support).
|
Their statement about GPU support is [pretty clear](https://scikit-learn.org/stable/faq.html#will-you-add-gpu-support).
|
||||||
|
|
||||||
GPU's also are only good at crunching numbers (floating point operations).
|
GPU's also are only good at crunching numbers (floating point operations).
|
||||||
For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting).
|
For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting).
|
||||||
As such, GPU's are not too well suited for most parts of hyperopt.
|
As such, GPU's are not too well suited for most parts of hyperopt.
|
||||||
|
|
||||||
The benefit of using GPU would therefore be pretty slim - and will not justify the complexity introduced by trying to add GPU support.
|
The benefit of using GPU would therefore be pretty slim - and will not justify the complexity introduced by trying to add GPU support.
|
||||||
@@ -232,9 +219,9 @@ already 8\*10^9\*10 evaluations. A roughly total of 80 billion evaluations.
|
|||||||
Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th
|
Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th
|
||||||
of the search space, assuming that the bot never tests the same parameters more than once.
|
of the search space, assuming that the bot never tests the same parameters more than once.
|
||||||
|
|
||||||
* The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 100000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
|
* The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 100000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
|
||||||
|
|
||||||
Example: 4% profit 650 times vs 0,3% profit a trade 10000 times in a year. If we assume you set the --timerange to 365 days.
|
Example: 4% profit 650 times vs 0,3% profit a trade 10000 times in a year. If we assume you set the --timerange to 365 days.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
`freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601`
|
`freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601`
|
||||||
|
@@ -1,244 +0,0 @@
|
|||||||
# Configuration
|
|
||||||
|
|
||||||
FreqAI is configured through the typical [Freqtrade config file](configuration.md) and the standard [Freqtrade strategy](strategy-customization.md). Examples of FreqAI config and strategy files can be found in `config_examples/config_freqai.example.json` and `freqtrade/templates/FreqaiExampleStrategy.py`, respectively.
|
|
||||||
|
|
||||||
## Setting up the configuration file
|
|
||||||
|
|
||||||
Although there are plenty of additional parameters to choose from, as highlighted in the [parameter table](freqai-parameter-table.md#parameter-table), a FreqAI config must at minimum include the following parameters (the parameter values are only examples):
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"enabled": true,
|
|
||||||
"purge_old_models": true,
|
|
||||||
"train_period_days": 30,
|
|
||||||
"backtest_period_days": 7,
|
|
||||||
"identifier" : "unique-id",
|
|
||||||
"feature_parameters" : {
|
|
||||||
"include_timeframes": ["5m","15m","4h"],
|
|
||||||
"include_corr_pairlist": [
|
|
||||||
"ETH/USD",
|
|
||||||
"LINK/USD",
|
|
||||||
"BNB/USD"
|
|
||||||
],
|
|
||||||
"label_period_candles": 24,
|
|
||||||
"include_shifted_candles": 2,
|
|
||||||
"indicator_periods_candles": [10, 20]
|
|
||||||
},
|
|
||||||
"data_split_parameters" : {
|
|
||||||
"test_size": 0.25
|
|
||||||
},
|
|
||||||
"model_training_parameters" : {
|
|
||||||
"n_estimators": 100
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
A full example config is available in `config_examples/config_freqai.example.json`.
|
|
||||||
|
|
||||||
## Building a FreqAI strategy
|
|
||||||
|
|
||||||
The FreqAI strategy requires including the following lines of code in the standard [Freqtrade strategy](strategy-customization.md):
|
|
||||||
|
|
||||||
```python
|
|
||||||
# user should define the maximum startup candle count (the largest number of candles
|
|
||||||
# passed to any single indicator)
|
|
||||||
startup_candle_count: int = 20
|
|
||||||
|
|
||||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
|
|
||||||
# the model will return all labels created by user in `populate_any_indicators`
|
|
||||||
# (& appended targets), an indication of whether or not the prediction should be accepted,
|
|
||||||
# the target mean/std values for each of the labels created by user in
|
|
||||||
# `populate_any_indicators()` for each training period.
|
|
||||||
|
|
||||||
dataframe = self.freqai.start(dataframe, metadata, self)
|
|
||||||
|
|
||||||
return dataframe
|
|
||||||
|
|
||||||
def populate_any_indicators(
|
|
||||||
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Function designed to automatically generate, name and merge features
|
|
||||||
from user indicated timeframes in the configuration file. User controls the indicators
|
|
||||||
passed to the training/prediction by prepending indicators with `'%-' + pair `
|
|
||||||
(see convention below). I.e. user should not prepend any supporting metrics
|
|
||||||
(e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
|
||||||
model.
|
|
||||||
:param pair: pair to be used as informative
|
|
||||||
:param df: strategy dataframe which will receive merges from informatives
|
|
||||||
:param tf: timeframe of the dataframe which will modify the feature names
|
|
||||||
:param informative: the dataframe associated with the informative pair
|
|
||||||
"""
|
|
||||||
|
|
||||||
if informative is None:
|
|
||||||
informative = self.dp.get_pair_dataframe(pair, tf)
|
|
||||||
|
|
||||||
# first loop is automatically duplicating indicators for time periods
|
|
||||||
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
|
||||||
t = int(t)
|
|
||||||
informative[f"%-{pair}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{pair}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{pair}adx-period_{t}"] = ta.ADX(informative, window=t)
|
|
||||||
|
|
||||||
indicators = [col for col in informative if col.startswith("%")]
|
|
||||||
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
|
||||||
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
|
||||||
if n == 0:
|
|
||||||
continue
|
|
||||||
informative_shift = informative[indicators].shift(n)
|
|
||||||
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
|
||||||
informative = pd.concat((informative, informative_shift), axis=1)
|
|
||||||
|
|
||||||
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
|
||||||
skip_columns = [
|
|
||||||
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
|
||||||
]
|
|
||||||
df = df.drop(columns=skip_columns)
|
|
||||||
|
|
||||||
# Add generalized indicators here (because in live, it will call this
|
|
||||||
# function to populate indicators during training). Notice how we ensure not to
|
|
||||||
# add them multiple times
|
|
||||||
if set_generalized_indicators:
|
|
||||||
|
|
||||||
# user adds targets here by prepending them with &- (see convention below)
|
|
||||||
# If user wishes to use multiple targets, a multioutput prediction model
|
|
||||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
|
||||||
df["&-s_close"] = (
|
|
||||||
df["close"]
|
|
||||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.mean()
|
|
||||||
/ df["close"]
|
|
||||||
- 1
|
|
||||||
)
|
|
||||||
|
|
||||||
return df
|
|
||||||
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
Notice how the `populate_any_indicators()` is where [features](freqai-feature-engineering.md#feature-engineering) and labels/targets are added. A full example strategy is available in `templates/FreqaiExampleStrategy.py`.
|
|
||||||
|
|
||||||
Notice also the location of the labels under `if set_generalized_indicators:` at the bottom of the example. This is where single features and labels/targets should be added to the feature set to avoid duplication of them from various configuration parameters that multiply the feature set, such as `include_timeframes`.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
The `self.freqai.start()` function cannot be called outside the `populate_indicators()`.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Features **must** be defined in `populate_any_indicators()`. Defining FreqAI features in `populate_indicators()`
|
|
||||||
will cause the algorithm to fail in live/dry mode. In order to add generalized features that are not associated with a specific pair or timeframe, the following structure inside `populate_any_indicators()` should be used
|
|
||||||
(as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`):
|
|
||||||
|
|
||||||
```python
|
|
||||||
def populate_any_indicators(self, pair, df, tf, informative=None, set_generalized_indicators=False):
|
|
||||||
|
|
||||||
...
|
|
||||||
|
|
||||||
# Add generalized indicators here (because in live, it will call only this function to populate
|
|
||||||
# indicators for retraining). Notice how we ensure not to add them multiple times by associating
|
|
||||||
# these generalized indicators to the basepair/timeframe
|
|
||||||
if set_generalized_indicators:
|
|
||||||
df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7
|
|
||||||
df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25
|
|
||||||
|
|
||||||
# user adds targets here by prepending them with &- (see convention below)
|
|
||||||
# If user wishes to use multiple targets, a multioutput prediction model
|
|
||||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
|
||||||
df["&-s_close"] = (
|
|
||||||
df["close"]
|
|
||||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.mean()
|
|
||||||
/ df["close"]
|
|
||||||
- 1
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`.
|
|
||||||
|
|
||||||
## Important dataframe key patterns
|
|
||||||
|
|
||||||
Below are the values you can expect to include/use inside a typical strategy dataframe (`df[]`):
|
|
||||||
|
|
||||||
| DataFrame Key | Description |
|
|
||||||
|------------|-------------|
|
|
||||||
| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target (label) inside FreqAI (typically following the naming convention `&-s*`). For example, to predict the close price 40 candles into the future, you would set `df['&-s_close'] = df['close'].shift(-self.freqai_info["feature_parameters"]["label_period_candles"])` with `"label_period_candles": 40` in the config. FreqAI makes the predictions and gives them back under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`. <br> **Datatype:** Depends on the output of the model.
|
|
||||||
| `df['&*_std/mean']` | Standard deviation and mean values of the defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand the rarity of a prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` and explained [here](#creating-a-dynamic-target-threshold) to evaluate how often a particular prediction was observed during training or historically with `fit_live_predictions_candles`). <br> **Datatype:** Float.
|
|
||||||
| `df['do_predict']` | Indication of an outlier data point. The return value is integer between -2 and 2, which lets you know if the prediction is trustworthy or not. `do_predict==1` means that the prediction is trustworthy. If the Dissimilarity Index (DI, see details [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di)) of the input data point is above the threshold defined in the config, FreqAI will subtract 1 from `do_predict`, resulting in `do_predict==0`. If `use_SVM_to_remove_outliers()` is active, the Support Vector Machine (SVM, see details [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm)) may also detect outliers in training and prediction data. In this case, the SVM will also subtract 1 from `do_predict`. If the input data point was considered an outlier by the SVM but not by the DI, or vice versa, the result will be `do_predict==0`. If both the DI and the SVM considers the input data point to be an outlier, the result will be `do_predict==-1`. As with the SVM, if `use_DBSCAN_to_remove_outliers` is active, DBSCAN (see details [here](freqai-feature-engineering.md#identifying-outliers-with-dbscan)) may also detect outliers and subtract 1 from `do_predict`. Hence, if both the SVM and DBSCAN are active and identify a datapoint that was above the DI threshold as an outlier, the result will be `do_predict==-2`. A particular case is when `do_predict == 2`, which means that the model has expired due to exceeding `expired_hours`. <br> **Datatype:** Integer between -2 and 2.
|
|
||||||
| `df['DI_values']` | Dissimilarity Index (DI) values are proxies for the level of confidence FreqAI has in the prediction. A lower DI means the prediction is close to the training data, i.e., higher prediction confidence. See details about the DI [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di). <br> **Datatype:** Float.
|
|
||||||
| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature. For example, you can include the RSI in the training feature set (similar to in `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](freqai-feature-engineering.md). <br> **Note:** Since the number of features prepended with `%` can multiply very quickly (10s of thousands of features are easily engineered using the multiplictative functionality of, e.g., `include_shifted_candles` and `include_timeframes` as described in the [parameter table](freqai-parameter-table.md)), these features are removed from the dataframe that is returned from FreqAI to the strategy. To keep a particular type of feature for plotting purposes, you would prepend it with `%%`. <br> **Datatype:** Depends on the output of the model.
|
|
||||||
|
|
||||||
## Setting the `startup_candle_count`
|
|
||||||
|
|
||||||
The `startup_candle_count` in the FreqAI strategy needs to be set up in the same way as in the standard Freqtrade strategy (see details [here](strategy-customization.md#strategy-startup-period)). This value is used by Freqtrade to ensure that a sufficient amount of data is provided when calling the `dataprovider`, to avoid any NaNs at the beginning of the first training. You can easily set this value by identifying the longest period (in candle units) which is passed to the indicator creation functions (e.g., Ta-Lib functions). In the presented example, `startup_candle_count` is 20 since this is the maximum value in `indicators_periods_candles`.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
There are instances where the Ta-Lib functions actually require more data than just the passed `period` or else the feature dataset gets populated with NaNs. Anecdotally, multiplying the `startup_candle_count` by 2 always leads to a fully NaN free training dataset. Hence, it is typically safest to multiply the expected `startup_candle_count` by 2. Look out for this log message to confirm that the data is clean:
|
|
||||||
|
|
||||||
```
|
|
||||||
2022-08-31 15:14:04 - freqtrade.freqai.data_kitchen - INFO - dropped 0 training points due to NaNs in populated dataset 4319.
|
|
||||||
```
|
|
||||||
|
|
||||||
## Creating a dynamic target threshold
|
|
||||||
|
|
||||||
Deciding when to enter or exit a trade can be done in a dynamic way to reflect current market conditions. FreqAI allows you to return additional information from the training of a model (more info [here](freqai-feature-engineering.md#returning-additional-info-from-training)). For example, the `&*_std/mean` return values describe the statistical distribution of the target/label *during the most recent training*. Comparing a given prediction to these values allows you to know the rarity of the prediction. In `templates/FreqaiExampleStrategy.py`, the `target_roi` and `sell_roi` are defined to be 1.25 z-scores away from the mean which causes predictions that are closer to the mean to be filtered out.
|
|
||||||
|
|
||||||
```python
|
|
||||||
dataframe["target_roi"] = dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * 1.25
|
|
||||||
dataframe["sell_roi"] = dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * 1.25
|
|
||||||
```
|
|
||||||
|
|
||||||
To consider the population of *historical predictions* for creating the dynamic target instead of information from the training as discussed above, you would set `fit_live_predictions_candles` in the config to the number of historical prediction candles you wish to use to generate target statistics.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"fit_live_predictions_candles": 300,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
If this value is set, FreqAI will initially use the predictions from the training data and subsequently begin introducing real prediction data as it is generated. FreqAI will save this historical data to be reloaded if you stop and restart a model with the same `identifier`.
|
|
||||||
|
|
||||||
## Using different prediction models
|
|
||||||
|
|
||||||
FreqAI has multiple example prediction model libraries that are ready to be used as is via the flag `--freqaimodel`. These libraries include `CatBoost`, `LightGBM`, and `XGBoost` regression, classification, and multi-target models, and can be found in `freqai/prediction_models/`.
|
|
||||||
|
|
||||||
Regression and classification models differ in what targets they predict - a regression model will predict a target of continuous values, for example what price BTC will be at tomorrow, whilst a classifier will predict a target of discrete values, for example if the price of BTC will go up tomorrow or not. This means that you have to specify your targets differently depending on which model type you are using (see details [below](#setting-model-targets)).
|
|
||||||
|
|
||||||
All of the aforementioned model libraries implement gradient boosted decision tree algorithms. They all work on the principle of ensemble learning, where predictions from multiple simple learners are combined to get a final prediction that is more stable and generalized. The simple learners in this case are decision trees. Gradient boosting refers to the method of learning, where each simple learner is built in sequence - the subsequent learner is used to improve on the error from the previous learner. If you want to learn more about the different model libraries you can find the information in their respective docs:
|
|
||||||
|
|
||||||
* CatBoost: https://catboost.ai/en/docs/
|
|
||||||
* LightGBM: https://lightgbm.readthedocs.io/en/v3.3.2/#
|
|
||||||
* XGBoost: https://xgboost.readthedocs.io/en/stable/#
|
|
||||||
|
|
||||||
There are also numerous online articles describing and comparing the algorithms. Some relatively light-weight examples would be [CatBoost vs. LightGBM vs. XGBoost — Which is the best algorithm?](https://towardsdatascience.com/catboost-vs-lightgbm-vs-xgboost-c80f40662924#:~:text=In%20CatBoost%2C%20symmetric%20trees%2C%20or,the%20same%20depth%20can%20differ.) and [XGBoost, LightGBM or CatBoost — which boosting algorithm should I use?](https://medium.com/riskified-technology/xgboost-lightgbm-or-catboost-which-boosting-algorithm-should-i-use-e7fda7bb36bc). Keep in mind that the performance of each model is highly dependent on the application and so any reported metrics might not be true for your particular use of the model.
|
|
||||||
|
|
||||||
Apart from the models already available in FreqAI, it is also possible to customize and create your own prediction models using the `IFreqaiModel` class. You are encouraged to inherit `fit()`, `train()`, and `predict()` to customize various aspects of the training procedures. You can place custom FreqAI models in `user_data/freqaimodels` - and freqtrade will pick them up from there based on the provided `--freqaimodel` name - which has to correspond to the class name of your custom model.
|
|
||||||
Make sure to use unique names to avoid overriding built-in models.
|
|
||||||
|
|
||||||
### Setting model targets
|
|
||||||
|
|
||||||
#### Regressors
|
|
||||||
|
|
||||||
If you are using a regressor, you need to specify a target that has continuous values. FreqAI includes a variety of regressors, such as the `CatboostRegressor`via the flag `--freqaimodel CatboostRegressor`. An example of how you could set a regression target for predicting the price 100 candles into the future would be
|
|
||||||
|
|
||||||
```python
|
|
||||||
df['&s-close_price'] = df['close'].shift(-100)
|
|
||||||
```
|
|
||||||
|
|
||||||
If you want to predict multiple targets, you need to define multiple labels using the same syntax as shown above.
|
|
||||||
|
|
||||||
#### Classifiers
|
|
||||||
|
|
||||||
If you are using a classifier, you need to specify a target that has discrete values. FreqAI includes a variety of classifiers, such as the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. If you elects to use a classifier, the classes need to be set using strings. For example, if you want to predict if the price 100 candles into the future goes up or down you would set
|
|
||||||
|
|
||||||
```python
|
|
||||||
df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down')
|
|
||||||
```
|
|
||||||
|
|
||||||
If you want to predict multiple targets you must specify all labels in the same label column. You could, for example, add the label `same` to define where the price was unchanged by setting
|
|
||||||
|
|
||||||
```python
|
|
||||||
df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down')
|
|
||||||
df['&s-up_or_down'] = np.where( df["close"].shift(-100) == df["close"], 'same', df['&s-up_or_down'])
|
|
||||||
```
|
|
@@ -1,78 +0,0 @@
|
|||||||
# Development
|
|
||||||
|
|
||||||
## Project architecture
|
|
||||||
|
|
||||||
The architecture and functions of FreqAI are generalized to encourages development of unique features, functions, models, etc.
|
|
||||||
|
|
||||||
The class structure and a detailed algorithmic overview is depicted in the following diagram:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
As shown, there are three distinct objects comprising FreqAI:
|
|
||||||
|
|
||||||
* **IFreqaiModel** - A singular persistent object containing all the necessary logic to collect, store, and process data, engineer features, run training, and inference models.
|
|
||||||
* **FreqaiDataKitchen** - A non-persistent object which is created uniquely for each unique asset/model. Beyond metadata, it also contains a variety of data processing tools.
|
|
||||||
* **FreqaiDataDrawer** - A singular persistent object containing all the historical predictions, models, and save/load methods.
|
|
||||||
|
|
||||||
There are a variety of built-in [prediction models](freqai-configuration.md#using-different-prediction-models) which inherit directly from `IFreqaiModel`. Each of these models have full access to all methods in `IFreqaiModel` and can therefore override any of those functions at will. However, advanced users will likely stick to overriding `fit()`, `train()`, `predict()`, and `data_cleaning_train/predict()`.
|
|
||||||
|
|
||||||
## Data handling
|
|
||||||
|
|
||||||
FreqAI aims to organize model files, prediction data, and meta data in a way that simplifies post-processing and enhances crash resilience by automatic data reloading. The data is saved in a file structure,`user_data_dir/models/`, which contains all the data associated with the trainings and backtests. The `FreqaiDataKitchen()` relies heavily on the file structure for proper training and inferencing and should therefore not be manually modified.
|
|
||||||
|
|
||||||
### File structure
|
|
||||||
|
|
||||||
The file structure is automatically generated based on the model `identifier` set in the [config](freqai-configuration.md#setting-up-the-configuration-file). The following structure shows where the data is stored for post processing:
|
|
||||||
|
|
||||||
| Structure | Description |
|
|
||||||
|-----------|-------------|
|
|
||||||
| `config_*.json` | A copy of the model specific configuration file. |
|
|
||||||
| `historic_predictions.pkl` | A file containing all historic predictions generated during the lifetime of the `identifier` model during live deployment. `historic_predictions.pkl` is used to reload the model after a crash or a config change. A backup file is always held in case of corruption on the main file. FreqAI **automatically** detects corruption and replaces the corrupted file with the backup. |
|
|
||||||
| `pair_dictionary.json` | A file containing the training queue as well as the on disk location of the most recently trained model. |
|
|
||||||
| `sub-train-*_TIMESTAMP` | A folder containing all the files associated with a single model, such as: <br>
|
|
||||||
|| `*_metadata.json` - Metadata for the model, such as normalization max/min, expected training feature list, etc. <br>
|
|
||||||
|| `*_model.*` - The model file saved to disk for reloading from a crash. Can be `joblib` (typical boosting libs), `zip` (stable_baselines), `hd5` (keras type), etc. <br>
|
|
||||||
|| `*_pca_object.pkl` - The [Principal component analysis (PCA)](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis) transform (if `principal_component_analysis: True` is set in the config) which will be used to transform unseen prediction features. <br>
|
|
||||||
|| `*_svm_model.pkl` - The [Support Vector Machine (SVM)](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm) model (if `use_SVM_to_remove_outliers: True` is set in the config) which is used to detect outliers in unseen prediction features. <br>
|
|
||||||
|| `*_trained_df.pkl` - The dataframe containing all the training features used to train the `identifier` model. This is used for computing the [Dissimilarity Index (DI)](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) and can also be used for post-processing. <br>
|
|
||||||
|| `*_trained_dates.df.pkl` - The dates associated with the `trained_df.pkl`, which is useful for post-processing. |
|
|
||||||
|
|
||||||
The example file structure would look like this:
|
|
||||||
|
|
||||||
```
|
|
||||||
├── models
|
|
||||||
│ └── unique-id
|
|
||||||
│ ├── config_freqai.example.json
|
|
||||||
│ ├── historic_predictions.backup.pkl
|
|
||||||
│ ├── historic_predictions.pkl
|
|
||||||
│ ├── pair_dictionary.json
|
|
||||||
│ ├── sub-train-1INCH_1662821319
|
|
||||||
│ │ ├── cb_1inch_1662821319_metadata.json
|
|
||||||
│ │ ├── cb_1inch_1662821319_model.joblib
|
|
||||||
│ │ ├── cb_1inch_1662821319_pca_object.pkl
|
|
||||||
│ │ ├── cb_1inch_1662821319_svm_model.joblib
|
|
||||||
│ │ ├── cb_1inch_1662821319_trained_dates_df.pkl
|
|
||||||
│ │ └── cb_1inch_1662821319_trained_df.pkl
|
|
||||||
│ ├── sub-train-1INCH_1662821371
|
|
||||||
│ │ ├── cb_1inch_1662821371_metadata.json
|
|
||||||
│ │ ├── cb_1inch_1662821371_model.joblib
|
|
||||||
│ │ ├── cb_1inch_1662821371_pca_object.pkl
|
|
||||||
│ │ ├── cb_1inch_1662821371_svm_model.joblib
|
|
||||||
│ │ ├── cb_1inch_1662821371_trained_dates_df.pkl
|
|
||||||
│ │ └── cb_1inch_1662821371_trained_df.pkl
|
|
||||||
│ ├── sub-train-ADA_1662821344
|
|
||||||
│ │ ├── cb_ada_1662821344_metadata.json
|
|
||||||
│ │ ├── cb_ada_1662821344_model.joblib
|
|
||||||
│ │ ├── cb_ada_1662821344_pca_object.pkl
|
|
||||||
│ │ ├── cb_ada_1662821344_svm_model.joblib
|
|
||||||
│ │ ├── cb_ada_1662821344_trained_dates_df.pkl
|
|
||||||
│ │ └── cb_ada_1662821344_trained_df.pkl
|
|
||||||
│ └── sub-train-ADA_1662821399
|
|
||||||
│ ├── cb_ada_1662821399_metadata.json
|
|
||||||
│ ├── cb_ada_1662821399_model.joblib
|
|
||||||
│ ├── cb_ada_1662821399_pca_object.pkl
|
|
||||||
│ ├── cb_ada_1662821399_svm_model.joblib
|
|
||||||
│ ├── cb_ada_1662821399_trained_dates_df.pkl
|
|
||||||
│ └── cb_ada_1662821399_trained_df.pkl
|
|
||||||
|
|
||||||
```
|
|
@@ -1,268 +0,0 @@
|
|||||||
# Feature engineering
|
|
||||||
|
|
||||||
## Defining the features
|
|
||||||
|
|
||||||
Low level feature engineering is performed in the user strategy within a function called `populate_any_indicators()`. That function sets the `base features` such as, `RSI`, `MFI`, `EMA`, `SMA`, time of day, volume, etc. The `base features` can be custom indicators or they can be imported from any technical-analysis library that you can find. One important syntax rule is that all `base features` string names are prepended with `%-{pair}`, while labels/targets are prepended with `&`.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Adding the full pair string, e.g. XYZ/USD, in the feature name enables improved performance for dataframe caching on the backend. If you decide *not* to add the full pair string in the feature string, FreqAI will operate in a reduced performance mode.
|
|
||||||
|
|
||||||
Meanwhile, high level feature engineering is handled within `"feature_parameters":{}` in the FreqAI config. Within this file, it is possible to decide large scale feature expansions on top of the `base_features` such as "including correlated pairs" or "including informative timeframes" or even "including recent candles."
|
|
||||||
|
|
||||||
It is advisable to start from the template `populate_any_indicators()` in the source provided example strategy (found in `templates/FreqaiExampleStrategy.py`) to ensure that the feature definitions are following the correct conventions. Here is an example of how to set the indicators and labels in the strategy:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def populate_any_indicators(
|
|
||||||
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Function designed to automatically generate, name, and merge features
|
|
||||||
from user-indicated timeframes in the configuration file. The user controls the indicators
|
|
||||||
passed to the training/prediction by prepending indicators with `'%-' + pair `
|
|
||||||
(see convention below). I.e., the user should not prepend any supporting metrics
|
|
||||||
(e.g., bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
|
||||||
model.
|
|
||||||
:param pair: pair to be used as informative
|
|
||||||
:param df: strategy dataframe which will receive merges from informatives
|
|
||||||
:param tf: timeframe of the dataframe which will modify the feature names
|
|
||||||
:param informative: the dataframe associated with the informative pair
|
|
||||||
"""
|
|
||||||
|
|
||||||
if informative is None:
|
|
||||||
informative = self.dp.get_pair_dataframe(pair, tf)
|
|
||||||
|
|
||||||
# first loop is automatically duplicating indicators for time periods
|
|
||||||
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
|
||||||
t = int(t)
|
|
||||||
informative[f"%-{pair}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{pair}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{pair}adx-period_{t}"] = ta.ADX(informative, window=t)
|
|
||||||
|
|
||||||
bollinger = qtpylib.bollinger_bands(
|
|
||||||
qtpylib.typical_price(informative), window=t, stds=2.2
|
|
||||||
)
|
|
||||||
informative[f"{pair}bb_lowerband-period_{t}"] = bollinger["lower"]
|
|
||||||
informative[f"{pair}bb_middleband-period_{t}"] = bollinger["mid"]
|
|
||||||
informative[f"{pair}bb_upperband-period_{t}"] = bollinger["upper"]
|
|
||||||
|
|
||||||
informative[f"%-{pair}bb_width-period_{t}"] = (
|
|
||||||
informative[f"{pair}bb_upperband-period_{t}"]
|
|
||||||
- informative[f"{pair}bb_lowerband-period_{t}"]
|
|
||||||
) / informative[f"{pair}bb_middleband-period_{t}"]
|
|
||||||
informative[f"%-{pair}close-bb_lower-period_{t}"] = (
|
|
||||||
informative["close"] / informative[f"{pair}bb_lowerband-period_{t}"]
|
|
||||||
)
|
|
||||||
|
|
||||||
informative[f"%-{pair}relative_volume-period_{t}"] = (
|
|
||||||
informative["volume"] / informative["volume"].rolling(t).mean()
|
|
||||||
)
|
|
||||||
|
|
||||||
indicators = [col for col in informative if col.startswith("%")]
|
|
||||||
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
|
||||||
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
|
||||||
if n == 0:
|
|
||||||
continue
|
|
||||||
informative_shift = informative[indicators].shift(n)
|
|
||||||
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
|
||||||
informative = pd.concat((informative, informative_shift), axis=1)
|
|
||||||
|
|
||||||
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
|
||||||
skip_columns = [
|
|
||||||
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
|
||||||
]
|
|
||||||
df = df.drop(columns=skip_columns)
|
|
||||||
|
|
||||||
# Add generalized indicators here (because in live, it will call this
|
|
||||||
# function to populate indicators during training). Notice how we ensure not to
|
|
||||||
# add them multiple times
|
|
||||||
if set_generalized_indicators:
|
|
||||||
df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7
|
|
||||||
df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25
|
|
||||||
|
|
||||||
# user adds targets here by prepending them with &- (see convention below)
|
|
||||||
# If user wishes to use multiple targets, a multioutput prediction model
|
|
||||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
|
||||||
df["&-s_close"] = (
|
|
||||||
df["close"]
|
|
||||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.mean()
|
|
||||||
/ df["close"]
|
|
||||||
- 1
|
|
||||||
)
|
|
||||||
|
|
||||||
return df
|
|
||||||
```
|
|
||||||
|
|
||||||
In the presented example, the user does not wish to pass the `bb_lowerband` as a feature to the model,
|
|
||||||
and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the
|
|
||||||
model for training/prediction and has therefore prepended it with `%`.
|
|
||||||
|
|
||||||
After having defined the `base features`, the next step is to expand upon them using the powerful `feature_parameters` in the configuration file:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
//...
|
|
||||||
"feature_parameters" : {
|
|
||||||
"include_timeframes": ["5m","15m","4h"],
|
|
||||||
"include_corr_pairlist": [
|
|
||||||
"ETH/USD",
|
|
||||||
"LINK/USD",
|
|
||||||
"BNB/USD"
|
|
||||||
],
|
|
||||||
"label_period_candles": 24,
|
|
||||||
"include_shifted_candles": 2,
|
|
||||||
"indicator_periods_candles": [10, 20]
|
|
||||||
},
|
|
||||||
//...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The `include_timeframes` in the config above are the timeframes (`tf`) of each call to `populate_any_indicators()` in the strategy. In the presented case, the user is asking for the `5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set.
|
|
||||||
|
|
||||||
You can ask for each of the defined features to be included also for informative pairs using the `include_corr_pairlist`. This means that the feature set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of the correlated pairs defined in the config (`ETH/USD`, `LINK/USD`, and `BNB/USD` in the presented example).
|
|
||||||
|
|
||||||
`include_shifted_candles` indicates the number of previous candles to include in the feature set. For example, `include_shifted_candles: 2` tells FreqAI to include the past 2 candles for each of the features in the feature set.
|
|
||||||
|
|
||||||
In total, the number of features the user of the presented example strat has created is: length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
|
||||||
$= 3 * 3 * 3 * 2 * 2 = 108$.
|
|
||||||
|
|
||||||
### Returning additional info from training
|
|
||||||
|
|
||||||
Important metrics can be returned to the strategy at the end of each model training by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside the custom prediction model class.
|
|
||||||
|
|
||||||
FreqAI takes the `my_new_value` assigned in this dictionary and expands it to fit the dataframe that is returned to the strategy. You can then use the returned metrics in your strategy through `dataframe['my_new_value']`. An example of how return values can be used in FreqAI are the `&*_mean` and `&*_std` values that are used to [created a dynamic target threshold](freqai-configuration.md#creating-a-dynamic-target-threshold).
|
|
||||||
|
|
||||||
Another example, where the user wants to use live metrics from the trade database, is shown below:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"extra_returns_per_train": {"total_profit": 4}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
You need to set the standard dictionary in the config so that FreqAI can return proper dataframe shapes. These values will likely be overridden by the prediction model, but in the case where the model has yet to set them, or needs a default initial value, the pre-set values are what will be returned.
|
|
||||||
|
|
||||||
## Feature normalization
|
|
||||||
|
|
||||||
FreqAI is strict when it comes to data normalization. The train features, $X^{train}$, are always normalized to [-1, 1] using a shifted min-max normalization:
|
|
||||||
|
|
||||||
$$X^{train}_{norm} = 2 * \frac{X^{train} - X^{train}.min()}{X^{train}.max() - X^{train}.min()} - 1$$
|
|
||||||
|
|
||||||
All other data (test data and unseen prediction data in dry/live/backtest) is always automatically normalized to the training feature space according to industry standards. FreqAI stores all the metadata required to ensure that test and prediction features will be properly normalized and that predictions are properly denormalized. For this reason, it is not recommended to eschew industry standards and modify FreqAI internals - however - advanced users can do so by inheriting `train()` in their custom `IFreqaiModel` and using their own normalization functions.
|
|
||||||
|
|
||||||
## Data dimensionality reduction with Principal Component Analysis
|
|
||||||
|
|
||||||
You can reduce the dimensionality of your features by activating the `principal_component_analysis` in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"principal_component_analysis": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This will perform PCA on the features and reduce their dimensionality so that the explained variance of the data set is >= 0.999. Reducing data dimensionality makes training the model faster and hence allows for more up-to-date models.
|
|
||||||
|
|
||||||
## Inlier metric
|
|
||||||
|
|
||||||
The `inlier_metric` is a metric aimed at quantifying how similar a the features of a data point are to the most recent historic data points.
|
|
||||||
|
|
||||||
You define the lookback window by setting `inlier_metric_window` and FreqAI computes the distance between the present time point and each of the previous `inlier_metric_window` lookback points. A Weibull function is fit to each of the lookback distributions and its cumulative distribution function (CDF) is used to produce a quantile for each lookback point. The `inlier_metric` is then computed for each time point as the average of the corresponding lookback quantiles. The figure below explains the concept for an `inlier_metric_window` of 5.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
FreqAI adds the `inlier_metric` to the training features and hence gives the model access to a novel type of temporal information.
|
|
||||||
|
|
||||||
This function does **not** remove outliers from the data set.
|
|
||||||
|
|
||||||
## Weighting features for temporal importance
|
|
||||||
|
|
||||||
FreqAI allows you to set a `weight_factor` to weight recent data more strongly than past data via an exponential function:
|
|
||||||
|
|
||||||
$$ W_i = \exp(\frac{-i}{\alpha*n}) $$
|
|
||||||
|
|
||||||
where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. Below is a figure showing the effect of different weight factors on the data points in a feature set.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Outlier detection
|
|
||||||
|
|
||||||
Equity and crypto markets suffer from a high level of non-patterned noise in the form of outlier data points. FreqAI implements a variety of methods to identify such outliers and hence mitigate risk.
|
|
||||||
|
|
||||||
### Identifying outliers with the Dissimilarity Index (DI)
|
|
||||||
|
|
||||||
The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each prediction made by the model.
|
|
||||||
|
|
||||||
You can tell FreqAI to remove outlier data points from the training/test data sets using the DI by including the following statement in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"DI_threshold": 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The DI allows predictions which are outliers (not existent in the model feature space) to be thrown out due to low levels of certainty. To do so, FreqAI measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points:
|
|
||||||
|
|
||||||
$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$
|
|
||||||
|
|
||||||
where $d_{ab}$ is the distance between the normalized points $a$ and $b$, and $p$ is the number of features, i.e., the length of the vector $X$. The characteristic distance, $\overline{d}$, for a set of training data points is simply the mean of the average distances:
|
|
||||||
|
|
||||||
$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$
|
|
||||||
|
|
||||||
$\overline{d}$ quantifies the spread of the training data, which is compared to the distance between a new prediction feature vectors, $X_k$ and all the training data:
|
|
||||||
|
|
||||||
$$ d_k = \arg \min d_{k,i} $$
|
|
||||||
|
|
||||||
This enables the estimation of the Dissimilarity Index as:
|
|
||||||
|
|
||||||
$$ DI_k = d_k/\overline{d} $$
|
|
||||||
|
|
||||||
You can tweak the DI through the `DI_threshold` to increase or decrease the extrapolation of the trained model. A higher `DI_threshold` means that the DI is more lenient and allows predictions further away from the training data to be used whilst a lower `DI_threshold` has the opposite effect and hence discards more predictions.
|
|
||||||
|
|
||||||
Below is a figure that describes the DI for a 3D data set.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
### Identifying outliers using a Support Vector Machine (SVM)
|
|
||||||
|
|
||||||
You can tell FreqAI to remove outlier data points from the training/test data sets using a Support Vector Machine (SVM) by including the following statement in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"use_SVM_to_remove_outliers": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The SVM will be trained on the training data and any data point that the SVM deems to be beyond the feature space will be removed.
|
|
||||||
|
|
||||||
FreqAI uses `sklearn.linear_model.SGDOneClassSVM` (details are available on scikit-learn's webpage [here](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDOneClassSVM.html) (external website)) and you can elect to provide additional parameters for the SVM, such as `shuffle`, and `nu`.
|
|
||||||
|
|
||||||
The parameter `shuffle` is by default set to `False` to ensure consistent results. If it is set to `True`, running the SVM multiple times on the same data set might result in different outcomes due to `max_iter` being to low for the algorithm to reach the demanded `tol`. Increasing `max_iter` solves this issue but causes the procedure to take longer time.
|
|
||||||
|
|
||||||
The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers and should be between 0 and 1.
|
|
||||||
|
|
||||||
### Identifying outliers with DBSCAN
|
|
||||||
|
|
||||||
You can configure FreqAI to use DBSCAN to cluster and remove outliers from the training/test data set or incoming outliers from predictions, by activating `use_DBSCAN_to_remove_outliers` in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"use_DBSCAN_to_remove_outliers": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
DBSCAN is an unsupervised machine learning algorithm that clusters data without needing to know how many clusters there should be.
|
|
||||||
|
|
||||||
Given a number of data points $N$, and a distance $\varepsilon$, DBSCAN clusters the data set by setting all data points that have $N-1$ other data points within a distance of $\varepsilon$ as *core points*. A data point that is within a distance of $\varepsilon$ from a *core point* but that does not have $N-1$ other data points within a distance of $\varepsilon$ from itself is considered an *edge point*. A cluster is then the collection of *core points* and *edge points*. Data points that have no other data points at a distance $<\varepsilon$ are considered outliers. The figure below shows a cluster with $N = 3$.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
FreqAI uses `sklearn.cluster.DBSCAN` (details are available on scikit-learn's webpage [here](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html) (external website)) with `min_samples` ($N$) taken as 1/4 of the no. of time points (candles) in the feature set. `eps` ($\varepsilon$) is computed automatically as the elbow point in the *k-distance graph* computed from the nearest neighbors in the pairwise distances of all data points in the feature set.
|
|
@@ -1,53 +0,0 @@
|
|||||||
# Parameter table
|
|
||||||
|
|
||||||
The table below will list all configuration parameters available for FreqAI. Some of the parameters are exemplified in `config_examples/config_freqai.example.json`.
|
|
||||||
|
|
||||||
Mandatory parameters are marked as **Required** and have to be set in one of the suggested ways.
|
|
||||||
|
|
||||||
| Parameter | Description |
|
|
||||||
|------------|-------------|
|
|
||||||
| | **General configuration parameters**
|
|
||||||
| `freqai` | **Required.** <br> The parent dictionary containing all the parameters for controlling FreqAI. <br> **Datatype:** Dictionary.
|
|
||||||
| `train_period_days` | **Required.** <br> Number of days to use for the training data (width of the sliding window). <br> **Datatype:** Positive integer.
|
|
||||||
| `backtest_period_days` | **Required.** <br> Number of days to inference from the trained model before sliding the `train_period_days` window defined above, and retraining the model during backtesting (more info [here](freqai-running.md#backtesting)). This can be fractional days, but beware that the provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float.
|
|
||||||
| `identifier` | **Required.** <br> A unique ID for the current model. If models are saved to disk, the `identifier` allows for reloading specific pre-trained models/data. <br> **Datatype:** String.
|
|
||||||
| `live_retrain_hours` | Frequency of retraining during dry/live runs. <br> **Datatype:** Float > 0. <br> Default: `0` (models retrain as often as possible).
|
|
||||||
| `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old. <br> **Datatype:** Positive integer. <br> Default: `0` (models never expire).
|
|
||||||
| `purge_old_models` | Delete obsolete models. <br> **Datatype:** Boolean. <br> Default: `False` (all historic models remain on disk).
|
|
||||||
| `save_backtest_models` | Save models to disk when running backtesting. Backtesting operates most efficiently by saving the prediction data and reusing them directly for subsequent runs (when you wish to tune entry/exit parameters). Saving backtesting models to disk also allows to use the same model files for starting a dry/live instance with the same model `identifier`. <br> **Datatype:** Boolean. <br> Default: `False` (no models are saved).
|
|
||||||
| `fit_live_predictions_candles` | Number of historical candles to use for computing target (label) statistics from prediction data, instead of from the training dataset (more information can be found [here](freqai-configuration.md#creating-a-dynamic-target-threshold)). <br> **Datatype:** Positive integer.
|
|
||||||
| `follow_mode` | Use a `follower` that will look for models associated with a specific `identifier` and load those for inferencing. A `follower` will **not** train new models. <br> **Datatype:** Boolean. <br> Default: `False`.
|
|
||||||
| `continual_learning` | Use the final state of the most recently trained model as starting point for the new model, allowing for incremental learning (more information can be found [here](freqai-running.md#continual-learning)). <br> **Datatype:** Boolean. <br> Default: `False`.
|
|
||||||
| `write_metrics_to_disk` | Collect train timings, inference timings and cpu usage in json file. <br> **Datatype:** Boolean. <br> Default: `False`
|
|
||||||
| | **Feature parameters**
|
|
||||||
| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples are shown [here](freqai-feature-engineering.md). <br> **Datatype:** Dictionary.
|
|
||||||
| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for. The list is added as features to the base indicators dataset. <br> **Datatype:** List of timeframes (strings).
|
|
||||||
| `include_corr_pairlist` | A list of correlated coins that FreqAI will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` during feature engineering (see details [here](freqai-feature-engineering.md)) will be created for each correlated coin. The correlated coins features are added to the base indicators dataset. <br> **Datatype:** List of assets (strings).
|
|
||||||
| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators` (see `templates/FreqaiExampleStrategy.py` for detailed usage). You can create custom labels and choose whether to make use of this parameter or not. <br> **Datatype:** Positive integer.
|
|
||||||
| `include_shifted_candles` | Add features from previous candles to subsequent candles with the intent of adding historical information. If used, FreqAI will duplicate and shift all features from the `include_shifted_candles` previous candles so that the information is available for the subsequent candle. <br> **Datatype:** Positive integer.
|
|
||||||
| `weight_factor` | Weight training data points according to their recency (see details [here](freqai-feature-engineering.md#weighting-features-for-temporal-importance)). <br> **Datatype:** Positive float (typically < 1).
|
|
||||||
| `indicator_max_period_candles` | **No longer used (#7325)**. Replaced by `startup_candle_count` which is set in the [strategy](freqai-configuration.md#building-a-freqai-strategy). `startup_candle_count` is timeframe independent and defines the maximum *period* used in `populate_any_indicators()` for indicator creation. FreqAI uses this parameter together with the maximum timeframe in `include_time_frames` to calculate how many data points to download such that the first data point does not include a NaN. <br> **Datatype:** Positive integer.
|
|
||||||
| `indicator_periods_candles` | Time periods to calculate indicators for. The indicators are added to the base indicator dataset. <br> **Datatype:** List of positive integers.
|
|
||||||
| `principal_component_analysis` | Automatically reduce the dimensionality of the data set using Principal Component Analysis. See details about how it works [here](#reducing-data-dimensionality-with-principal-component-analysis) <br> **Datatype:** Boolean. <br> Default: `False`.
|
|
||||||
| `plot_feature_importances` | Create a feature importance plot for each model for the top/bottom `plot_feature_importances` number of features. <br> **Datatype:** Integer. <br> Default: `0`.
|
|
||||||
| `DI_threshold` | Activates the use of the Dissimilarity Index for outlier detection when set to > 0. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di). <br> **Datatype:** Positive float (typically < 1).
|
|
||||||
| `use_SVM_to_remove_outliers` | Train a support vector machine to detect and remove outliers from the training dataset, as well as from incoming data points. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Boolean.
|
|
||||||
| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. See details about some select parameters [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Dictionary.
|
|
||||||
| `use_DBSCAN_to_remove_outliers` | Cluster data using the DBSCAN algorithm to identify and remove outliers from training and prediction data. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-with-dbscan). <br> **Datatype:** Boolean.
|
|
||||||
| `inlier_metric_window` | If set, FreqAI adds an `inlier_metric` to the training feature set and set the lookback to be the `inlier_metric_window`, i.e., the number of previous time points to compare the current candle to. Details of how the `inlier_metric` is computed can be found [here](freqai-feature-engineering.md#inlier-metric). <br> **Datatype:** Integer. <br> Default: `0`.
|
|
||||||
| `noise_standard_deviation` | If set, FreqAI adds noise to the training features with the aim of preventing overfitting. FreqAI generates random deviates from a gaussian distribution with a standard deviation of `noise_standard_deviation` and adds them to all data points. `noise_standard_deviation` should be kept relative to the normalized space, i.e., between -1 and 1. In other words, since data in FreqAI is always normalized to be between -1 and 1, `noise_standard_deviation: 0.05` would result in 32% of the data being randomly increased/decreased by more than 2.5% (i.e., the percent of data falling within the first standard deviation). <br> **Datatype:** Integer. <br> Default: `0`.
|
|
||||||
| `outlier_protection_percentage` | Enable to prevent outlier detection methods from discarding too much data. If more than `outlier_protection_percentage` % of points are detected as outliers by the SVM or DBSCAN, FreqAI will log a warning message and ignore outlier detection, i.e., the original dataset will be kept intact. If the outlier protection is triggered, no predictions will be made based on the training dataset. <br> **Datatype:** Float. <br> Default: `30`.
|
|
||||||
| `reverse_train_test_order` | Split the feature dataset (see below) and use the latest data split for training and test on historical split of the data. This allows the model to be trained up to the most recent data point, while avoiding overfitting. However, you should be careful to understand the unorthodox nature of this parameter before employing it. <br> **Datatype:** Boolean. <br> Default: `False` (no reversal).
|
|
||||||
| | **Data split parameters**
|
|
||||||
| `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website). <br> **Datatype:** Dictionary.
|
|
||||||
| `test_size` | The fraction of data that should be used for testing instead of training. <br> **Datatype:** Positive float < 1.
|
|
||||||
| `shuffle` | Shuffle the training data points during training. Typically, to not remove the chronological order of data in time-series forecasting, this is set to `False`. <br> **Datatype:** Boolean. <br> Defaut: `False`.
|
|
||||||
| | **Model training parameters**
|
|
||||||
| `model_training_parameters` | A flexible dictionary that includes all parameters available by the selected model library. For example, if you use `LightGBMRegressor`, this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html) (external website). If you select a different model, this dictionary can contain any parameter from that model. A list of the currently available models can be found [here](freqai-configuration.md#using-different-prediction-models). <br> **Datatype:** Dictionary.
|
|
||||||
| `n_estimators` | The number of boosted trees to fit in the training of the model. <br> **Datatype:** Integer.
|
|
||||||
| `learning_rate` | Boosting learning rate during training of the model. <br> **Datatype:** Float.
|
|
||||||
| `n_jobs`, `thread_count`, `task_type` | Set the number of threads for parallel processing and the `task_type` (`gpu` or `cpu`). Different model libraries use different parameter names. <br> **Datatype:** Float.
|
|
||||||
| | **Extraneous parameters**
|
|
||||||
| `keras` | If the selected model makes use of Keras (typical for Tensorflow-based prediction models), this flag needs to be activated so that the model save/loading follows Keras standards. <br> **Datatype:** Boolean. <br> Default: `False`.
|
|
||||||
| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for shifting candles (`include_shifted_candles`) by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction. <br> **Datatype:** Integer. <br> Default: `2`.
|
|
||||||
| `reduce_df_footprint` | Recast all numeric columns to float32/int32, with the objective of reducing ram/disk usage and decreasing train/inference timing. This parameter is set in the main level of the Freqtrade configuration file (not inside FreqAI). <br> **Datatype:** Boolean. <br> Default: `False`.
|
|
@@ -1,185 +0,0 @@
|
|||||||
# Running FreqAI
|
|
||||||
|
|
||||||
There are two ways to train and deploy an adaptive machine learning model - live deployment and historical backtesting. In both cases, FreqAI runs/simulates periodic retraining of models as shown in the following figure:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Live deployments
|
|
||||||
|
|
||||||
FreqAI can be run dry/live using the following command:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade trade --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor
|
|
||||||
```
|
|
||||||
|
|
||||||
When launched, FreqAI will start training a new model, with a new `identifier`, based on the config settings. Following training, the model will be used to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the coin pairs to try to keep all models equally up to date. FreqAI will always use the most recently trained model to make predictions on incoming live data. If you do not want FreqAI to retrain new models as often as possible, you can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before training a new model. Additionally, you can set `expired_hours` to tell FreqAI to avoid making predictions on models that are older than that number of hours.
|
|
||||||
|
|
||||||
Trained models are by default saved to disk to allow for reuse during backtesting or after a crash. You can opt to [purge old models](#purging-old-model-data) to save disk space by setting `"purge_old_models": true` in the config.
|
|
||||||
|
|
||||||
To start a dry/live run from a saved backtest model (or from a previously crashed dry/live session), you only need to specify the `identifier` of the specific model:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"identifier": "example",
|
|
||||||
"live_retrain_hours": 0.5
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In this case, although FreqAI will initiate with a pre-trained model, it will still check to see how much time has elapsed since the model was trained. If a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will start training a new model.
|
|
||||||
|
|
||||||
### Automatic data download
|
|
||||||
|
|
||||||
FreqAI automatically downloads the proper amount of data needed to ensure training of a model through the defined `train_period_days` and `startup_candle_count` (see the [parameter table](freqai-parameter-table.md) for detailed descriptions of these parameters).
|
|
||||||
|
|
||||||
### Saving prediction data
|
|
||||||
|
|
||||||
All predictions made during the lifetime of a specific `identifier` model are stored in `historic_predictions.pkl` to allow for reloading after a crash or changes made to the config.
|
|
||||||
|
|
||||||
### Purging old model data
|
|
||||||
|
|
||||||
FreqAI stores new model files after each successful training. These files become obsolete as new models are generated to adapt to new market conditions. If you are planning to leave FreqAI running for extended periods of time with high frequency retraining, you should enable `purge_old_models` in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"purge_old_models": true,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This will automatically purge all models older than the two most recently trained ones to save disk space.
|
|
||||||
|
|
||||||
## Backtesting
|
|
||||||
|
|
||||||
The FreqAI backtesting module can be executed with the following command:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade backtesting --strategy FreqaiExampleStrategy --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701
|
|
||||||
```
|
|
||||||
|
|
||||||
If this command has never been executed with the existing config file, FreqAI will train a new model
|
|
||||||
for each pair, for each backtesting window within the expanded `--timerange`.
|
|
||||||
|
|
||||||
Backtesting mode requires [downloading the necessary data](#downloading-data-to-cover-the-full-backtest-period) before deployment (unlike in dry/live mode where FreqAI handles the data downloading automatically). You should be careful to consider that the time range of the downloaded data is more than the backtesting time range. This is because FreqAI needs data prior to the desired backtesting time range in order to train a model to be ready to make predictions on the first candle of the set backtesting time range. More details on how to calculate the data to download can be found [here](#deciding-the-size-of-the-sliding-training-window-and-backtesting-duration).
|
|
||||||
|
|
||||||
!!! Note "Model reuse"
|
|
||||||
Once the training is completed, you can execute the backtesting again with the same config file and
|
|
||||||
FreqAI will find the trained models and load them instead of spending time training. This is useful
|
|
||||||
if you want to tweak (or even hyperopt) buy and sell criteria inside the strategy. If you
|
|
||||||
*want* to retrain a new model with the same config file, you should simply change the `identifier`.
|
|
||||||
This way, you can return to using any model you wish by simply specifying the `identifier`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Saving prediction data
|
|
||||||
|
|
||||||
To allow for tweaking your strategy (**not** the features!), FreqAI will automatically save the predictions during backtesting so that they can be reused for future backtests and live runs using the same `identifier` model. This provides a performance enhancement geared towards enabling **high-level hyperopting** of entry/exit criteria.
|
|
||||||
|
|
||||||
An additional directory called `backtesting_predictions`, which contains all the predictions stored in `hdf` format, will be created in the `unique-id` folder.
|
|
||||||
|
|
||||||
To change your **features**, you **must** set a new `identifier` in the config to signal to FreqAI to train new models.
|
|
||||||
|
|
||||||
To save the models generated during a particular backtest so that you can start a live deployment from one of them instead of training a new model, you must set `save_backtest_models` to `True` in the config.
|
|
||||||
|
|
||||||
### Backtest live models
|
|
||||||
|
|
||||||
FreqAI allow you to reuse ready models through the backtest parameter `--freqai-backtest-live-models`. This can be useful when you want to reuse models generated in dry/run for comparison or other study. For that, you must set `"purge_old_models"` to `True` in the config.
|
|
||||||
|
|
||||||
The `--timerange` parameter must not be informed, as it will be automatically calculated through the training end dates of the models.
|
|
||||||
|
|
||||||
Each model has an identifier derived from the training end date. If you have only 1 model trained, FreqAI will backtest from the training end date until the current date. If you have more than 1 model, each model will perform the backtesting according to the training end date until the training end date of the next model and so on. For the last model, the period of the previous model will be used for the execution.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Currently, there is no checking for expired models, even if the `expired_hours` parameter is set.
|
|
||||||
|
|
||||||
|
|
||||||
### Downloading data to cover the full backtest period
|
|
||||||
|
|
||||||
For live/dry deployments, FreqAI will download the necessary data automatically. However, to use backtesting functionality, you need to download the necessary data using `download-data` (details [here](data-download.md#data-downloading)). You need to pay careful attention to understanding how much *additional* data needs to be downloaded to ensure that there is a sufficient amount of training data *before* the start of the backtesting time range. The amount of additional data can be roughly estimated by moving the start date of the time range backwards by `train_period_days` and the `startup_candle_count` (see the [parameter table](freqai-parameter-table.md) for detailed descriptions of these parameters) from the beginning of the desired backtesting time range.
|
|
||||||
|
|
||||||
As an example, to backtest the `--timerange 20210501-20210701` using the [example config](freqai-configuration.md#setting-up-the-configuration-file) which sets `train_period_days` to 30, together with `startup_candle_count: 40` on a maximum `include_timeframes` of 1h, the start date for the downloaded data needs to be `20210501` - 30 days - 40 * 1h / 24 hours = 20210330 (31.7 days earlier than the start of the desired training time range).
|
|
||||||
|
|
||||||
### Deciding the size of the sliding training window and backtesting duration
|
|
||||||
|
|
||||||
The backtesting time range is defined with the typical `--timerange` parameter in the configuration file. The duration of the sliding training window is set by `train_period_days`, whilst `backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be
|
|
||||||
a float to indicate sub-daily retraining in live/dry mode). In the presented [example config](freqai-configuration.md#setting-up-the-configuration-file) (found in `config_examples/config_freqai.example.json`), the user is asking FreqAI to use a training period of 30 days and backtest on the subsequent 7 days. After the training of the model, FreqAI will backtest the subsequent 7 days. The "sliding window" then moves one week forward (emulating FreqAI retraining once per week in live mode) and the new model uses the previous 30 days (including the 7 days used for backtesting by the previous model) to train. This is repeated until the end of `--timerange`. This means that if you set `--timerange 20210501-20210701`, FreqAI will have trained 8 separate models at the end of `--timerange` (because the full range comprises 8 weeks).
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Although fractional `backtest_period_days` is allowed, you should be aware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, by setting a `--timerange` of 10 days, and a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. Because of this, a true backtest of FreqAI adaptive training would take a *very* long time. The best way to fully test a model is to run it dry and let it train constantly. In this case, backtesting would take the exact same amount of time as a dry run.
|
|
||||||
|
|
||||||
## Defining model expirations
|
|
||||||
|
|
||||||
During dry/live mode, FreqAI trains each coin pair sequentially (on separate threads/GPU from the main Freqtrade bot). This means that there is always an age discrepancy between models. If you are training on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old. This may be undesirable if the characteristic time scale (the trade duration target) for a strategy is less than 4 hours. You can decide to only make trade entries if the model is less than a certain number of hours old by setting the `expiration_hours` in the config file:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"expiration_hours": 0.5,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In the presented example config, the user will only allow predictions on models that are less than 1/2 hours old.
|
|
||||||
|
|
||||||
## Controlling the model learning process
|
|
||||||
|
|
||||||
Model training parameters are unique to the selected machine learning library. FreqAI allows you to set any parameter for any library using the `model_training_parameters` dictionary in the config. The example config (found in `config_examples/config_freqai.example.json`) shows some of the example parameters associated with `Catboost` and `LightGBM`, but you can add any parameters available in those libraries or any other machine learning library you choose to implement.
|
|
||||||
|
|
||||||
Data split parameters are defined in `data_split_parameters` which can be any parameters associated with Scikit-learn's `train_test_split()` function. `train_test_split()` has a parameters called `shuffle` which allows to shuffle the data or keep it unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data. More details about these parameters can be found the [Scikit-learn website](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website).
|
|
||||||
|
|
||||||
The FreqAI specific parameter `label_period_candles` defines the offset (number of candles into the future) used for the `labels`. In the presented [example config](freqai-configuration.md#setting-up-the-configuration-file), the user is asking for `labels` that are 24 candles in the future.
|
|
||||||
|
|
||||||
## Continual learning
|
|
||||||
|
|
||||||
You can choose to adopt a continual learning scheme by setting `"continual_learning": true` in the config. By enabling `continual_learning`, after training an initial model from scratch, subsequent trainings will start from the final model state of the preceding training. This gives the new model a "memory" of the previous state. By default, this is set to `False` which means that all new models are trained from scratch, without input from previous models.
|
|
||||||
|
|
||||||
## Hyperopt
|
|
||||||
|
|
||||||
You can hyperopt using the same command as for [typical Freqtrade hyperopt](hyperopt.md):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade hyperopt --hyperopt-loss SharpeHyperOptLoss --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --timerange 20220428-20220507
|
|
||||||
```
|
|
||||||
|
|
||||||
`hyperopt` requires you to have the data pre-downloaded in the same fashion as if you were doing [backtesting](#backtesting). In addition, you must consider some restrictions when trying to hyperopt FreqAI strategies:
|
|
||||||
|
|
||||||
- The `--analyze-per-epoch` hyperopt parameter is not compatible with FreqAI.
|
|
||||||
- It's not possible to hyperopt indicators in the `populate_any_indicators()` function. This means that you cannot optimize model parameters using hyperopt. Apart from this exception, it is possible to optimize all other [spaces](hyperopt.md#running-hyperopt-with-smaller-search-space).
|
|
||||||
- The backtesting instructions also apply to hyperopt.
|
|
||||||
|
|
||||||
The best method for combining hyperopt and FreqAI is to focus on hyperopting entry/exit thresholds/criteria. You need to focus on hyperopting parameters that are not used in your features. For example, you should not try to hyperopt rolling window lengths in the feature creation, or any part of the FreqAI config which changes predictions. In order to efficiently hyperopt the FreqAI strategy, FreqAI stores predictions as dataframes and reuses them. Hence the requirement to hyperopt entry/exit thresholds/criteria only.
|
|
||||||
|
|
||||||
A good example of a hyperoptable parameter in FreqAI is a threshold for the [Dissimilarity Index (DI)](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) `DI_values` beyond which we consider data points as outliers:
|
|
||||||
|
|
||||||
```python
|
|
||||||
di_max = IntParameter(low=1, high=20, default=10, space='buy', optimize=True, load=True)
|
|
||||||
dataframe['outlier'] = np.where(dataframe['DI_values'] > self.di_max.value/10, 1, 0)
|
|
||||||
```
|
|
||||||
|
|
||||||
This specific hyperopt would help you understand the appropriate `DI_values` for your particular parameter space.
|
|
||||||
|
|
||||||
## Using Tensorboard
|
|
||||||
|
|
||||||
CatBoost models benefit from tracking training metrics via Tensorboard. You can take advantage of the FreqAI integration to track training and evaluation performance across all coins and across all retrainings. Tensorboard is activated via the following command:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd freqtrade
|
|
||||||
tensorboard --logdir user_data/models/unique-id
|
|
||||||
```
|
|
||||||
|
|
||||||
where `unique-id` is the `identifier` set in the `freqai` configuration file. This command must be run in a separate shell if you wish to view the output in your browser at 127.0.0.1:6060 (6060 is the default port used by Tensorboard).
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Setting up a follower
|
|
||||||
|
|
||||||
You can indicate to the bot that it should not train models, but instead should look for models trained by a leader with a specific `identifier` by defining:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"enabled": true,
|
|
||||||
"follow_mode": true,
|
|
||||||
"identifier": "example",
|
|
||||||
"feature_parameters": {
|
|
||||||
// leader bots feature_parameters inserted here
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In this example, the user has a leader bot with the `"identifier": "example"`. The leader bot is already running or is launched simultaneously with the follower. The follower will load models created by the leader and inference them to obtain predictions instead of training its own models. The user will also need to duplicate the `feature_parameters` parameters from from the leaders freqai configuration file into the freqai section of the followers config.
|
|
759
docs/freqai.md
@@ -2,103 +2,768 @@
|
|||||||
|
|
||||||
# FreqAI
|
# FreqAI
|
||||||
|
|
||||||
## Introduction
|
FreqAI is a module designed to automate a variety of tasks associated with training a predictive model to generate market forecasts given a set of input features.
|
||||||
|
|
||||||
FreqAI is a software designed to automate a variety of tasks associated with training a predictive machine learning model to generate market forecasts given a set of input signals. In general, the FreqAI aims to be a sand-box for easily deploying robust machine-learning libraries on real-time data ([details])(#freqai-position-in-open-source-machine-learning-landscape).
|
Among the the features included:
|
||||||
|
|
||||||
Features include:
|
* **Self-adaptive retraining**: retrain models during live deployments to self-adapt to the market in an unsupervised manner.
|
||||||
|
* **Rapid feature engineering**: create large rich feature sets (10k+ features) based on simple user created strategies.
|
||||||
* **Self-adaptive retraining** - Retrain models during [live deployments](freqai-running.md#live-deployments) to self-adapt to the market in a supervised manner
|
* **High performance**: adaptive retraining occurs on separate thread (or on GPU if available) from inferencing and bot trade operations. Keep newest models and data in memory for rapid inferencing.
|
||||||
* **Rapid feature engineering** - Create large rich [feature sets](freqai-feature-engineering.md#feature-engineering) (10k+ features) based on simple user-created strategies
|
* **Realistic backtesting**: emulate self-adaptive retraining with backtesting module that automates past retraining.
|
||||||
* **High performance** - Threading allows for adaptive model retraining on a separate thread (or on GPU if available) from model inferencing (prediction) and bot trade operations. Newest models and data are kept in RAM for rapid inferencing
|
* **Modifiable**: use the generalized and robust architecture for incorporating any machine learning library/method available in Python. Seven examples available.
|
||||||
* **Realistic backtesting** - Emulate self-adaptive training on historic data with a [backtesting module](freqai-running.md#backtesting) that automates retraining
|
* **Smart outlier removal**: remove outliers from training and prediction sets using a variety of outlier detection techniques.
|
||||||
* **Extensibility** - The generalized and robust architecture allows for incorporating any [machine learning library/method](freqai-configuration.md#using-different-prediction-models) available in Python. Eight examples are currently available, including classifiers, regressors, and a convolutional neural network
|
* **Crash resilience**: model storage to disk to make reloading from a crash fast and easy (and purge obsolete files for sustained dry/live runs).
|
||||||
* **Smart outlier removal** - Remove outliers from training and prediction data sets using a variety of [outlier detection techniques](freqai-feature-engineering.md#outlier-detection)
|
* **Automated data normalization**: normalize the data in a smart and statistically safe way.
|
||||||
* **Crash resilience** - Store trained models to disk to make reloading from a crash fast and easy, and [purge obsolete files](freqai-running.md#purging-old-model-data) for sustained dry/live runs
|
* **Automatic data download**: compute the data download timerange and update historic data (in live deployments).
|
||||||
* **Automatic data normalization** - [Normalize the data](freqai-feature-engineering.md#feature-normalization) in a smart and statistically safe way
|
* **Clean incoming data** safe NaN handling before training and prediction.
|
||||||
* **Automatic data download** - Compute timeranges for data downloads and update historic data (in live deployments)
|
* **Dimensionality reduction**: reduce the size of the training data via Principal Component Analysis.
|
||||||
* **Cleaning of incoming data** - Handle NaNs safely before training and model inferencing
|
* **Deploy bot fleets**: set one bot to train models while a fleet of other bots inference into the models and handle trades.
|
||||||
* **Dimensionality reduction** - Reduce the size of the training data via [Principal Component Analysis](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis)
|
|
||||||
* **Deploying bot fleets** - Set one bot to train models while a fleet of [follower bots](freqai-running.md#setting-up-a-follower) inference the models and handle trades
|
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
The easiest way to quickly test FreqAI is to run it in dry mode with the following command:
|
The easiest way to quickly test FreqAI is to run it in dry run with the following command
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade trade --config config_examples/config_freqai.example.json --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates
|
freqtrade trade --config config_examples/config_freqai.example.json --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates
|
||||||
```
|
```
|
||||||
|
|
||||||
You will see the boot-up process of automatic data downloading, followed by simultaneous training and trading.
|
where the user will see the boot-up process of auto-data downloading, followed by simultaneous training and trading.
|
||||||
|
|
||||||
An example strategy, prediction model, and config to use as a starting points can be found in
|
The example strategy, example prediction model, and example config can all be found in
|
||||||
`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`, and
|
`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`,
|
||||||
`config_examples/config_freqai.example.json`, respectively.
|
`config_examples/config_freqai.example.json`, respectively.
|
||||||
|
|
||||||
## General approach
|
## General approach
|
||||||
|
|
||||||
You provide FreqAI with a set of custom *base indicators* (the same way as in a [typical Freqtrade strategy](strategy-customization.md)) as well as target values (*labels*). For each pair in the whitelist, FreqAI trains a model to predict the target values based on the input of custom indicators. The models are then consistently retrained, with a predetermined frequency, to adapt to market conditions. FreqAI offers the ability to both backtest strategies (emulating reality with periodic retraining on historic data) and deploy dry/live runs. In dry/live conditions, FreqAI can be set to constant retraining in a background thread to keep models as up to date as possible.
|
The user provides FreqAI with a set of custom *base* indicators (created inside the strategy the same way
|
||||||
|
a typical Freqtrade strategy is created) as well as target values which look into the future.
|
||||||
|
FreqAI trains a model to predict the target value based on the input of custom indicators for each pair in the whitelist. These models are consistently retrained to adapt to market conditions. FreqAI offers the ability to both backtest strategies (emulating reality with periodic retraining) and deploy dry/live. In dry/live conditions, FreqAI can be set to constant retraining in a background thread in an effort to keep models as young as possible.
|
||||||
|
|
||||||
An overview of the algorithm, explaining the data processing pipeline and model usage, is shown below.
|
An overview of the algorithm is shown here to help users understand the data processing pipeline and the model usage.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
### Important machine learning vocabulary
|
## Background and vocabulary
|
||||||
|
|
||||||
**Features** - the parameters, based on historic data, on which a model is trained. All features for a single candle are stored as a vector. In FreqAI, you build a feature data set from anything you can construct in the strategy.
|
**Features** are the quantities with which a model is trained. $X_i$ represents the
|
||||||
|
vector of all features for a single candle. In FreqAI, the user
|
||||||
|
builds the features from anything they can construct in the strategy.
|
||||||
|
|
||||||
**Labels** - the target values that the model is trained toward. Each feature vector is associated with a single label that is defined by you within the strategy. These labels intentionally look into the future and are what you are training the model to be able to predict.
|
**Labels** are the target values with which the weights inside a model are trained
|
||||||
|
toward. Each set of features is associated with a single label, which is also
|
||||||
|
defined within the strategy by the user. These labels intentionally look into the
|
||||||
|
future, and are not available to the model during dryrun/live/backtesting.
|
||||||
|
|
||||||
**Training** - the process of "teaching" the model to match the feature sets to the associated labels. Different types of models "learn" in different ways which means that one might be better than another for a specific application. More information about the different models that are already implemented in FreqAI can be found [here](freqai-configuration.md#using-different-prediction-models).
|
**Training** refers to the process of feeding individual feature sets into the
|
||||||
|
model with associated labels with the goal of matching input feature sets to associated labels.
|
||||||
|
|
||||||
**Train data** - a subset of the feature data set that is fed to the model during training to "teach" the model how to predict the targets. This data directly influences weight connections in the model.
|
**Train data** is a subset of the historic data which is fed to the model during
|
||||||
|
training to adjust weights. This data directly influences weight connections in the model.
|
||||||
|
|
||||||
**Test data** - a subset of the feature data set that is used to evaluate the performance of the model after training. This data does not influence nodal weights within the model.
|
**Test data** is a subset of the historic data which is used to evaluate the
|
||||||
|
intermediate performance of the model during training. This data does not
|
||||||
**Inferencing** - the process of feeding a trained model new unseen data on which it will make a prediction.
|
directly influence nodal weights within the model.
|
||||||
|
|
||||||
## Install prerequisites
|
## Install prerequisites
|
||||||
|
|
||||||
The normal Freqtrade install process will ask if you wish to install FreqAI dependencies. You should reply "yes" to this question if you wish to use FreqAI. If you did not reply yes, you can manually install these dependencies after the install with:
|
The normal Freqtrade install process will ask the user if they wish to install FreqAI dependencies. The user should reply "yes" to this question if they wish to use FreqAI. If the user did not reply yes, they can manually install these dependencies after the install with:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
pip install -r requirements-freqai.txt
|
pip install -r requirements-freqai.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Catboost will not be installed on arm devices (raspberry, Mac M1, ARM based VPS, ...), since it does not provide wheels for this platform.
|
Catboost will not be installed on arm devices (raspberry, Mac M1, ARM based VPS, ...), since Catboost does not provide wheels for this platform.
|
||||||
|
|
||||||
### Usage with docker
|
### Usage with docker
|
||||||
|
|
||||||
If you are using docker, a dedicated tag with FreqAI dependencies is available as `:freqai`. As such - you can replace the image line in your docker-compose file with `image: freqtradeorg/freqtrade:develop_freqai`. This image contains the regular FreqAI dependencies. Similar to native installs, Catboost will not be available on ARM based devices.
|
For docker users, a dedicated tag with freqAI dependencies is available as `:freqai`.
|
||||||
|
As such - you can replace the image line in your docker-compose file with `image: freqtradeorg/freqtrade:develop_freqai`.
|
||||||
|
This image contains the regular freqAI dependencies. Similar to native installs, Catboost will not be available on ARM based devices.
|
||||||
|
|
||||||
|
## Configuring FreqAI
|
||||||
|
|
||||||
|
### Parameter table
|
||||||
|
|
||||||
|
The table below will list all configuration parameters available for FreqAI.
|
||||||
|
|
||||||
|
Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways.
|
||||||
|
|
||||||
|
| Parameter | Description |
|
||||||
|
|------------|-------------|
|
||||||
|
| `freqai` | **Required.** The parent dictionary containing all the parameters below for controlling FreqAI. <br> **Datatype:** dictionary.
|
||||||
|
| `identifier` | **Required.** A unique name for the current model. This can be reused to reload pre-trained models/data. <br> **Datatype:** string.
|
||||||
|
| `train_period_days` | **Required.** Number of days to use for the training data (width of the sliding window). <br> **Datatype:** positive integer.
|
||||||
|
| `backtest_period_days` | **Required.** Number of days to inference into the trained model before sliding the window and retraining. This can be fractional days, but beware that the user provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float.
|
||||||
|
| `live_retrain_hours` | Frequency of retraining during dry/live runs. Default set to 0, which means it will retrain as often as possible. <br> **Datatype:** Float > 0.
|
||||||
|
| `follow_mode` | If true, this instance of FreqAI will look for models associated with `identifier` and load those for inferencing. A `follower` will **not** train new models. `False` by default. <br> **Datatype:** boolean.
|
||||||
|
| `startup_candles` | Number of candles needed for *backtesting only* to ensure all indicators are non NaNs at the start of the first train period. <br> **Datatype:** positive integer.
|
||||||
|
| `fit_live_predictions_candles` | Computes target (label) statistics from prediction data, instead of from the training data set. Number of candles is the number of historical candles it uses to generate the statistics. <br> **Datatype:** positive integer.
|
||||||
|
| `purge_old_models` | Tell FreqAI to delete obsolete models. Otherwise, all historic models will remain on disk. Defaults to `False`. <br> **Datatype:** boolean.
|
||||||
|
| `expiration_hours` | Ask FreqAI to avoid making predictions if a model is more than `expiration_hours` old. Defaults to 0 which means models never expire. <br> **Datatype:** positive integer.
|
||||||
|
| | **Feature Parameters**
|
||||||
|
| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples shown [here](#feature-engineering) <br> **Datatype:** dictionary.
|
||||||
|
| `include_corr_pairlist` | A list of correlated coins that FreqAI will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` will be created for each coin in this list, and that set of features is added to the base asset feature set. <br> **Datatype:** list of assets (strings).
|
||||||
|
| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for and added as features to the base asset feature set. <br> **Datatype:** list of timeframes (strings).
|
||||||
|
| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators`, refer to `templates/FreqaiExampleStrategy.py` for detailed usage. The user can create custom labels, making use of this parameter not. <br> **Datatype:** positive integer.
|
||||||
|
| `include_shifted_candles` | Parameter used to add a sense of temporal recency to flattened regression type input data. `include_shifted_candles` takes all features, duplicates and shifts them by the number indicated by user. <br> **Datatype:** positive integer.
|
||||||
|
| `DI_threshold` | Activates the Dissimilarity Index for outlier detection when above 0, explained in detail [here](#removing-outliers-with-the-dissimilarity-index). <br> **Datatype:** positive float (typically below 1).
|
||||||
|
| `weight_factor` | Used to set weights for training data points according to their recency, see details and a figure of how it works [here](#controlling-the-model-learning-process). <br> **Datatype:** positive float (typically below 1).
|
||||||
|
| `principal_component_analysis` | Ask FreqAI to automatically reduce the dimensionality of the data set using PCA. <br> **Datatype:** boolean.
|
||||||
|
| `use_SVM_to_remove_outliers` | Ask FreqAI to train a support vector machine to detect and remove outliers from the training data set as well as from incoming data points. <br> **Datatype:** boolean.
|
||||||
|
| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. E.g. `nu` *Very* broadly, is the percentage of data points that should be considered outliers. `shuffle` is by default false to maintain reproducibility. But these and all others can be added/changed in this dictionary. <br> **Datatype:** dictionary.
|
||||||
|
| `stratify_training_data` | This value is used to indicate the stratification of the data. e.g. 2 would set every 2nd data point into a separate dataset to be pulled from during training/testing. <br> **Datatype:** positive integer.
|
||||||
|
| `indicator_max_period_candles` | The maximum *period* used in `populate_any_indicators()` for indicator creation. FreqAI uses this information in combination with the maximum timeframe to calculate how many data points it should download so that the first data point does not have a NaN <br> **Datatype:** positive integer.
|
||||||
|
| `indicator_periods_candles` | A list of integers used to duplicate all indicators according to a set of periods and add them to the feature set. <br> **Datatype:** list of positive integers.
|
||||||
|
| `use_DBSCAN_to_remove_outliers` | Inactive by default. If true, FreqAI clusters data using DBSCAN to identify and remove outliers from training and prediction data. <br> **Datatype:** float (fraction of 1).
|
||||||
|
| | **Data split parameters**
|
||||||
|
| `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) <br> **Datatype:** dictionary.
|
||||||
|
| `test_size` | Fraction of data that should be used for testing instead of training. <br> **Datatype:** positive float below 1.
|
||||||
|
| `shuffle` | Shuffle the training data points during training. Typically for time-series forecasting, this is set to False. <br> **Datatype:** boolean.
|
||||||
|
| | **Model training parameters**
|
||||||
|
| `model_training_parameters` | A flexible dictionary that includes all parameters available by the user selected library. For example, if the user uses `LightGBMRegressor`, then this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html). If the user selects a different model, then this dictionary can contain any parameter from that different model. <br> **Datatype:** dictionary.
|
||||||
|
| `n_estimators` | A common parameter among regressors which sets the number of boosted trees to fit <br> **Datatype:** integer.
|
||||||
|
| `learning_rate` | A common parameter among regressors which sets the boosting learning rate. <br> **Datatype:** float.
|
||||||
|
| `n_jobs`, `thread_count`, `task_type` | Different libraries use different parameter names to control the number of threads used for parallel processing or whether or not it is a `task_type` of `gpu` or `cpu`. <br> **Datatype:** float.
|
||||||
|
| | **Extraneous parameters**
|
||||||
|
| `keras` | If your model makes use of keras (typical of Tensorflow based prediction models), activate this flag so that the model save/loading follows keras standards. Default value `false` <br> **Datatype:** boolean.
|
||||||
|
| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for `shift` by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction. Default value, 2 <br> **Datatype:** integer.
|
||||||
|
|
||||||
|
### Important FreqAI dataframe key patterns
|
||||||
|
|
||||||
|
Here are the values the user can expect to include/use inside the typical strategy dataframe (`df[]`):
|
||||||
|
|
||||||
|
| DataFrame Key | Description |
|
||||||
|
|------------|-------------|
|
||||||
|
| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target inside FreqAI (typically following the naming convention `&-s*`). These same dataframe columns names are fed back to the user as the predictions. For example, the user wishes to predict the price change in the next 40 candles (similar to `templates/FreqaiExampleStrategy.py`) by setting `df['&-s_close']`. FreqAI makes the predictions and gives them back to the user under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`. <br> **Datatype:** depends on the output of the model.
|
||||||
|
| `df['&*_std/mean']` | The standard deviation and mean values of the user defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand rarity of prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` to evaluate how often a particular prediction was observed during training (or historically with `fit_live_predictions_candles`)<br> **Datatype:** float.
|
||||||
|
| `df['do_predict']` | An indication of an outlier, this return value is integer between -1 and 2 which lets the user understand if the prediction is trustworthy or not. `do_predict==1` means the prediction is trustworthy. If the [Dissimilarity Index](#removing-outliers-with-the-dissimilarity-index) is above the user defined threshold, it will subtract 1 from `do_predict`. If `use_SVM_to_remove_outliers()` is active, then the Support Vector Machine (SVM) may also detect outliers in training and prediction data. In this case, the SVM will also subtract one from `do_predict`. A particular case is when `do_predict == 2`, it means that the model has expired due to `expired_hours`. <br> **Datatype:** integer between -1 and 2.
|
||||||
|
| `df['DI_values']` | The raw Dissimilarity Index values to give the user a sense of confidence in the prediction. Lower DI means the data point is closer to the trained parameter space. <br> **Datatype:** float.
|
||||||
|
| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature inside FreqAI. For example, the user can include the rsi in the training feature set (similar to `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](#building-the-feature-set). <br>**Note**: since the number of features prepended with `%` can multiply very quickly (10s of thousands of features is easily engineered using the multiplictative functionality described in the `feature_parameters` table.) these features are removed from the dataframe upon return from FreqAI. If the user wishes to keep a particular type of feature for plotting purposes, you can prepend it with `%%`. <br> **Datatype:** depends on the output of the model.
|
||||||
|
|
||||||
|
### Example config file
|
||||||
|
|
||||||
|
The user interface is isolated to the typical config file. A typical FreqAI config setup could include:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"startup_candles": 10000,
|
||||||
|
"purge_old_models": true,
|
||||||
|
"train_period_days": 30,
|
||||||
|
"backtest_period_days": 7,
|
||||||
|
"identifier" : "unique-id",
|
||||||
|
"feature_parameters" : {
|
||||||
|
"include_timeframes": ["5m","15m","4h"],
|
||||||
|
"include_corr_pairlist": [
|
||||||
|
"ETH/USD",
|
||||||
|
"LINK/USD",
|
||||||
|
"BNB/USD"
|
||||||
|
],
|
||||||
|
"label_period_candles": 24,
|
||||||
|
"include_shifted_candles": 2,
|
||||||
|
"weight_factor": 0,
|
||||||
|
"indicator_max_period_candles": 20,
|
||||||
|
"indicator_periods_candles": [10, 20]
|
||||||
|
},
|
||||||
|
"data_split_parameters" : {
|
||||||
|
"test_size": 0.25,
|
||||||
|
"random_state": 42
|
||||||
|
},
|
||||||
|
"model_training_parameters" : {
|
||||||
|
"n_estimators": 100,
|
||||||
|
"random_state": 42,
|
||||||
|
"learning_rate": 0.02,
|
||||||
|
"task_type": "CPU",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Feature engineering
|
||||||
|
|
||||||
|
Features are added by the user inside the `populate_any_indicators()` method of the strategy
|
||||||
|
by prepending indicators with `%` and labels are added by prepending `&`.
|
||||||
|
There are some important components/structures that the user *must* include when building their feature set.
|
||||||
|
Another structure to consider is the location of the labels at the bottom of the example function (below `if set_generalized_indicators:`).
|
||||||
|
This is where the user will add single features and labels to their feature set to avoid duplication from
|
||||||
|
various configuration parameters which multiply the feature set such as `include_timeframes`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def populate_any_indicators(
|
||||||
|
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Function designed to automatically generate, name and merge features
|
||||||
|
from user indicated timeframes in the configuration file. User controls the indicators
|
||||||
|
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
||||||
|
(see convention below). I.e. user should not prepend any supporting metrics
|
||||||
|
(e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
||||||
|
model.
|
||||||
|
:param pair: pair to be used as informative
|
||||||
|
:param df: strategy dataframe which will receive merges from informatives
|
||||||
|
:param tf: timeframe of the dataframe which will modify the feature names
|
||||||
|
:param informative: the dataframe associated with the informative pair
|
||||||
|
:param coin: the name of the coin which will modify the feature names.
|
||||||
|
"""
|
||||||
|
|
||||||
|
coint = pair.split('/')[0]
|
||||||
|
|
||||||
|
if informative is None:
|
||||||
|
informative = self.dp.get_pair_dataframe(pair, tf)
|
||||||
|
|
||||||
|
# first loop is automatically duplicating indicators for time periods
|
||||||
|
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
||||||
|
t = int(t)
|
||||||
|
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
||||||
|
|
||||||
|
bollinger = qtpylib.bollinger_bands(
|
||||||
|
qtpylib.typical_price(informative), window=t, stds=2.2
|
||||||
|
)
|
||||||
|
informative[f"{coin}bb_lowerband-period_{t}"] = bollinger["lower"]
|
||||||
|
informative[f"{coin}bb_middleband-period_{t}"] = bollinger["mid"]
|
||||||
|
informative[f"{coin}bb_upperband-period_{t}"] = bollinger["upper"]
|
||||||
|
|
||||||
|
informative[f"%-{coin}bb_width-period_{t}"] = (
|
||||||
|
informative[f"{coin}bb_upperband-period_{t}"]
|
||||||
|
- informative[f"{coin}bb_lowerband-period_{t}"]
|
||||||
|
) / informative[f"{coin}bb_middleband-period_{t}"]
|
||||||
|
informative[f"%-{coin}close-bb_lower-period_{t}"] = (
|
||||||
|
informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"]
|
||||||
|
)
|
||||||
|
|
||||||
|
informative[f"%-{coin}relative_volume-period_{t}"] = (
|
||||||
|
informative["volume"] / informative["volume"].rolling(t).mean()
|
||||||
|
)
|
||||||
|
|
||||||
|
indicators = [col for col in informative if col.startswith("%")]
|
||||||
|
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
||||||
|
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
||||||
|
if n == 0:
|
||||||
|
continue
|
||||||
|
informative_shift = informative[indicators].shift(n)
|
||||||
|
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
||||||
|
informative = pd.concat((informative, informative_shift), axis=1)
|
||||||
|
|
||||||
|
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
||||||
|
skip_columns = [
|
||||||
|
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
||||||
|
]
|
||||||
|
df = df.drop(columns=skip_columns)
|
||||||
|
|
||||||
|
# Add generalized indicators here (because in live, it will call this
|
||||||
|
# function to populate indicators during training). Notice how we ensure not to
|
||||||
|
# add them multiple times
|
||||||
|
if set_generalized_indicators:
|
||||||
|
df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7
|
||||||
|
df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25
|
||||||
|
|
||||||
|
# user adds targets here by prepending them with &- (see convention below)
|
||||||
|
# If user wishes to use multiple targets, a multioutput prediction model
|
||||||
|
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||||
|
df["&-s_close"] = (
|
||||||
|
df["close"]
|
||||||
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.mean()
|
||||||
|
/ df["close"]
|
||||||
|
- 1
|
||||||
|
)
|
||||||
|
|
||||||
|
return df
|
||||||
|
```
|
||||||
|
|
||||||
|
The user of the present example does not wish to pass the `bb_lowerband` as a feature to the model,
|
||||||
|
and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the
|
||||||
|
model for training/prediction and has therefore prepended it with `%`.
|
||||||
|
|
||||||
|
The `include_timeframes` from the example config above are the timeframes (`tf`) of each call to `populate_any_indicators()`
|
||||||
|
included metric for inclusion in the feature set. In the present case, the user is asking for the
|
||||||
|
`5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set.
|
||||||
|
|
||||||
|
In addition, the user can ask for each of these features to be included from
|
||||||
|
informative pairs using the `include_corr_pairlist`. This means that the present feature
|
||||||
|
set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of
|
||||||
|
`ETH/USD`, `LINK/USD`, and `BNB/USD`.
|
||||||
|
|
||||||
|
`include_shifted_candles` is another user controlled parameter which indicates the number of previous
|
||||||
|
candles to include in the present feature set. In other words, `include_shifted_candles: 2`, tells
|
||||||
|
FreqAI to include the the past 2 candles for each of the features included in the dataset.
|
||||||
|
|
||||||
|
In total, the number of features the present user has created is:
|
||||||
|
|
||||||
|
length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
||||||
|
$3 * 3 * 3 * 2 * 2 = 108$.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Features **must** be defined in `populate_any_indicators()`. Making features in `populate_indicators()`
|
||||||
|
will fail in live/dry mode. If the user wishes to add generalized features that are not associated with
|
||||||
|
a specific pair or timeframe, they should use the following structure inside `populate_any_indicators()`
|
||||||
|
(as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False):
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
# Add generalized indicators here (because in live, it will call only this function to populate
|
||||||
|
# indicators for retraining). Notice how we ensure not to add them multiple times by associating
|
||||||
|
# these generalized indicators to the basepair/timeframe
|
||||||
|
if set_generalized_indicators:
|
||||||
|
df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7
|
||||||
|
df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25
|
||||||
|
|
||||||
|
# user adds targets here by prepending them with &- (see convention below)
|
||||||
|
# If user wishes to use multiple targets, a multioutput prediction model
|
||||||
|
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||||
|
df["&-s_close"] = (
|
||||||
|
df["close"]
|
||||||
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.mean()
|
||||||
|
/ df["close"]
|
||||||
|
- 1
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
(Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`)
|
||||||
|
|
||||||
|
### Deciding the sliding training window and backtesting duration
|
||||||
|
|
||||||
|
Users define the backtesting timerange with the typical `--timerange` parameter in the user
|
||||||
|
configuration file. `train_period_days` is the duration of the sliding training window, while
|
||||||
|
`backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be
|
||||||
|
a float to indicate sub daily retraining in live/dry mode). In the present example,
|
||||||
|
the user is asking FreqAI to use a training period of 30 days and backtest the subsequent 7 days.
|
||||||
|
This means that if the user sets `--timerange 20210501-20210701`,
|
||||||
|
FreqAI will train 8 separate models (because the full range comprises 8 weeks),
|
||||||
|
and then backtest the subsequent week associated with each of the 8 training
|
||||||
|
data set timerange months. Users can think of this as a "sliding window" which
|
||||||
|
emulates FreqAI retraining itself once per week in live using the previous
|
||||||
|
month of data.
|
||||||
|
|
||||||
|
In live, the required training data is automatically computed and downloaded. However, in backtesting
|
||||||
|
the user must manually enter the required number of `startup_candles` in the config. This value
|
||||||
|
is used to increase the available data to FreqAI and should be sufficient to enable all indicators
|
||||||
|
to be NaN free at the beginning of the first training timerange. This boils down to identifying the
|
||||||
|
highest timeframe (`4h` in present example) and the longest indicator period (25 in present example)
|
||||||
|
and adding this to the `train_period_days`. The units need to be in the base candle time frame:
|
||||||
|
|
||||||
|
`startup_candles` = ( 4 hours * 25 max period * 60 minutes/hour + 30 day train_period_days * 1440 minutes per day ) / 5 min (base time frame) = 1488.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
In dry/live, this is all precomputed and handled automatically. Thus, `startup_candle` has no influence on dry/live.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Although fractional `backtest_period_days` is allowed, the user should be ware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, if the user wants to set a `--timerange` of 10 days, and asks for a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. This is why it is physically impossible to truly backtest FreqAI adaptive training. The best way to fully test a model is to run it dry and let it constantly train. In this case, backtesting would take the exact same amount of time as a dry run.
|
||||||
|
|
||||||
|
## Running FreqAI
|
||||||
|
|
||||||
|
### Backtesting
|
||||||
|
|
||||||
|
The FreqAI backtesting module can be executed with the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade backtesting --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701
|
||||||
|
```
|
||||||
|
|
||||||
|
Backtesting mode requires the user to have the data pre-downloaded (unlike dry/live, where FreqAI automatically downloads the necessary data). The user should be careful to consider that the range of the downloaded data is more than the backtesting range. This is because FreqAI needs data prior to the desired backtesting range in order to train a model to be ready to make predictions on the first candle of the user set backtesting range. More details on how to calculate the data download timerange can be found [here](#deciding-the-sliding-training-window-and-backtesting-duration).
|
||||||
|
|
||||||
|
If this command has never been executed with the existing config file, then it will train a new model
|
||||||
|
for each pair, for each backtesting window within the bigger `--timerange`.
|
||||||
|
|
||||||
|
!!! Note "Model reuse"
|
||||||
|
Once the training is completed, the user can execute this again with the same config file and
|
||||||
|
FreqAI will find the trained models and load them instead of spending time training. This is useful
|
||||||
|
if the user wants to tweak (or even hyperopt) buy and sell criteria inside the strategy. IF the user
|
||||||
|
*wants* to retrain a new model with the same config file, then he/she should simply change the `identifier`.
|
||||||
|
This way, the user can return to using any model they wish by simply changing the `identifier`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Building a freqai strategy
|
||||||
|
|
||||||
|
The FreqAI strategy requires the user to include the following lines of code in the strategy:
|
||||||
|
|
||||||
|
```python
|
||||||
|
|
||||||
|
def informative_pairs(self):
|
||||||
|
whitelist_pairs = self.dp.current_whitelist()
|
||||||
|
corr_pairs = self.config["freqai"]["feature_parameters"]["include_corr_pairlist"]
|
||||||
|
informative_pairs = []
|
||||||
|
for tf in self.config["freqai"]["feature_parameters"]["include_timeframes"]:
|
||||||
|
for pair in whitelist_pairs:
|
||||||
|
informative_pairs.append((pair, tf))
|
||||||
|
for pair in corr_pairs:
|
||||||
|
if pair in whitelist_pairs:
|
||||||
|
continue # avoid duplication
|
||||||
|
informative_pairs.append((pair, tf))
|
||||||
|
return informative_pairs
|
||||||
|
|
||||||
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
|
||||||
|
# All indicators must be populated by populate_any_indicators() for live functionality
|
||||||
|
# to work correctly.
|
||||||
|
|
||||||
|
# the model will return all labels created by user in `populate_any_indicators`
|
||||||
|
# (& appended targets), an indication of whether or not the prediction should be accepted,
|
||||||
|
# the target mean/std values for each of the labels created by user in
|
||||||
|
# `populate_any_indicators()` for each training period.
|
||||||
|
|
||||||
|
dataframe = self.freqai.start(dataframe, metadata, self)
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
|
||||||
|
def populate_any_indicators(
|
||||||
|
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Function designed to automatically generate, name and merge features
|
||||||
|
from user indicated timeframes in the configuration file. User controls the indicators
|
||||||
|
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
||||||
|
(see convention below). I.e. user should not prepend any supporting metrics
|
||||||
|
(e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
||||||
|
model.
|
||||||
|
:param pair: pair to be used as informative
|
||||||
|
:param df: strategy dataframe which will receive merges from informatives
|
||||||
|
:param tf: timeframe of the dataframe which will modify the feature names
|
||||||
|
:param informative: the dataframe associated with the informative pair
|
||||||
|
:param coin: the name of the coin which will modify the feature names.
|
||||||
|
"""
|
||||||
|
|
||||||
|
coin = pair.split('/')[0]
|
||||||
|
|
||||||
|
if informative is None:
|
||||||
|
informative = self.dp.get_pair_dataframe(pair, tf)
|
||||||
|
|
||||||
|
# first loop is automatically duplicating indicators for time periods
|
||||||
|
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
||||||
|
t = int(t)
|
||||||
|
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
||||||
|
|
||||||
|
indicators = [col for col in informative if col.startswith("%")]
|
||||||
|
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
||||||
|
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
||||||
|
if n == 0:
|
||||||
|
continue
|
||||||
|
informative_shift = informative[indicators].shift(n)
|
||||||
|
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
||||||
|
informative = pd.concat((informative, informative_shift), axis=1)
|
||||||
|
|
||||||
|
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
||||||
|
skip_columns = [
|
||||||
|
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
||||||
|
]
|
||||||
|
df = df.drop(columns=skip_columns)
|
||||||
|
|
||||||
|
# Add generalized indicators here (because in live, it will call this
|
||||||
|
# function to populate indicators during training). Notice how we ensure not to
|
||||||
|
# add them multiple times
|
||||||
|
if set_generalized_indicators:
|
||||||
|
|
||||||
|
# user adds targets here by prepending them with &- (see convention below)
|
||||||
|
# If user wishes to use multiple targets, a multioutput prediction model
|
||||||
|
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||||
|
df["&-s_close"] = (
|
||||||
|
df["close"]
|
||||||
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.mean()
|
||||||
|
/ df["close"]
|
||||||
|
- 1
|
||||||
|
)
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
### FreqAI position in open-source machine learning landscape
|
```
|
||||||
|
|
||||||
Forecasting chaotic time-series based systems, such as equity/cryptocurrency markets, requires a broad set of tools geared toward testing a wide range of hypotheses. Fortunately, a recent maturation of robust machine learning libraries (e.g. `scikit-learn`) has opened up a wide range of research possibilities. Scientists from a diverse range of fields can now easily prototype their studies on an abundance of established machine learning algorithms. Similarly, these user-friendly libraries enable "citzen scientists" to use their basic Python skills for data-exploration. However, leveraging these machine learning libraries on historical and live chaotic data sources can be logistically difficult and expensive. Additionally, robust data-collection, storage, and handling presents a disparate challenge. [`FreqAI`](#freqai) aims to provide a generalized and extensible open-sourced framework geared toward live deployments of adaptive modeling for market forecasting. The `FreqAI` framework is effectively a sandbox for the rich world of open-source machine learning libraries. Inside the `FreqAI` sandbox, users find they can combine a wide variety of third-party libraries to test creative hypotheses on a free live 24/7 chaotic data source - cryptocurrency exchange data.
|
Notice how the `populate_any_indicators()` is where the user adds their own features and labels ([more information](#feature-engineering)). See a full example at `templates/FreqaiExampleStrategy.py`.
|
||||||
|
|
||||||
## Common pitfalls
|
### Setting classifier targets
|
||||||
|
|
||||||
FreqAI cannot be combined with dynamic `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically).
|
FreqAI includes a the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. Typically, the user would set the targets using strings:
|
||||||
|
|
||||||
|
```python
|
||||||
|
df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down')
|
||||||
|
```
|
||||||
|
|
||||||
|
### Running the model live
|
||||||
|
|
||||||
|
FreqAI can be run dry/live using the following command
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade trade --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, FreqAI will not find any existing models and will start by training a new one
|
||||||
|
given the user configuration settings. Following training, it will use that model to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the pairs to try and keep all models equally "young." FreqAI will always use the newest trained model to make predictions on incoming live data. If users do not want FreqAI to retrain new models as often as possible, they can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before retraining a new model. Additionally, users can set `expired_hours` to tell FreqAI to avoid making predictions on models aged over this number of hours.
|
||||||
|
|
||||||
|
If the user wishes to start dry/live from a backtested saved model, the user only needs to reuse
|
||||||
|
the same `identifier` parameter
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"identifier": "example",
|
||||||
|
"live_retrain_hours": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In this case, although FreqAI will initiate with a
|
||||||
|
pre-trained model, it will still check to see how much time has elapsed since the model was trained,
|
||||||
|
and if a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will self retrain.
|
||||||
|
|
||||||
|
## Data analysis techniques
|
||||||
|
|
||||||
|
### Controlling the model learning process
|
||||||
|
|
||||||
|
Model training parameters are unique to the ML library used by the user. FreqAI allows users to set any parameter for any library using the `model_training_parameters` dictionary in the user configuration file. The example configuration files show some of the example parameters associated with `Catboost` and `LightGBM`, but users can add any parameters available in those libraries.
|
||||||
|
|
||||||
|
Data split parameters are defined in `data_split_parameters` which can be any parameters associated with `Sklearn`'s `train_test_split()` function. FreqAI includes some additional parameters such `weight_factor` which allows the user to weight more recent data more strongly
|
||||||
|
than past data via an exponential function:
|
||||||
|
|
||||||
|
$$ W_i = \exp(\frac{-i}{\alpha*n}) $$
|
||||||
|
|
||||||
|
where $W_i$ is the weight of data point $i$ in a total set of $n$ data points.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
`train_test_split()` has a parameters called `shuffle`, which users also have access to in FreqAI, that allows them to keep the data unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data.
|
||||||
|
|
||||||
|
Finally, `label_period_candles` defines the offset used for the `labels`. In the present example,
|
||||||
|
the user is asking for `labels` that are 24 candles in the future.
|
||||||
|
|
||||||
|
### Removing outliers with the Dissimilarity Index
|
||||||
|
|
||||||
|
The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each
|
||||||
|
prediction by the model. To do so, FreqAI measures the distance between each training
|
||||||
|
data point and all other training data points:
|
||||||
|
|
||||||
|
$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$
|
||||||
|
|
||||||
|
where $d_{ab}$ is the distance between the normalized points $a$ and $b$. $p$
|
||||||
|
is the number of features i.e. the length of the vector $X$.
|
||||||
|
The characteristic distance, $\overline{d}$ for a set of training data points is simply the mean
|
||||||
|
of the average distances:
|
||||||
|
|
||||||
|
$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$
|
||||||
|
|
||||||
|
$\overline{d}$ quantifies the spread of the training data, which is compared to
|
||||||
|
the distance between the new prediction feature vectors, $X_k$ and all the training
|
||||||
|
data:
|
||||||
|
|
||||||
|
$$ d_k = \arg \min d_{k,i} $$
|
||||||
|
|
||||||
|
which enables the estimation of a Dissimilarity Index:
|
||||||
|
|
||||||
|
$$ DI_k = d_k/\overline{d} $$
|
||||||
|
|
||||||
|
Equity and crypto markets suffer from a high level of non-patterned noise in the
|
||||||
|
form of outlier data points. The dissimilarity index allows predictions which
|
||||||
|
are outliers and not existent in the model feature space, to be thrown out due
|
||||||
|
to low levels of certainty. Activating the Dissimilarity Index can be achieved with:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"DI_threshold": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The user can tweak the DI with `DI_threshold` to increase or decrease the extrapolation of the trained model.
|
||||||
|
|
||||||
|
### Reducing data dimensionality with Principal Component Analysis
|
||||||
|
|
||||||
|
Users can reduce the dimensionality of their features by activating the `principal_component_analysis`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"principal_component_analysis": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Which will perform PCA on the features and reduce the dimensionality of the data so that the explained
|
||||||
|
variance of the data set is >= 0.999.
|
||||||
|
|
||||||
|
### Removing outliers using a Support Vector Machine (SVM)
|
||||||
|
|
||||||
|
The user can tell FreqAI to remove outlier data points from the training/test data sets by setting:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"use_SVM_to_remove_outliers": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
FreqAI will train an SVM on the training data (or components if the user activated
|
||||||
|
`principal_component_analysis`) and remove any data point that it deems to be sitting beyond the feature space.
|
||||||
|
|
||||||
|
### Clustering the training data and removing outliers with DBSCAN
|
||||||
|
|
||||||
|
The user can configure FreqAI to use DBSCAN to cluster training data and remove outliers from the training data set. The user activates `use_DBSCAN_to_remove_outliers` to cluster training data for identification of outliers. Also used to detect incoming outliers for prediction data points.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"use_DBSCAN_to_remove_outliers": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Stratifying the data
|
||||||
|
|
||||||
|
The user can stratify the training/testing data using:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"stratify_training_data": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
which will split the data chronologically so that every Xth data points is a testing data point. In the
|
||||||
|
present example, the user is asking for every third data point in the dataframe to be used for
|
||||||
|
testing, the other points are used for training.
|
||||||
|
|
||||||
|
## Setting up a follower
|
||||||
|
|
||||||
|
The user can define:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"follow_mode": true,
|
||||||
|
"identifier": "example"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
to indicate to the bot that it should not train models, but instead should look for models trained
|
||||||
|
by a leader with the same `identifier`. In this example, the user has a leader bot with the
|
||||||
|
`identifier: "example"` already running or launching simultaneously as the present follower.
|
||||||
|
The follower will load models created by the leader and inference them to obtain predictions.
|
||||||
|
|
||||||
|
## Purging old model data
|
||||||
|
|
||||||
|
FreqAI stores new model files each time it retrains. These files become obsolete as new models
|
||||||
|
are trained and FreqAI adapts to the new market conditions. Users planning to leave FreqAI running
|
||||||
|
for extended periods of time with high frequency retraining should set `purge_old_models` in their
|
||||||
|
config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"purge_old_models": true,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
which will automatically purge all models older than the two most recently trained ones.
|
||||||
|
|
||||||
|
## Defining model expirations
|
||||||
|
|
||||||
|
During dry/live, FreqAI trains each pair sequentially (on separate threads/GPU from the main
|
||||||
|
Freqtrade bot). This means there is always an age discrepancy between models. If a user is training
|
||||||
|
on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old.
|
||||||
|
This may be undesirable if the characteristic time scale (read trade duration target) for a strategy
|
||||||
|
is much less than 4 hours. The user can decide to only make trade entries if the model is less than
|
||||||
|
a certain number of hours in age by setting the `expiration_hours` in the config file:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"expiration_hours": 0.5,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In the present example, the user will only allow predictions on models that are less than 1/2 hours
|
||||||
|
old.
|
||||||
|
|
||||||
|
## Choosing the calculation of the `target_roi`
|
||||||
|
|
||||||
|
As shown in `templates/FreqaiExampleStrategy.py`, the `target_roi` is based on two metrics computed
|
||||||
|
by FreqAI: `label_mean` and `label_std`. These are the statistics associated with the labels used
|
||||||
|
*during the most recent training*.
|
||||||
|
This allows the model to know what magnitude of a target to be expecting since it is directly stemming from the training data.
|
||||||
|
By default, FreqAI computes this based on training data and it assumes the labels are Gaussian distributed.
|
||||||
|
These are big assumptions that the user should consider when creating their labels. If the user wants to consider the population
|
||||||
|
of *historical predictions* for creating the dynamic target instead of the trained labels, the user
|
||||||
|
can do so by setting `fit_live_prediction_candles` to the number of historical prediction candles
|
||||||
|
the user wishes to use to generate target statistics.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"fit_live_prediction_candles": 300,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If the user sets this value, FreqAI will initially use the predictions from the training data set
|
||||||
|
and then subsequently begin introducing real prediction data as it is generated. FreqAI will save
|
||||||
|
this historical data to be reloaded if the user stops and restarts with the same `identifier`.
|
||||||
|
|
||||||
|
## Extra returns per train
|
||||||
|
|
||||||
|
Users may find that there are some important metrics that they'd like to return to the strategy at the end of each retrain.
|
||||||
|
Users can include these metrics by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside their custom prediction
|
||||||
|
model class. FreqAI takes the `my_new_value` assigned in this dictionary and expands it to fit the return dataframe to the strategy.
|
||||||
|
The user can then use the value in the strategy with `dataframe['my_new_value']`. An example of how this is already used in FreqAI is
|
||||||
|
the `&*_mean` and `&*_std` values, which indicate the mean and standard deviation of that particular label during the most recent training.
|
||||||
|
Another example is shown below if the user wants to use live metrics from the trade database.
|
||||||
|
|
||||||
|
The user needs to set the standard dictionary in the config so FreqAI can return proper dataframe shapes:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"extra_returns_per_train": {"total_profit": 4}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
These values will likely be overridden by the user prediction model, but in the case where the user model has yet to set them, or needs
|
||||||
|
a default initial value - this is the value that will be returned.
|
||||||
|
|
||||||
|
## Building an IFreqaiModel
|
||||||
|
|
||||||
|
FreqAI has multiple example prediction model based libraries such as `Catboost` regression (`freqai/prediction_models/CatboostRegressor.py`) and `LightGBM` regression.
|
||||||
|
However, users can customize and create their own prediction models using the `IFreqaiModel` class.
|
||||||
|
Users are encouraged to inherit `train()` and `predict()` to let them customize various aspects of their training procedures.
|
||||||
|
|
||||||
|
## Additional information
|
||||||
|
|
||||||
|
### Common pitfalls
|
||||||
|
|
||||||
|
FreqAI cannot be combined with `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically).
|
||||||
This is for performance reasons - FreqAI relies on making quick predictions/retrains. To do this effectively,
|
This is for performance reasons - FreqAI relies on making quick predictions/retrains. To do this effectively,
|
||||||
it needs to download all the training data at the beginning of a dry/live instance. FreqAI stores and appends
|
it needs to download all the training data at the beginning of a dry/live instance. FreqAI stores and appends
|
||||||
new candles automatically for future retrains. This means that if new pairs arrive later in the dry run due to a volume pairlist, it will not have the data ready. However, FreqAI does work with the `ShufflePairlist` or a `VolumePairlist` which keeps the total pairlist constant (but reorders the pairs according to volume).
|
new candles automatically for future retrains. But this means that if new pairs arrive later in the dry run due
|
||||||
|
to a volume pairlist, it will not have the data ready. FreqAI does work, however, with the `ShufflePairlist`.
|
||||||
|
|
||||||
|
### Feature normalization
|
||||||
|
|
||||||
|
The feature set created by the user is automatically normalized to the training data only.
|
||||||
|
This includes all test data and unseen prediction data (dry/live/backtest).
|
||||||
|
|
||||||
|
### File structure
|
||||||
|
|
||||||
|
`user_data_dir/models/` contains all the data associated with the trainings and backtests.
|
||||||
|
This file structure is heavily controlled and read by the `FreqaiDataKitchen()`
|
||||||
|
and should therefore not be modified.
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
FreqAI is developed by a group of individuals who all contribute specific skillsets to the project.
|
FreqAI was developed by a group of individuals who all contributed specific skillsets to the project.
|
||||||
|
|
||||||
Conception and software development:
|
Conception and software development:
|
||||||
Robert Caulk @robcaulk
|
Robert Caulk @robcaulk
|
||||||
|
|
||||||
Theoretical brainstorming and data analysis:
|
Theoretical brainstorming:
|
||||||
Elin Törnquist @th0rntwig
|
Elin Törnquist @thorntwig
|
||||||
|
|
||||||
Code review and software architecture brainstorming:
|
Code review, software architecture brainstorming:
|
||||||
@xmatthias
|
@xmatthias
|
||||||
|
|
||||||
Software development:
|
|
||||||
Wagner Costa @wagnercosta
|
|
||||||
|
|
||||||
Beta testing and bug reporting:
|
Beta testing and bug reporting:
|
||||||
Stefan Gehring @bloodhunter4rc, @longyu, Andrew Lawless @paranoidandy, Pascal Schmidt @smidelis, Ryan McMullan @smarmau, Juha Nykänen @suikula, Johan van der Vlugt @jooopiert, Richárd Józsa @richardjosza, Timothy Pogue @wizrds
|
@bloodhunter4rc, Salah Lamkadem @ikonx, @ken11o2, @longyu, @paranoidandy, @smidelis, @smarm
|
||||||
|
Juha Nykänen @suikula, Wagner Costa @wagnercosta
|
||||||
|
@@ -40,8 +40,7 @@ pip install -r requirements-hyperopt.txt
|
|||||||
```
|
```
|
||||||
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[--recursive-strategy-search] [--freqaimodel NAME]
|
[--recursive-strategy-search] [-i TIMEFRAME]
|
||||||
[--freqaimodel-path PATH] [-i TIMEFRAME]
|
|
||||||
[--timerange TIMERANGE]
|
[--timerange TIMERANGE]
|
||||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[--max-open-trades INT]
|
[--max-open-trades INT]
|
||||||
@@ -54,7 +53,7 @@ usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
|||||||
[--print-all] [--no-color] [--print-json] [-j JOBS]
|
[--print-all] [--no-color] [--print-json] [-j JOBS]
|
||||||
[--random-state INT] [--min-trades INT]
|
[--random-state INT] [--min-trades INT]
|
||||||
[--hyperopt-loss NAME] [--disable-param-export]
|
[--hyperopt-loss NAME] [--disable-param-export]
|
||||||
[--ignore-missing-spaces] [--analyze-per-epoch]
|
[--ignore-missing-spaces]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@@ -130,7 +129,6 @@ optional arguments:
|
|||||||
--ignore-missing-spaces, --ignore-unparameterized-spaces
|
--ignore-missing-spaces, --ignore-unparameterized-spaces
|
||||||
Suppress errors for any requested Hyperopt spaces that
|
Suppress errors for any requested Hyperopt spaces that
|
||||||
do not contain any parameters.
|
do not contain any parameters.
|
||||||
--analyze-per-epoch Run populate_indicators once per epoch.
|
|
||||||
|
|
||||||
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).
|
||||||
@@ -156,10 +154,6 @@ Strategy arguments:
|
|||||||
--recursive-strategy-search
|
--recursive-strategy-search
|
||||||
Recursively search for a strategy in the strategies
|
Recursively search for a strategy in the strategies
|
||||||
folder.
|
folder.
|
||||||
--freqaimodel NAME Specify a custom freqaimodels.
|
|
||||||
--freqaimodel-path PATH
|
|
||||||
Specify additional lookup path for freqaimodels.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Hyperopt checklist
|
### Hyperopt checklist
|
||||||
@@ -191,7 +185,7 @@ Rarely you may also need to create a [nested class](advanced-hyperopt.md#overrid
|
|||||||
|
|
||||||
### Hyperopt execution logic
|
### Hyperopt execution logic
|
||||||
|
|
||||||
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators, unless `--analyze-per-epoch` is specified.
|
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators.
|
||||||
|
|
||||||
Hyperopt will then spawn into different processes (number of processors, or `-j <n>`), and run backtesting over and over again, changing the parameters that are part of the `--spaces` defined.
|
Hyperopt will then spawn into different processes (number of processors, or `-j <n>`), and run backtesting over and over again, changing the parameters that are part of the `--spaces` defined.
|
||||||
|
|
||||||
@@ -432,10 +426,9 @@ While this strategy is most likely too simple to provide consistent profit, it s
|
|||||||
`range` property may also be used with `DecimalParameter` and `CategoricalParameter`. `RealParameter` does not provide this property due to infinite search space.
|
`range` property may also be used with `DecimalParameter` and `CategoricalParameter`. `RealParameter` does not provide this property due to infinite search space.
|
||||||
|
|
||||||
??? Hint "Performance tip"
|
??? Hint "Performance tip"
|
||||||
During normal hyperopting, indicators are calculated once and supplied to each epoch, linearly increasing RAM usage as a factor of increasing cores. As this also has performance implications, hyperopt provides `--analyze-per-epoch` which will move the execution of `populate_indicators()` to the epoch process, calculating a single value per parameter per epoch instead of using the `.range` functionality. In this case, `.range` functionality will only return the actually used value. This will reduce RAM usage, but increase CPU usage. However, your hyperopting run will be less likely to fail due to Out Of Memory (OOM) issues.
|
By doing the calculation of all possible indicators in `populate_indicators()`, the calculation of the indicator happens only once for every parameter.
|
||||||
|
While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values).
|
||||||
In either case, you should try to use space ranges as small as possible this will improve CPU/RAM usage in both scenarios.
|
You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space.
|
||||||
|
|
||||||
|
|
||||||
## Optimizing protections
|
## Optimizing protections
|
||||||
|
|
||||||
@@ -886,7 +879,6 @@ To combat these, you have multiple options:
|
|||||||
* Avoid using `--timeframe-detail` (this loads a lot of additional data into memory).
|
* Avoid using `--timeframe-detail` (this loads a lot of additional data into memory).
|
||||||
* Reduce the number of parallel processes (`-j <n>`).
|
* Reduce the number of parallel processes (`-j <n>`).
|
||||||
* Increase the memory of your machine.
|
* Increase the memory of your machine.
|
||||||
* Use `--analyze-per-epoch` if you're using a lot of parameters with `.range` functionality.
|
|
||||||
|
|
||||||
|
|
||||||
## The objective has been evaluated at this point before.
|
## The objective has been evaluated at this point before.
|
||||||
|
@@ -22,7 +22,6 @@ You may also use something like `.*DOWN/BTC` or `.*UP/BTC` to exclude leveraged
|
|||||||
|
|
||||||
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||||
* [`VolumePairList`](#volume-pair-list)
|
* [`VolumePairList`](#volume-pair-list)
|
||||||
* [`ProducerPairList`](#producerpairlist)
|
|
||||||
* [`AgeFilter`](#agefilter)
|
* [`AgeFilter`](#agefilter)
|
||||||
* [`OffsetFilter`](#offsetfilter)
|
* [`OffsetFilter`](#offsetfilter)
|
||||||
* [`PerformanceFilter`](#performancefilter)
|
* [`PerformanceFilter`](#performancefilter)
|
||||||
@@ -85,7 +84,7 @@ Filtering instances (not the first position in the list) will not apply any cach
|
|||||||
|
|
||||||
You can define a minimum volume with `min_value` - which will filter out pairs with a volume lower than the specified value in the specified timerange.
|
You can define a minimum volume with `min_value` - which will filter out pairs with a volume lower than the specified value in the specified timerange.
|
||||||
|
|
||||||
##### VolumePairList Advanced mode
|
### VolumePairList Advanced mode
|
||||||
|
|
||||||
`VolumePairList` can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the `quoteVolume` over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles.
|
`VolumePairList` can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the `quoteVolume` over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles.
|
||||||
|
|
||||||
@@ -147,32 +146,6 @@ More sophisticated approach can be used, by using `lookback_timeframe` for candl
|
|||||||
!!! Note
|
!!! Note
|
||||||
`VolumePairList` does not support backtesting mode.
|
`VolumePairList` does not support backtesting mode.
|
||||||
|
|
||||||
#### ProducerPairList
|
|
||||||
|
|
||||||
With `ProducerPairList`, you can reuse the pairlist from a [Producer](producer-consumer.md) without explicitly defining the pairlist on each consumer.
|
|
||||||
|
|
||||||
[Consumer mode](producer-consumer.md) is required for this pairlist to work.
|
|
||||||
|
|
||||||
The pairlist will perform a check on active pairs against the current exchange configuration to avoid attempting to trade on invalid markets.
|
|
||||||
|
|
||||||
You can limit the length of the pairlist with the optional parameter `number_assets`. Using `"number_assets"=0` or omitting this key will result in the reuse of all producer pairs valid for the current setup.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"pairlists": [
|
|
||||||
{
|
|
||||||
"method": "ProducerPairList",
|
|
||||||
"number_assets": 5,
|
|
||||||
"producer_name": "default",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
!!! Tip "Combining pairlists"
|
|
||||||
This pairlist can be combined with all other pairlists and filters for further pairlist reduction, and can also act as an "additional" pairlist, on top of already defined pairs.
|
|
||||||
`ProducerPairList` can also be used multiple times in sequence, combining the pairs from multiple producers.
|
|
||||||
Obviously in complex such configurations, the Producer may not provide data for all pairs, so the strategy must be fit for this.
|
|
||||||
|
|
||||||
#### AgeFilter
|
#### AgeFilter
|
||||||
|
|
||||||
Removes pairs that have been listed on the exchange for less than `min_days_listed` days (defaults to `10`) or more than `max_days_listed` days (defaults `None` mean infinity).
|
Removes pairs that have been listed on the exchange for less than `min_days_listed` days (defaults to `10`) or more than `max_days_listed` days (defaults `None` mean infinity).
|
||||||
@@ -268,7 +241,7 @@ This option is disabled by default, and will only apply if set to > 0.
|
|||||||
The `max_value` setting removes pairs where the minimum value change is above a specified value.
|
The `max_value` setting removes pairs where the minimum value change is above a specified value.
|
||||||
This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20\$) as the coin has risen sharply since the last limit adaption.
|
This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20\$) as the coin has risen sharply since the last limit adaption.
|
||||||
As a result of the above, you can only buy for 20\$, or 40\$ - but not for 25\$.
|
As a result of the above, you can only buy for 20\$, or 40\$ - but not for 25\$.
|
||||||
On exchanges that deduct fees from the receiving currency (e.g. binance) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit.
|
On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit.
|
||||||
|
|
||||||
The `low_price_ratio` setting removes pairs where a raise of 1 price unit (pip) is above the `low_price_ratio` ratio.
|
The `low_price_ratio` setting removes pairs where a raise of 1 price unit (pip) is above the `low_price_ratio` ratio.
|
||||||
This option is disabled by default, and will only apply if set to > 0.
|
This option is disabled by default, and will only apply if set to > 0.
|
||||||
@@ -286,18 +259,6 @@ Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 -
|
|||||||
|
|
||||||
Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.
|
Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.
|
||||||
|
|
||||||
By default, ShuffleFilter will shuffle pairs once per candle.
|
|
||||||
To shuffle on every iteration, set `"shuffle_frequency"` to `"iteration"` instead of the default of `"candle"`.
|
|
||||||
|
|
||||||
``` json
|
|
||||||
{
|
|
||||||
"method": "ShuffleFilter",
|
|
||||||
"shuffle_frequency": "candle",
|
|
||||||
"seed": 42
|
|
||||||
}
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Tip
|
!!! Tip
|
||||||
You may set the `seed` value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If `seed` is not set, the pairs are shuffled in the non-repeatable random order. ShuffleFilter will automatically detect runmodes and apply the `seed` only for backtesting modes - if a `seed` value is set.
|
You may set the `seed` value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If `seed` is not set, the pairs are shuffled in the non-repeatable random order. ShuffleFilter will automatically detect runmodes and apply the `seed` only for backtesting modes - if a `seed` value is set.
|
||||||
|
|
||||||
|
@@ -32,7 +32,7 @@ Freqtrade is a free and open source crypto trading bot written in Python. It is
|
|||||||
- Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode).
|
- Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode).
|
||||||
- Run using Edge (optional module): The concept is to find the best historical [trade expectancy](edge.md#expectancy) by markets based on variation of the stop-loss and then allow/reject markets to trade. The sizing of the trade is based on a risk of a percentage of your capital.
|
- Run using Edge (optional module): The concept is to find the best historical [trade expectancy](edge.md#expectancy) by markets based on variation of the stop-loss and then allow/reject markets to trade. The sizing of the trade is based on a risk of a percentage of your capital.
|
||||||
- Control/Monitor: Use Telegram or a WebUI (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).
|
- Control/Monitor: Use Telegram or a WebUI (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).
|
||||||
- Analyze: 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
|
## Supported exchange marketplaces
|
||||||
|
|
||||||
@@ -40,6 +40,7 @@ Please read the [exchange specific notes](exchanges.md) to learn about eventual,
|
|||||||
|
|
||||||
- [X] [Binance](https://www.binance.com/)
|
- [X] [Binance](https://www.binance.com/)
|
||||||
- [X] [Bittrex](https://bittrex.com/)
|
- [X] [Bittrex](https://bittrex.com/)
|
||||||
|
- [X] [FTX](https://ftx.com/#a=2258149)
|
||||||
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
- [X] [Huobi](http://huobi.com/)
|
- [X] [Huobi](http://huobi.com/)
|
||||||
- [X] [Kraken](https://kraken.com/)
|
- [X] [Kraken](https://kraken.com/)
|
||||||
@@ -50,7 +51,7 @@ Please read the [exchange specific notes](exchanges.md) to learn about eventual,
|
|||||||
|
|
||||||
- [X] [Binance](https://www.binance.com/)
|
- [X] [Binance](https://www.binance.com/)
|
||||||
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
- [X] [OKX](https://okx.com/)
|
- [X] [OKX](https://okx.com/).
|
||||||
|
|
||||||
Please make sure to read the [exchange specific notes](exchanges.md), as well as the [trading with leverage](leverage.md) documentation before diving in.
|
Please make sure to read the [exchange specific notes](exchanges.md), as well as the [trading with leverage](leverage.md) documentation before diving in.
|
||||||
|
|
||||||
|
@@ -13,7 +13,7 @@
|
|||||||
Please only use advanced trading modes when you know how freqtrade (and your strategy) works.
|
Please only use advanced trading modes when you know how freqtrade (and your strategy) works.
|
||||||
Also, never risk more than what you can afford to lose.
|
Also, never risk more than what you can afford to lose.
|
||||||
|
|
||||||
If you already have an existing strategy, please read the [strategy migration guide](strategy_migration.md#strategy-migration-between-v2-and-v3) to migrate your strategy from a freqtrade v2 strategy, to strategy of version 3 which can short and trade futures.
|
Please read the [strategy migration guide](strategy_migration.md#strategy-migration-between-v2-and-v3) to migrate your strategy from a freqtrade v2 strategy, to v3 strategy that can short and trade futures.
|
||||||
|
|
||||||
## Shorting
|
## Shorting
|
||||||
|
|
||||||
@@ -62,13 +62,6 @@ You will also have to pick a "margin mode" (explanation below) - with freqtrade
|
|||||||
"margin_mode": "isolated"
|
"margin_mode": "isolated"
|
||||||
```
|
```
|
||||||
|
|
||||||
##### Pair namings
|
|
||||||
|
|
||||||
Freqtrade follows the [ccxt naming conventions for futures](https://docs.ccxt.com/en/latest/manual.html?#perpetual-swap-perpetual-future).
|
|
||||||
A futures pair will therefore have the naming of `base/quote:settle` (e.g. `ETH/USDT:USDT`).
|
|
||||||
|
|
||||||
Binance is currently still an exception to this naming scheme, where pairs are named `ETH/USDT` also for futures markets, but will be aligned as soon as CCXT is ready.
|
|
||||||
|
|
||||||
### Margin mode
|
### Margin mode
|
||||||
|
|
||||||
On top of `trading_mode` - you will also have to configure your `margin_mode`.
|
On top of `trading_mode` - you will also have to configure your `margin_mode`.
|
||||||
|
@@ -1,165 +0,0 @@
|
|||||||
# Producer / Consumer mode
|
|
||||||
|
|
||||||
freqtrade provides a mechanism whereby an instance (also called `consumer`) may listen to messages from an upstream freqtrade instance (also called `producer`) using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times.
|
|
||||||
|
|
||||||
See [Message Websocket](rest-api.md#message-websocket) in the Rest API docs for setting up the `api_server` configuration for your message websocket (this will be your producer).
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
We strongly recommend to set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Enable subscribing to an instance by adding the `external_message_consumer` section to the consumer's config file.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
//...
|
|
||||||
"external_message_consumer": {
|
|
||||||
"enabled": true,
|
|
||||||
"producers": [
|
|
||||||
{
|
|
||||||
"name": "default", // This can be any name you'd like, default is "default"
|
|
||||||
"host": "127.0.0.1", // The host from your producer's api_server config
|
|
||||||
"port": 8080, // The port from your producer's api_server config
|
|
||||||
"secure": false, // Use a secure websockets connection, default false
|
|
||||||
"ws_token": "sercet_Ws_t0ken" // The ws_token from your producer's api_server config
|
|
||||||
}
|
|
||||||
],
|
|
||||||
// The following configurations are optional, and usually not required
|
|
||||||
// "wait_timeout": 300,
|
|
||||||
// "ping_timeout": 10,
|
|
||||||
// "sleep_time": 10,
|
|
||||||
// "remove_entry_exit_signals": false,
|
|
||||||
// "message_size_limit": 8
|
|
||||||
}
|
|
||||||
//...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Description |
|
|
||||||
|------------|-------------|
|
|
||||||
| `enabled` | **Required.** Enable consumer mode. If set to false, all other settings in this section are ignored.<br>*Defaults to `false`.*<br> **Datatype:** boolean .
|
|
||||||
| `producers` | **Required.** List of producers <br> **Datatype:** Array.
|
|
||||||
| `producers.name` | **Required.** Name of this producer. This name must be used in calls to `get_producer_pairs()` and `get_producer_df()` if more than one producer is used.<br> **Datatype:** string
|
|
||||||
| `producers.host` | **Required.** The hostname or IP address from your producer.<br> **Datatype:** string
|
|
||||||
| `producers.port` | **Required.** The port matching the above host.<br> **Datatype:** string
|
|
||||||
| `producers.secure` | **Optional.** Use ssl in websockets connection. Default False.<br> **Datatype:** string
|
|
||||||
| `producers.ws_token` | **Required.** `ws_token` as configured on the producer.<br> **Datatype:** string
|
|
||||||
| | **Optional settings**
|
|
||||||
| `wait_timeout` | Timeout until we ping again if no message is received. <br>*Defaults to `300`.*<br> **Datatype:** Integer - in seconds.
|
|
||||||
| `wait_timeout` | Ping timeout <br>*Defaults to `10`.*<br> **Datatype:** Integer - in seconds.
|
|
||||||
| `sleep_time` | Sleep time before retrying to connect.<br>*Defaults to `10`.*<br> **Datatype:** Integer - in seconds.
|
|
||||||
| `remove_entry_exit_signals` | Remove signal columns from the dataframe (set them to 0) on dataframe receipt.<br>*Defaults to `10`.*<br> **Datatype:** Integer - in seconds.
|
|
||||||
| `message_size_limit` | Size limit per message<br>*Defaults to `8`.*<br> **Datatype:** Integer - Megabytes.
|
|
||||||
|
|
||||||
Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a producer instance's messages (or multiple producer instances in advanced configurations) and requests the producer's most recently analyzed dataframes for each pair in the active whitelist.
|
|
||||||
|
|
||||||
A consumer instance will then have a full copy of the analyzed dataframes without the need to calculate them itself.
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
### Example - Producer Strategy
|
|
||||||
|
|
||||||
A simple strategy with multiple indicators. No special considerations are required in the strategy itself.
|
|
||||||
|
|
||||||
```py
|
|
||||||
class ProducerStrategy(IStrategy):
|
|
||||||
#...
|
|
||||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Calculate indicators in the standard freqtrade way which can then be broadcast to other instances
|
|
||||||
"""
|
|
||||||
dataframe['rsi'] = ta.RSI(dataframe)
|
|
||||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
|
||||||
dataframe['bb_lowerband'] = bollinger['lower']
|
|
||||||
dataframe['bb_middleband'] = bollinger['mid']
|
|
||||||
dataframe['bb_upperband'] = bollinger['upper']
|
|
||||||
dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
|
|
||||||
|
|
||||||
return dataframe
|
|
||||||
|
|
||||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Populates the entry signal for the given dataframe
|
|
||||||
"""
|
|
||||||
dataframe.loc[
|
|
||||||
(
|
|
||||||
(qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) &
|
|
||||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
|
||||||
(dataframe['tema'] > dataframe['tema'].shift(1)) &
|
|
||||||
(dataframe['volume'] > 0)
|
|
||||||
),
|
|
||||||
'enter_long'] = 1
|
|
||||||
|
|
||||||
return dataframe
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Tip "FreqAI"
|
|
||||||
You can use this to setup [FreqAI](freqai.md) on a powerful machine, while you run consumers on simple machines like raspberries, which can interpret the signals generated from the producer in different ways.
|
|
||||||
|
|
||||||
|
|
||||||
### Example - Consumer Strategy
|
|
||||||
|
|
||||||
A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes available to make trading decisions based on the indicators calculated in the producer. In this example the consumer has the same entry criteria, however this is not necessary. The consumer may use different logic to enter/exit trades, and only use the indicators as specified.
|
|
||||||
|
|
||||||
```py
|
|
||||||
class ConsumerStrategy(IStrategy):
|
|
||||||
#...
|
|
||||||
process_only_new_candles = False # required for consumers
|
|
||||||
|
|
||||||
_columns_to_expect = ['rsi_default', 'tema_default', 'bb_middleband_default']
|
|
||||||
|
|
||||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Use the websocket api to get pre-populated indicators from another freqtrade instance.
|
|
||||||
Use `self.dp.get_producer_df(pair)` to get the dataframe
|
|
||||||
"""
|
|
||||||
pair = metadata['pair']
|
|
||||||
timeframe = self.timeframe
|
|
||||||
|
|
||||||
producer_pairs = self.dp.get_producer_pairs()
|
|
||||||
# You can specify which producer to get pairs from via:
|
|
||||||
# self.dp.get_producer_pairs("my_other_producer")
|
|
||||||
|
|
||||||
# This func returns the analyzed dataframe, and when it was analyzed
|
|
||||||
producer_dataframe, _ = self.dp.get_producer_df(pair)
|
|
||||||
# You can get other data if the producer makes it available:
|
|
||||||
# self.dp.get_producer_df(
|
|
||||||
# pair,
|
|
||||||
# timeframe="1h",
|
|
||||||
# candle_type=CandleType.SPOT,
|
|
||||||
# producer_name="my_other_producer"
|
|
||||||
# )
|
|
||||||
|
|
||||||
if not producer_dataframe.empty:
|
|
||||||
# If you plan on passing the producer's entry/exit signal directly,
|
|
||||||
# specify ffill=False or it will have unintended results
|
|
||||||
merged_dataframe = merge_informative_pair(dataframe, producer_dataframe,
|
|
||||||
timeframe, timeframe,
|
|
||||||
append_timeframe=False,
|
|
||||||
suffix="default")
|
|
||||||
return merged_dataframe
|
|
||||||
else:
|
|
||||||
dataframe[self._columns_to_expect] = 0
|
|
||||||
|
|
||||||
return dataframe
|
|
||||||
|
|
||||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Populates the entry signal for the given dataframe
|
|
||||||
"""
|
|
||||||
# Use the dataframe columns as if we calculated them ourselves
|
|
||||||
dataframe.loc[
|
|
||||||
(
|
|
||||||
(qtpylib.crossed_above(dataframe['rsi_default'], self.buy_rsi.value)) &
|
|
||||||
(dataframe['tema_default'] <= dataframe['bb_middleband_default']) &
|
|
||||||
(dataframe['tema_default'] > dataframe['tema_default'].shift(1)) &
|
|
||||||
(dataframe['volume'] > 0)
|
|
||||||
),
|
|
||||||
'enter_long'] = 1
|
|
||||||
|
|
||||||
return dataframe
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Tip "Using upstream signals"
|
|
||||||
By setting `remove_entry_exit_signals=false`, you can also use the producer's signals directly. They should be available as `enter_long_default` (assuming `suffix="default"` was used) - and can be used as either signal directly, or as additional indicator.
|
|
@@ -1,6 +1,6 @@
|
|||||||
markdown==3.3.7
|
markdown==3.3.7
|
||||||
mkdocs==1.4.2
|
mkdocs==1.3.1
|
||||||
mkdocs-material==8.5.10
|
mkdocs-material==8.4.0
|
||||||
mdx_truly_sane_lists==1.3
|
mdx_truly_sane_lists==1.3
|
||||||
pymdown-extensions==9.8
|
pymdown-extensions==9.5
|
||||||
jinja2==3.1.2
|
jinja2==3.1.2
|
||||||
|
123
docs/rest-api.md
@@ -31,8 +31,7 @@ Sample configuration:
|
|||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
"CORS_origins": [],
|
"CORS_origins": [],
|
||||||
"username": "Freqtrader",
|
"username": "Freqtrader",
|
||||||
"password": "SuperSecret1!",
|
"password": "SuperSecret1!"
|
||||||
"ws_token": "sercet_Ws_t0ken"
|
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -67,7 +66,7 @@ secrets.token_hex()
|
|||||||
|
|
||||||
!!! Danger "Password selection"
|
!!! Danger "Password selection"
|
||||||
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
|
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!).
|
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
|
||||||
|
|
||||||
@@ -94,6 +93,7 @@ Make sure that the following 2 lines are available in your docker-compose file:
|
|||||||
!!! Danger "Security warning"
|
!!! Danger "Security warning"
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
|
||||||
## Rest API
|
## Rest API
|
||||||
|
|
||||||
### Consuming the API
|
### Consuming the API
|
||||||
@@ -163,8 +163,6 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
|||||||
| `strategy <strategy>` | Get specific Strategy content. **Alpha**
|
| `strategy <strategy>` | Get specific Strategy content. **Alpha**
|
||||||
| `available_pairs` | List available backtest data. **Alpha**
|
| `available_pairs` | List available backtest data. **Alpha**
|
||||||
| `version` | Show version.
|
| `version` | Show version.
|
||||||
| `sysinfo` | Show informations about the system load.
|
|
||||||
| `health` | Show bot health (last bot loop).
|
|
||||||
|
|
||||||
!!! Warning "Alpha status"
|
!!! Warning "Alpha status"
|
||||||
Endpoints labeled with *Alpha status* above may change at any time without notice.
|
Endpoints labeled with *Alpha status* above may change at any time without notice.
|
||||||
@@ -229,11 +227,6 @@ forceexit
|
|||||||
Force-exit a trade.
|
Force-exit a trade.
|
||||||
|
|
||||||
:param tradeid: Id of the trade (can be received via status command)
|
:param tradeid: Id of the trade (can be received via status command)
|
||||||
:param ordertype: Order type to use (must be market or limit)
|
|
||||||
:param amount: Amount to sell. Full sell if not given
|
|
||||||
|
|
||||||
health
|
|
||||||
Provides a quick health check of the running bot.
|
|
||||||
|
|
||||||
locks
|
locks
|
||||||
Return current locks
|
Return current locks
|
||||||
@@ -274,7 +267,7 @@ reload_config
|
|||||||
Reload configuration.
|
Reload configuration.
|
||||||
|
|
||||||
show_config
|
show_config
|
||||||
|
|
||||||
Returns part of the configuration, relevant for trading operations.
|
Returns part of the configuration, relevant for trading operations.
|
||||||
|
|
||||||
start
|
start
|
||||||
@@ -319,118 +312,12 @@ version
|
|||||||
|
|
||||||
whitelist
|
whitelist
|
||||||
Show the current whitelist.
|
Show the current whitelist.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Message WebSocket
|
|
||||||
|
|
||||||
The API Server includes a websocket endpoint for subscribing to RPC messages from the freqtrade Bot.
|
|
||||||
This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more.
|
|
||||||
|
|
||||||
This is also used to setup [Producer/Consumer mode](producer-consumer.md) in Freqtrade.
|
|
||||||
|
|
||||||
Assuming your rest API is set to `127.0.0.1` on port `8080`, the endpoint is available at `http://localhost:8080/api/v1/message/ws`.
|
|
||||||
|
|
||||||
To access the websocket endpoint, the `ws_token` is required as a query parameter in the endpoint URL.
|
|
||||||
|
|
||||||
To generate a safe `ws_token` you can run the following code:
|
|
||||||
|
|
||||||
``` python
|
|
||||||
>>> import secrets
|
|
||||||
>>> secrets.token_urlsafe(25)
|
|
||||||
'hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q'
|
|
||||||
```
|
|
||||||
|
|
||||||
You would then add that token under `ws_token` in your `api_server` config. Like so:
|
|
||||||
|
|
||||||
``` json
|
|
||||||
"api_server": {
|
|
||||||
"enabled": true,
|
|
||||||
"listen_ip_address": "127.0.0.1",
|
|
||||||
"listen_port": 8080,
|
|
||||||
"verbosity": "error",
|
|
||||||
"enable_openapi": false,
|
|
||||||
"jwt_secret_key": "somethingrandom",
|
|
||||||
"CORS_origins": [],
|
|
||||||
"username": "Freqtrader",
|
|
||||||
"password": "SuperSecret1!",
|
|
||||||
"ws_token": "hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q" // <-----
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
You can now connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q`.
|
|
||||||
|
|
||||||
!!! Danger "Reuse of example tokens"
|
|
||||||
Please do not use the above example token. To make sure you are secure, generate a completely new token.
|
|
||||||
|
|
||||||
#### Using the WebSocket
|
|
||||||
|
|
||||||
Once connected to the WebSocket, the bot will broadcast RPC messages to anyone who is subscribed to them. To subscribe to a list of messages, you must send a JSON request through the WebSocket like the one below. The `data` key must be a list of message type strings.
|
|
||||||
|
|
||||||
``` json
|
|
||||||
{
|
|
||||||
"type": "subscribe",
|
|
||||||
"data": ["whitelist", "analyzed_df"] // A list of string message types
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
For a list of message types, please refer to the RPCMessageType enum in `freqtrade/enums/rpcmessagetype.py`
|
|
||||||
|
|
||||||
Now anytime those types of RPC messages are sent in the bot, you will receive them through the WebSocket as long as the connection is active. They typically take the same form as the request:
|
|
||||||
|
|
||||||
``` json
|
|
||||||
{
|
|
||||||
"type": "analyzed_df",
|
|
||||||
"data": {
|
|
||||||
"key": ["NEO/BTC", "5m", "spot"],
|
|
||||||
"df": {}, // The dataframe
|
|
||||||
"la": "2022-09-08 22:14:41.457786+00:00"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Reverse Proxy setup
|
|
||||||
|
|
||||||
When using [Nginx](https://nginx.org/en/docs/), the following configuration is required for WebSockets to work (Note this configuration is incomplete, it's missing some information and can not be used as is):
|
|
||||||
|
|
||||||
Please make sure to replace `<freqtrade_listen_ip>` (and the subsequent port) with the IP and Port matching your configuration/setup.
|
|
||||||
|
|
||||||
```
|
|
||||||
http {
|
|
||||||
map $http_upgrade $connection_upgrade {
|
|
||||||
default upgrade;
|
|
||||||
'' close;
|
|
||||||
}
|
|
||||||
|
|
||||||
#...
|
|
||||||
|
|
||||||
server {
|
|
||||||
#...
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_pass http://<freqtrade_listen_ip>:8080;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection $connection_upgrade;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
To properly configure your reverse proxy (securely), please consult it's documentation for proxying websockets.
|
|
||||||
|
|
||||||
- **Traefik**: Traefik supports websockets out of the box, see the [documentation](https://doc.traefik.io/traefik/)
|
|
||||||
- **Caddy**: Caddy v2 supports websockets out of the box, see the [documentation](https://caddyserver.com/docs/v2-upgrade#proxy)
|
|
||||||
|
|
||||||
!!! Tip "SSL certificates"
|
|
||||||
You can use tools like certbot to setup ssl certificates to access your bot's UI through encrypted connection by using any fo the above reverse proxies.
|
|
||||||
While this will protect your data in transit, we do not recommend to run the freqtrade API outside of your private network (VPN, SSH tunnel).
|
|
||||||
|
|
||||||
### OpenAPI interface
|
### OpenAPI interface
|
||||||
|
|
||||||
To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration.
|
To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration.
|
||||||
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs - but it'll depend on your settings.
|
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.
|
||||||
|
|
||||||
### Advanced API usage using JWT tokens
|
### Advanced API usage using JWT tokens
|
||||||
|
|
||||||
|
@@ -24,7 +24,7 @@ These modes can be configured with these values:
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Stoploss on exchange is only supported for Binance (stop-loss-limit), Huobi (stop-limit), Kraken (stop-loss-market, stop-loss-limit), Gateio (stop-limit), and Kucoin (stop-limit and stop-market) as of now.
|
Stoploss on exchange is only supported for Binance (stop-loss-limit), Huobi (stop-limit), Kraken (stop-loss-market, stop-loss-limit), FTX (stop limit and stop-market) Gateio (stop-limit), and Kucoin (stop-limit and stop-market) as of now.
|
||||||
<ins>Do not set too low/tight stoploss value if using stop loss on exchange!</ins>
|
<ins>Do not set too low/tight stoploss value if using stop loss on exchange!</ins>
|
||||||
If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work.
|
If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work.
|
||||||
|
|
||||||
@@ -87,7 +87,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-callbacks.md#custom-stoploss)
|
5. [Custom stoploss function](strategy-advanced.md#custom-stoploss)
|
||||||
|
|
||||||
### Static Stop Loss
|
### Static Stop Loss
|
||||||
|
|
||||||
|
@@ -106,12 +106,6 @@ def custom_exit(self, pair: str, trade: Trade, current_time: datetime, current_r
|
|||||||
!!! Note
|
!!! Note
|
||||||
`enter_tag` is limited to 100 characters, remaining data will be truncated.
|
`enter_tag` is limited to 100 characters, remaining data will be truncated.
|
||||||
|
|
||||||
!!! Warning
|
|
||||||
There is only one `enter_tag` column, which is used for both long and short trades.
|
|
||||||
As a consequence, this column must be treated as "last write wins" (it's just a dataframe column after all).
|
|
||||||
In fancy situations, where multiple signals collide (or if signals are deactivated again based on different conditions), this can lead to odd results with the wrong tag applied to an entry signal.
|
|
||||||
These results are a consequence of the strategy overwriting prior tags - where the last tag will "stick" and will be the one freqtrade will use.
|
|
||||||
|
|
||||||
## Exit tag
|
## Exit tag
|
||||||
|
|
||||||
Similar to [Buy Tagging](#buy-tag), you can also specify a sell tag.
|
Similar to [Buy Tagging](#buy-tag), you can also specify a sell tag.
|
||||||
|
@@ -75,7 +75,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Stake size management
|
### Stake size management
|
||||||
|
|
||||||
Called before entering a trade, makes it possible to manage your position size when placing a new trade.
|
Called before entering a trade, makes it possible to manage your position size when placing a new trade.
|
||||||
|
|
||||||
@@ -159,7 +159,6 @@ The stoploss price can only ever move upwards - if the stoploss value returned f
|
|||||||
|
|
||||||
The method must return a stoploss value (float / number) as a percentage of the current price.
|
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.
|
E.g. If the `current_rate` is 200 USD, then returning `0.02` will set the stoploss price 2% lower, at 196 USD.
|
||||||
During backtesting, `current_rate` (and `current_profit`) are provided against the candle's high (or low for short trades) - while the resulting stoploss is evaluated against the candle's low (or high for short trades).
|
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -424,7 +423,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
!!! Warning "Backtesting"
|
!!! Warning "Backtesting"
|
||||||
Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range.
|
Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range.
|
||||||
Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle.
|
Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle.
|
||||||
`custom_exit_price()` is only called for sells of type exit_signal, Custom exit and partial exits. All other exit-types will use regular backtesting prices.
|
`custom_exit_price()` is only called for sells of type exit_signal and Custom exit. All other exit-types will use regular backtesting prices.
|
||||||
|
|
||||||
## Custom order timeout rules
|
## Custom order timeout rules
|
||||||
|
|
||||||
@@ -644,7 +643,7 @@ This callback is **not** called when there is an open order (either buy or sell)
|
|||||||
|
|
||||||
Additional Buys are ignored once you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`, but the callback is called anyway looking for partial exits.
|
Additional Buys are ignored once you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`, but the callback is called anyway looking for partial exits.
|
||||||
|
|
||||||
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase your position (negative values will decrease your position), no matter if it's a long or short trade. Modifications to leverage are not possible, and the stake-amount is assumed to be before applying leverage.
|
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase your position (negative values will decrease your position), no matter if it's a long or short trade. Modifications to leverage are not possible.
|
||||||
|
|
||||||
!!! Note "About stake size"
|
!!! Note "About stake size"
|
||||||
Using fixed stake size means it will be the amount used for the first order, just like without position adjustment.
|
Using fixed stake size means it will be the amount used for the first order, just like without position adjustment.
|
||||||
@@ -655,7 +654,7 @@ Position adjustments will always be applied in the direction of the trade, so a
|
|||||||
Stoploss is still calculated from the initial opening price, not averaged price.
|
Stoploss is still calculated from the initial opening price, not averaged price.
|
||||||
Regular stoploss rules still apply (cannot move down).
|
Regular stoploss rules still apply (cannot move down).
|
||||||
|
|
||||||
While `/stopentry` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
|
While `/stopbuy` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
|
||||||
|
|
||||||
!!! Warning "Backtesting"
|
!!! Warning "Backtesting"
|
||||||
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so run-time performance will be affected.
|
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so run-time performance will be affected.
|
||||||
|
@@ -166,7 +166,7 @@ Additional technical libraries can be installed as necessary, or custom indicato
|
|||||||
|
|
||||||
Most indicators have an instable startup period, in which they are either not available (NaN), or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be.
|
Most indicators have an instable startup period, in which they are either not available (NaN), or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be.
|
||||||
To account for this, the strategy can be assigned the `startup_candle_count` attribute.
|
To account for this, the strategy can be assigned the `startup_candle_count` attribute.
|
||||||
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In the case where a user includes higher timeframes with informative pairs, the `startup_candle_count` does not necessarily change. The value is the maximum period (in candles) that any of the informatives timeframes need to compute stable indicators.
|
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.
|
||||||
|
|
||||||
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
|
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
|
||||||
|
|
||||||
@@ -264,8 +264,7 @@ def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFram
|
|||||||
### Exit signal rules
|
### Exit signal rules
|
||||||
|
|
||||||
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
|
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
|
||||||
The exit-signal is only used for exits if `use_exit_signal` is set to true in the configuration.
|
Please note that the exit-signal is only used if `use_exit_signal` is set to true in the configuration.
|
||||||
`use_exit_signal` will not influence [signal collision rules](#colliding-signals) - which will still apply and can prevent entries.
|
|
||||||
|
|
||||||
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
||||||
|
|
||||||
@@ -446,17 +445,15 @@ A full sample can be found [in the DataProvider section](#complete-data-provider
|
|||||||
|
|
||||||
??? Note "Alternative candle types"
|
??? Note "Alternative candle types"
|
||||||
Informative_pairs can also provide a 3rd tuple element defining the candle type explicitly.
|
Informative_pairs can also provide a 3rd tuple element defining the candle type explicitly.
|
||||||
Availability of alternative candle-types will depend on the trading-mode and the exchange.
|
Availability of alternative candle-types will depend on the trading-mode and the exchange. Details about this can be found in the exchange documentation.
|
||||||
In general, spot pairs cannot be used in futures markets, and futures candles can't be used as informative pairs for spot bots.
|
|
||||||
Details about this may vary, if they do, this can be found in the exchange documentation.
|
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
def informative_pairs(self):
|
def informative_pairs(self):
|
||||||
return [
|
return [
|
||||||
("ETH/USDT", "5m", ""), # Uses default candletype, depends on trading_mode (recommended)
|
("ETH/USDT", "5m", ""), # Uses default candletype, depends on trading_mode
|
||||||
("ETH/USDT", "5m", "spot"), # Forces usage of spot candles (only valid for bots running on spot markets).
|
("ETH/USDT", "5m", "spot"), # Forces usage of spot candles
|
||||||
("BTC/TUSD", "15m", "futures"), # Uses futures candles (only bots with `trading_mode=futures`)
|
("BTC/TUSD", "15m", "futures"), # Uses futures candles
|
||||||
("BTC/TUSD", "15m", "mark"), # Uses mark candles (only bots with `trading_mode=futures`)
|
("BTC/TUSD", "15m", "mark"), # Uses mark candles
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
***
|
***
|
||||||
@@ -657,13 +654,13 @@ This is where calling `self.dp.current_whitelist()` comes in handy.
|
|||||||
# fetch live / historical candle (OHLCV) data for the first informative pair
|
# fetch live / historical candle (OHLCV) data for the first informative pair
|
||||||
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
inf_pair, inf_timeframe = self.informative_pairs()[0]
|
||||||
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
informative = self.dp.get_pair_dataframe(pair=inf_pair,
|
||||||
timeframe=inf_timeframe)
|
timeframe=inf_timeframe)
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning "Warning about backtesting"
|
!!! Warning "Warning about backtesting"
|
||||||
In backtesting, `dp.get_pair_dataframe()` behavior differs depending on where it's called.
|
Be careful when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
|
||||||
Within `populate_*()` methods, `dp.get_pair_dataframe()` returns the full timerange. Please make sure to not "look into the future" to avoid surprises when running in dry/live mode.
|
for the backtesting runmode) provides the full time-range in one go,
|
||||||
Within [callbacks](strategy-callbacks.md), you'll get the full timerange up to the current (simulated) candle.
|
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode.
|
||||||
|
|
||||||
### *get_analyzed_dataframe(pair, timeframe)*
|
### *get_analyzed_dataframe(pair, timeframe)*
|
||||||
|
|
||||||
@@ -672,13 +669,13 @@ It can also be used in specific callbacks to get the signal that caused the acti
|
|||||||
|
|
||||||
``` python
|
``` python
|
||||||
# fetch current dataframe
|
# fetch current dataframe
|
||||||
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.
|
||||||
You can check for this with `if dataframe.empty:` and handle this case accordingly.
|
|
||||||
This should not happen when using whitelisted pairs.
|
This should not happen when using whitelisted pairs.
|
||||||
|
|
||||||
### *orderbook(pair, maximum)*
|
### *orderbook(pair, maximum)*
|
||||||
@@ -725,7 +722,7 @@ if self.dp.runmode.value in ('live', 'dry_run'):
|
|||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
Although the ticker data structure is a part of the ccxt Unified Interface, the values returned by this method can
|
Although the ticker data structure is a part of the ccxt Unified Interface, the values returned by this method can
|
||||||
vary for different exchanges. For instance, many exchanges do not return `vwap` values, some exchanges
|
vary for different exchanges. For instance, many exchanges do not return `vwap` values, the FTX exchange
|
||||||
does not always fills in the `last` field (so it can be None), etc. So you need to carefully verify the ticker
|
does not always fills in the `last` field (so it can be None), etc. So you need to carefully verify the ticker
|
||||||
data returned from the exchange and add appropriate error handling / defaults.
|
data returned from the exchange and add appropriate error handling / defaults.
|
||||||
|
|
||||||
@@ -827,8 +824,6 @@ Options:
|
|||||||
- Merge the dataframe without lookahead bias
|
- Merge the dataframe without lookahead bias
|
||||||
- Forward-fill (optional)
|
- Forward-fill (optional)
|
||||||
|
|
||||||
For a full sample, please refer to the [complete data provider example](#complete-data-provider-sample) below.
|
|
||||||
|
|
||||||
All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
|
All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
|
||||||
|
|
||||||
!!! Example "Column renaming"
|
!!! Example "Column renaming"
|
||||||
|
@@ -43,25 +43,19 @@ Note : `forcesell`, `forcebuy`, `emergencysell` are changed to `force_exit`, `fo
|
|||||||
* `order_time_in_force` buy -> entry, sell -> exit.
|
* `order_time_in_force` buy -> entry, sell -> exit.
|
||||||
* `order_types` buy -> entry, sell -> exit.
|
* `order_types` buy -> entry, sell -> exit.
|
||||||
* `unfilledtimeout` buy -> entry, sell -> exit.
|
* `unfilledtimeout` buy -> entry, sell -> exit.
|
||||||
* `ignore_buying_expired_candle_after` -> moved to root level instead of "ask_strategy/exit_pricing"
|
|
||||||
* Terminology changes
|
* Terminology changes
|
||||||
* Sell reasons changed to reflect the new naming of "exit" instead of sells. Be careful in your strategy if you're using `exit_reason` checks and eventually update your strategy.
|
* Sell reasons changed to reflect the new naming of "exit" instead of sells. Be careful in your strategy if you're using `exit_reason` checks and eventually update your strategy.
|
||||||
* `sell_signal` -> `exit_signal`
|
* `sell_signal` -> `exit_signal`
|
||||||
* `custom_sell` -> `custom_exit`
|
* `custom_sell` -> `custom_exit`
|
||||||
* `force_sell` -> `force_exit`
|
* `force_sell` -> `force_exit`
|
||||||
* `emergency_sell` -> `emergency_exit`
|
* `emergency_sell` -> `emergency_exit`
|
||||||
* Order pricing
|
|
||||||
* `bid_strategy` -> `entry_pricing`
|
|
||||||
* `ask_strategy` -> `exit_pricing`
|
|
||||||
* `ask_last_balance` -> `price_last_balance`
|
|
||||||
* `bid_last_balance` -> `price_last_balance`
|
|
||||||
* Webhook terminology changed from "sell" to "exit", and from "buy" to entry
|
* Webhook terminology changed from "sell" to "exit", and from "buy" to entry
|
||||||
* `webhookbuy` -> `entry`
|
* `webhookbuy` -> `webhookentry`
|
||||||
* `webhookbuyfill` -> `entry_fill`
|
* `webhookbuyfill` -> `webhookentryfill`
|
||||||
* `webhookbuycancel` -> `entry_cancel`
|
* `webhookbuycancel` -> `webhookentrycancel`
|
||||||
* `webhooksell` -> `exit`
|
* `webhooksell` -> `webhookexit`
|
||||||
* `webhooksellfill` -> `exit_fill`
|
* `webhooksellfill` -> `webhookexitfill`
|
||||||
* `webhooksellcancel` -> `exit_cancel`
|
* `webhooksellcancel` -> `webhookexitcancel`
|
||||||
* Telegram notification settings
|
* Telegram notification settings
|
||||||
* `buy` -> `entry`
|
* `buy` -> `entry`
|
||||||
* `buy_fill` -> `entry_fill`
|
* `buy_fill` -> `entry_fill`
|
||||||
@@ -338,8 +332,8 @@ After:
|
|||||||
|
|
||||||
``` python hl_lines="2 3"
|
``` python hl_lines="2 3"
|
||||||
order_time_in_force: Dict = {
|
order_time_in_force: Dict = {
|
||||||
"entry": "GTC",
|
"entry": "gtc",
|
||||||
"exit": "GTC",
|
"exit": "gtc",
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -449,7 +443,6 @@ Please refer to the [pricing documentation](configuration.md#prices-used-for-ord
|
|||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
"bid_last_balance": 0.0
|
"bid_last_balance": 0.0
|
||||||
"ignore_buying_expired_candle_after": 120
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -473,7 +466,6 @@ after:
|
|||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
"price_last_balance": 0.0
|
"price_last_balance": 0.0
|
||||||
},
|
}
|
||||||
"ignore_buying_expired_candle_after": 120
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@@ -77,14 +77,11 @@ Example configuration showing the different settings:
|
|||||||
"enabled": true,
|
"enabled": true,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
"chat_id": "your_telegram_chat_id",
|
"chat_id": "your_telegram_chat_id",
|
||||||
"allow_custom_messages": true,
|
|
||||||
"notification_settings": {
|
"notification_settings": {
|
||||||
"status": "silent",
|
"status": "silent",
|
||||||
"warning": "on",
|
"warning": "on",
|
||||||
"startup": "off",
|
"startup": "off",
|
||||||
"entry": "silent",
|
"entry": "silent",
|
||||||
"entry_fill": "on",
|
|
||||||
"entry_cancel": "silent",
|
|
||||||
"exit": {
|
"exit": {
|
||||||
"roi": "silent",
|
"roi": "silent",
|
||||||
"emergency_exit": "on",
|
"emergency_exit": "on",
|
||||||
@@ -93,10 +90,11 @@ Example configuration showing the different settings:
|
|||||||
"trailing_stop_loss": "on",
|
"trailing_stop_loss": "on",
|
||||||
"stop_loss": "on",
|
"stop_loss": "on",
|
||||||
"stoploss_on_exchange": "on",
|
"stoploss_on_exchange": "on",
|
||||||
"custom_exit": "silent",
|
"custom_exit": "silent"
|
||||||
"partial_exit": "on"
|
|
||||||
},
|
},
|
||||||
|
"entry_cancel": "silent",
|
||||||
"exit_cancel": "on",
|
"exit_cancel": "on",
|
||||||
|
"entry_fill": "off",
|
||||||
"exit_fill": "off",
|
"exit_fill": "off",
|
||||||
"protection_trigger": "off",
|
"protection_trigger": "off",
|
||||||
"protection_trigger_global": "on",
|
"protection_trigger_global": "on",
|
||||||
@@ -116,7 +114,6 @@ Example configuration showing the different settings:
|
|||||||
`show_candle` - show candle values as part of entry/exit messages. Only possible values are `"ohlc"` or `"off"`.
|
`show_candle` - show candle values as part of entry/exit messages. Only possible values are `"ohlc"` or `"off"`.
|
||||||
|
|
||||||
`balance_dust_level` will define what the `/balance` command takes as "dust" - Currencies with a balance below this will be shown.
|
`balance_dust_level` will define what the `/balance` command takes as "dust" - Currencies with a balance below this will be shown.
|
||||||
`allow_custom_messages` completely disable strategy messages.
|
|
||||||
`reload` allows you to disable reload-buttons on selected messages.
|
`reload` allows you to disable reload-buttons on selected messages.
|
||||||
|
|
||||||
## Create a custom keyboard (command shortcut buttons)
|
## Create a custom keyboard (command shortcut buttons)
|
||||||
@@ -141,7 +138,7 @@ You can create your own keyboard in `config.json`:
|
|||||||
"enabled": true,
|
"enabled": true,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
"chat_id": "your_telegram_chat_id",
|
"chat_id": "your_telegram_chat_id",
|
||||||
"keyboard": [
|
"keyboard": [
|
||||||
["/daily", "/stats", "/balance", "/profit"],
|
["/daily", "/stats", "/balance", "/profit"],
|
||||||
["/status table", "/performance"],
|
["/status table", "/performance"],
|
||||||
["/reload_config", "/count", "/logs"]
|
["/reload_config", "/count", "/logs"]
|
||||||
@@ -152,7 +149,7 @@ You can create your own keyboard in `config.json`:
|
|||||||
!!! Note "Supported Commands"
|
!!! Note "Supported Commands"
|
||||||
Only the following commands are allowed. Command arguments are not supported!
|
Only the following commands are allowed. Command arguments are not supported!
|
||||||
|
|
||||||
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopentry`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
|
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopbuy`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
|
||||||
|
|
||||||
## Telegram commands
|
## Telegram commands
|
||||||
|
|
||||||
@@ -164,7 +161,7 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
|----------|-------------|
|
|----------|-------------|
|
||||||
| `/start` | Starts the trader
|
| `/start` | Starts the trader
|
||||||
| `/stop` | Stops the trader
|
| `/stop` | Stops the trader
|
||||||
| `/stopbuy | /stopentry` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `/stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `/reload_config` | Reloads the configuration file
|
| `/reload_config` | Reloads the configuration file
|
||||||
| `/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.
|
||||||
@@ -228,16 +225,16 @@ Once all positions are sold, run `/stop` to completely stop the bot.
|
|||||||
For each open trade, the bot will send you the following message.
|
For each open trade, the bot will send you the following message.
|
||||||
Enter Tag is configurable via Strategy.
|
Enter Tag is configurable via Strategy.
|
||||||
|
|
||||||
> **Trade ID:** `123` `(since 1 days ago)`
|
> **Trade ID:** `123` `(since 1 days ago)`
|
||||||
> **Current Pair:** CVC/BTC
|
> **Current Pair:** CVC/BTC
|
||||||
> **Direction:** Long
|
> **Direction:** Long
|
||||||
> **Leverage:** 1.0
|
> **Leverage:** 1.0
|
||||||
> **Amount:** `26.64180098`
|
> **Amount:** `26.64180098`
|
||||||
> **Enter Tag:** Awesome Long Signal
|
> **Enter Tag:** Awesome Long Signal
|
||||||
> **Open Rate:** `0.00007489`
|
> **Open Rate:** `0.00007489`
|
||||||
> **Current Rate:** `0.00007489`
|
> **Current Rate:** `0.00007489`
|
||||||
> **Current Profit:** `12.95%`
|
> **Current Profit:** `12.95%`
|
||||||
> **Stoploss:** `0.00007389 (-0.02%)`
|
> **Stoploss:** `0.00007389 (-0.02%)`
|
||||||
|
|
||||||
### /status table
|
### /status table
|
||||||
|
|
||||||
@@ -264,26 +261,26 @@ current max
|
|||||||
|
|
||||||
Return a summary of your profit/loss and performance.
|
Return a summary of your profit/loss and performance.
|
||||||
|
|
||||||
> **ROI:** Close trades
|
> **ROI:** Close trades
|
||||||
> ∙ `0.00485701 BTC (2.2%) (15.2 Σ%)`
|
> ∙ `0.00485701 BTC (2.2%) (15.2 Σ%)`
|
||||||
> ∙ `62.968 USD`
|
> ∙ `62.968 USD`
|
||||||
> **ROI:** All trades
|
> **ROI:** All trades
|
||||||
> ∙ `0.00255280 BTC (1.5%) (6.43 Σ%)`
|
> ∙ `0.00255280 BTC (1.5%) (6.43 Σ%)`
|
||||||
> ∙ `33.095 EUR`
|
> ∙ `33.095 EUR`
|
||||||
>
|
>
|
||||||
> **Total Trade Count:** `138`
|
> **Total Trade Count:** `138`
|
||||||
> **First Trade opened:** `3 days ago`
|
> **First Trade opened:** `3 days ago`
|
||||||
> **Latest Trade opened:** `2 minutes ago`
|
> **Latest Trade opened:** `2 minutes ago`
|
||||||
> **Avg. Duration:** `2:33:45`
|
> **Avg. Duration:** `2:33:45`
|
||||||
> **Best Performing:** `PAY/BTC: 50.23%`
|
> **Best Performing:** `PAY/BTC: 50.23%`
|
||||||
> **Trading volume:** `0.5 BTC`
|
> **Trading volume:** `0.5 BTC`
|
||||||
> **Profit factor:** `1.04`
|
> **Profit factor:** `1.04`
|
||||||
> **Max Drawdown:** `9.23% (0.01255 BTC)`
|
> **Max Drawdown:** `9.23% (0.01255 BTC)`
|
||||||
|
|
||||||
The relative profit of `1.2%` is the average profit per trade.
|
The relative profit of `1.2%` is the average profit per trade.
|
||||||
The relative profit of `15.2 Σ%` is be based on the starting capital - so in this case, the starting capital was `0.00485701 * 1.152 = 0.00738 BTC`.
|
The relative profit of `15.2 Σ%` is be based on the starting capital - so in this case, the starting capital was `0.00485701 * 1.152 = 0.00738 BTC`.
|
||||||
Starting capital is either taken from the `available_capital` setting, or calculated by using current wallet size - profits.
|
Starting capital is either taken from the `available_capital` setting, or calculated by using current wallet size - profits.
|
||||||
Profit Factor is calculated as gross profits / gross losses - and should serve as an overall metric for the strategy.
|
Profit Factor is calculated as gross profits / gross losses - and should serve as an overall metric for the strategy.
|
||||||
Max drawdown corresponds to the backtesting metric `Absolute Drawdown (Account)` - calculated as `(Absolute Drawdown) / (DrawdownHigh + startingBalance)`.
|
Max drawdown corresponds to the backtesting metric `Absolute Drawdown (Account)` - calculated as `(Absolute Drawdown) / (DrawdownHigh + startingBalance)`.
|
||||||
|
|
||||||
### /forceexit <trade_id>
|
### /forceexit <trade_id>
|
||||||
@@ -312,27 +309,27 @@ Note that for this to work, `force_entry_enable` needs to be set to true.
|
|||||||
### /performance
|
### /performance
|
||||||
|
|
||||||
Return the performance of each crypto-currency the bot has sold.
|
Return the performance of each crypto-currency the bot has sold.
|
||||||
> Performance:
|
> Performance:
|
||||||
> 1. `RCN/BTC 0.003 BTC (57.77%) (1)`
|
> 1. `RCN/BTC 0.003 BTC (57.77%) (1)`
|
||||||
> 2. `PAY/BTC 0.0012 BTC (56.91%) (1)`
|
> 2. `PAY/BTC 0.0012 BTC (56.91%) (1)`
|
||||||
> 3. `VIB/BTC 0.0011 BTC (47.07%) (1)`
|
> 3. `VIB/BTC 0.0011 BTC (47.07%) (1)`
|
||||||
> 4. `SALT/BTC 0.0010 BTC (30.24%) (1)`
|
> 4. `SALT/BTC 0.0010 BTC (30.24%) (1)`
|
||||||
> 5. `STORJ/BTC 0.0009 BTC (27.24%) (1)`
|
> 5. `STORJ/BTC 0.0009 BTC (27.24%) (1)`
|
||||||
> ...
|
> ...
|
||||||
|
|
||||||
### /balance
|
### /balance
|
||||||
|
|
||||||
Return the balance of all crypto-currency your have on the exchange.
|
Return the balance of all crypto-currency your have on the exchange.
|
||||||
|
|
||||||
> **Currency:** BTC
|
> **Currency:** BTC
|
||||||
> **Available:** 3.05890234
|
> **Available:** 3.05890234
|
||||||
> **Balance:** 3.05890234
|
> **Balance:** 3.05890234
|
||||||
> **Pending:** 0.0
|
> **Pending:** 0.0
|
||||||
|
|
||||||
> **Currency:** CVC
|
> **Currency:** CVC
|
||||||
> **Available:** 86.64180098
|
> **Available:** 86.64180098
|
||||||
> **Balance:** 86.64180098
|
> **Balance:** 86.64180098
|
||||||
> **Pending:** 0.0
|
> **Pending:** 0.0
|
||||||
|
|
||||||
### /daily <n>
|
### /daily <n>
|
||||||
|
|
||||||
@@ -379,7 +376,7 @@ Month (count) Profit BTC Profit USD Profit %
|
|||||||
|
|
||||||
Shows the current whitelist
|
Shows the current whitelist
|
||||||
|
|
||||||
> Using whitelist `StaticPairList` with 22 pairs
|
> Using whitelist `StaticPairList` with 22 pairs
|
||||||
> `IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC`
|
> `IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC`
|
||||||
|
|
||||||
### /blacklist [pair]
|
### /blacklist [pair]
|
||||||
@@ -389,7 +386,7 @@ If Pair is set, then this pair will be added to the pairlist.
|
|||||||
Also supports multiple pairs, separated by a space.
|
Also supports multiple pairs, separated by a space.
|
||||||
Use `/reload_config` to reset the blacklist.
|
Use `/reload_config` to reset the blacklist.
|
||||||
|
|
||||||
> Using blacklist `StaticPairList` with 2 pairs
|
> Using blacklist `StaticPairList` with 2 pairs
|
||||||
>`DODGE/BTC`, `HOT/BTC`.
|
>`DODGE/BTC`, `HOT/BTC`.
|
||||||
|
|
||||||
### /edge
|
### /edge
|
||||||
|
@@ -37,12 +37,3 @@ pip install -e .
|
|||||||
# Ensure freqUI is at the latest version
|
# Ensure freqUI is at the latest version
|
||||||
freqtrade install-ui
|
freqtrade install-ui
|
||||||
```
|
```
|
||||||
|
|
||||||
### Problems updating
|
|
||||||
|
|
||||||
Update-problems usually come missing dependencies (you didn't follow the above instructions) - or from updated dependencies, which fail to install (for example TA-lib).
|
|
||||||
Please refer to the corresponding installation sections (common problems linked below)
|
|
||||||
|
|
||||||
Common problems and their solutions:
|
|
||||||
|
|
||||||
* [ta-lib update on windows](windows_installation.md#2-install-ta-lib)
|
|
||||||
|
@@ -169,43 +169,6 @@ Example: Search dedicated strategy path.
|
|||||||
freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/
|
freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/
|
||||||
```
|
```
|
||||||
|
|
||||||
## List freqAI models
|
|
||||||
|
|
||||||
Use the `list-freqaimodels` subcommand to see all freqAI models available.
|
|
||||||
|
|
||||||
This subcommand is useful for finding problems in your environment with loading freqAI models: modules with models that contain errors and failed to load are printed in red (LOAD FAILED), while models with duplicate names are printed in yellow (DUPLICATE NAME).
|
|
||||||
|
|
||||||
```
|
|
||||||
usage: freqtrade list-freqaimodels [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|
||||||
[-d PATH] [--userdir PATH]
|
|
||||||
[--freqaimodel-path PATH] [-1] [--no-color]
|
|
||||||
|
|
||||||
optional arguments:
|
|
||||||
-h, --help show this help message and exit
|
|
||||||
--freqaimodel-path PATH
|
|
||||||
Specify additional lookup path for freqaimodels.
|
|
||||||
-1, --one-column Print output in one column.
|
|
||||||
--no-color Disable colorization of hyperopt results. May be
|
|
||||||
useful if you are redirecting output to a file.
|
|
||||||
|
|
||||||
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, --data-dir PATH
|
|
||||||
Path to directory with historical backtesting data.
|
|
||||||
--userdir PATH, --user-data-dir PATH
|
|
||||||
Path to userdata directory.
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## List Exchanges
|
## List Exchanges
|
||||||
|
|
||||||
Use the `list-exchanges` subcommand to see the exchanges available for the bot.
|
Use the `list-exchanges` subcommand to see the exchanges available for the bot.
|
||||||
@@ -263,6 +226,7 @@ equos True missing opt: fetchTicker, fetchTickers
|
|||||||
eterbase True
|
eterbase True
|
||||||
fcoin True missing opt: fetchMyTrades, fetchTickers
|
fcoin True missing opt: fetchMyTrades, fetchTickers
|
||||||
fcoinjp True missing opt: fetchMyTrades, fetchTickers
|
fcoinjp True missing opt: fetchMyTrades, fetchTickers
|
||||||
|
ftx True
|
||||||
gateio True
|
gateio True
|
||||||
gemini True
|
gemini True
|
||||||
gopax True
|
gopax True
|
||||||
@@ -368,6 +332,7 @@ fcoin True missing opt: fetchMyTrades, fetchTickers
|
|||||||
fcoinjp True missing opt: fetchMyTrades, fetchTickers
|
fcoinjp True missing opt: fetchMyTrades, fetchTickers
|
||||||
flowbtc False missing: fetchOrder, fetchOHLCV
|
flowbtc False missing: fetchOrder, fetchOHLCV
|
||||||
foxbit False missing: fetchOrder, fetchOHLCV
|
foxbit False missing: fetchOrder, fetchOHLCV
|
||||||
|
ftx True
|
||||||
gateio True
|
gateio True
|
||||||
gemini True
|
gemini True
|
||||||
gopax True
|
gopax True
|
||||||
@@ -560,14 +525,12 @@ 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.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade test-pairlist [-h] [--userdir PATH] [-v] [-c PATH]
|
usage: freqtrade test-pairlist [-h] [-v] [-c PATH]
|
||||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||||
[-1] [--print-json] [--exchange EXCHANGE]
|
[-1] [--print-json] [--exchange EXCHANGE]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--userdir PATH, --user-data-dir PATH
|
|
||||||
Path to userdata directory.
|
|
||||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default:
|
Specify configuration file (default:
|
||||||
|
@@ -10,37 +10,37 @@ Sample configuration (tested using IFTTT).
|
|||||||
"webhook": {
|
"webhook": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"url": "https://maker.ifttt.com/trigger/<YOUREVENT>/with/key/<YOURKEY>/",
|
"url": "https://maker.ifttt.com/trigger/<YOUREVENT>/with/key/<YOURKEY>/",
|
||||||
"entry": {
|
"webhookentry": {
|
||||||
"value1": "Buying {pair}",
|
"value1": "Buying {pair}",
|
||||||
"value2": "limit {limit:8f}",
|
"value2": "limit {limit:8f}",
|
||||||
"value3": "{stake_amount:8f} {stake_currency}"
|
"value3": "{stake_amount:8f} {stake_currency}"
|
||||||
},
|
},
|
||||||
"entry_cancel": {
|
"webhookentrycancel": {
|
||||||
"value1": "Cancelling Open Buy Order for {pair}",
|
"value1": "Cancelling Open Buy Order for {pair}",
|
||||||
"value2": "limit {limit:8f}",
|
"value2": "limit {limit:8f}",
|
||||||
"value3": "{stake_amount:8f} {stake_currency}"
|
"value3": "{stake_amount:8f} {stake_currency}"
|
||||||
},
|
},
|
||||||
"entry_fill": {
|
"webhookentryfill": {
|
||||||
"value1": "Buy Order for {pair} filled",
|
"value1": "Buy Order for {pair} filled",
|
||||||
"value2": "at {open_rate:8f}",
|
"value2": "at {open_rate:8f}",
|
||||||
"value3": ""
|
"value3": ""
|
||||||
},
|
},
|
||||||
"exit": {
|
"webhookexit": {
|
||||||
"value1": "Exiting {pair}",
|
"value1": "Exiting {pair}",
|
||||||
"value2": "limit {limit:8f}",
|
"value2": "limit {limit:8f}",
|
||||||
"value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})"
|
"value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})"
|
||||||
},
|
},
|
||||||
"exit_cancel": {
|
"webhookexitcancel": {
|
||||||
"value1": "Cancelling Open Exit Order for {pair}",
|
"value1": "Cancelling Open Exit Order for {pair}",
|
||||||
"value2": "limit {limit:8f}",
|
"value2": "limit {limit:8f}",
|
||||||
"value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})"
|
"value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})"
|
||||||
},
|
},
|
||||||
"exit_fill": {
|
"webhookexitfill": {
|
||||||
"value1": "Exit Order for {pair} filled",
|
"value1": "Exit Order for {pair} filled",
|
||||||
"value2": "at {close_rate:8f}.",
|
"value2": "at {close_rate:8f}.",
|
||||||
"value3": ""
|
"value3": ""
|
||||||
},
|
},
|
||||||
"status": {
|
"webhookstatus": {
|
||||||
"value1": "Status: {status}",
|
"value1": "Status: {status}",
|
||||||
"value2": "",
|
"value2": "",
|
||||||
"value3": ""
|
"value3": ""
|
||||||
@@ -57,7 +57,7 @@ You can set the POST body format to Form-Encoded (default), JSON-Encoded, or raw
|
|||||||
"enabled": true,
|
"enabled": true,
|
||||||
"url": "https://<YOURSUBDOMAIN>.cloud.mattermost.com/hooks/<YOURHOOK>",
|
"url": "https://<YOURSUBDOMAIN>.cloud.mattermost.com/hooks/<YOURHOOK>",
|
||||||
"format": "json",
|
"format": "json",
|
||||||
"status": {
|
"webhookstatus": {
|
||||||
"text": "Status: {status}"
|
"text": "Status: {status}"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -88,30 +88,17 @@ Optional parameters are available to enable automatic retries for webhook messag
|
|||||||
"url": "https://<YOURHOOKURL>",
|
"url": "https://<YOURHOOKURL>",
|
||||||
"retries": 3,
|
"retries": 3,
|
||||||
"retry_delay": 0.2,
|
"retry_delay": 0.2,
|
||||||
"status": {
|
"webhookstatus": {
|
||||||
"status": "Status: {status}"
|
"status": "Status: {status}"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
Custom messages can be sent to Webhook endpoints via the `self.dp.send_msg()` function from within the strategy. To enable this, set the `allow_custom_messages` option to `true`:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"webhook": {
|
|
||||||
"enabled": true,
|
|
||||||
"url": "https://<YOURHOOKURL>",
|
|
||||||
"allow_custom_messages": true,
|
|
||||||
"strategy_msg": {
|
|
||||||
"status": "StrategyMessage: {msg}"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
### Entry
|
### Webhookentry
|
||||||
|
|
||||||
The fields in `webhook.entry` are filled when the bot executes a long/short. Parameters are filled using string.format.
|
The fields in `webhook.webhookentry` are filled when the bot executes a long/short. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* `trade_id`
|
* `trade_id`
|
||||||
@@ -131,9 +118,9 @@ Possible parameters are:
|
|||||||
* `current_rate`
|
* `current_rate`
|
||||||
* `enter_tag`
|
* `enter_tag`
|
||||||
|
|
||||||
### Entry cancel
|
### Webhookentrycancel
|
||||||
|
|
||||||
The fields in `webhook.entry_cancel` are filled when the bot cancels a long/short order. Parameters are filled using string.format.
|
The fields in `webhook.webhookentrycancel` are filled when the bot cancels a long/short order. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* `trade_id`
|
* `trade_id`
|
||||||
@@ -152,9 +139,9 @@ Possible parameters are:
|
|||||||
* `current_rate`
|
* `current_rate`
|
||||||
* `enter_tag`
|
* `enter_tag`
|
||||||
|
|
||||||
### Entry fill
|
### Webhookentryfill
|
||||||
|
|
||||||
The fields in `webhook.entry_fill` are filled when the bot filled a long/short order. Parameters are filled using string.format.
|
The fields in `webhook.webhookentryfill` are filled when the bot filled a long/short order. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* `trade_id`
|
* `trade_id`
|
||||||
@@ -173,9 +160,9 @@ Possible parameters are:
|
|||||||
* `current_rate`
|
* `current_rate`
|
||||||
* `enter_tag`
|
* `enter_tag`
|
||||||
|
|
||||||
### Exit
|
### Webhookexit
|
||||||
|
|
||||||
The fields in `webhook.exit` are filled when the bot exits a trade. Parameters are filled using string.format.
|
The fields in `webhook.webhookexit` are filled when the bot exits a trade. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* `trade_id`
|
* `trade_id`
|
||||||
@@ -197,9 +184,9 @@ Possible parameters are:
|
|||||||
* `open_date`
|
* `open_date`
|
||||||
* `close_date`
|
* `close_date`
|
||||||
|
|
||||||
### Exit fill
|
### Webhookexitfill
|
||||||
|
|
||||||
The fields in `webhook.exit_fill` are filled when the bot fills a exit order (closes a Trade). Parameters are filled using string.format.
|
The fields in `webhook.webhookexitfill` are filled when the bot fills a exit order (closes a Trade). Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* `trade_id`
|
* `trade_id`
|
||||||
@@ -222,9 +209,9 @@ Possible parameters are:
|
|||||||
* `open_date`
|
* `open_date`
|
||||||
* `close_date`
|
* `close_date`
|
||||||
|
|
||||||
### Exit cancel
|
### Webhookexitcancel
|
||||||
|
|
||||||
The fields in `webhook.exit_cancel` are filled when the bot cancels a exit order. Parameters are filled using string.format.
|
The fields in `webhook.webhookexitcancel` are filled when the bot cancels a exit order. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
* `trade_id`
|
* `trade_id`
|
||||||
@@ -247,9 +234,9 @@ Possible parameters are:
|
|||||||
* `open_date`
|
* `open_date`
|
||||||
* `close_date`
|
* `close_date`
|
||||||
|
|
||||||
### Status
|
### Webhookstatus
|
||||||
|
|
||||||
The fields in `webhook.status` are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format.
|
The fields in `webhook.webhookstatus` are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format.
|
||||||
|
|
||||||
The only possible value here is `{status}`.
|
The only possible value here is `{status}`.
|
||||||
|
|
||||||
@@ -293,6 +280,7 @@ You can configure this as follows:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
The above represents the default (`exit_fill` and `entry_fill` are optional and will default to the above configuration) - modifications are obviously possible.
|
The above represents the default (`exit_fill` and `entry_fill` are optional and will default to the above configuration) - modifications are obviously possible.
|
||||||
|
|
||||||
Available fields correspond to the fields for webhooks and are documented in the corresponding webhook sections.
|
Available fields correspond to the fields for webhooks and are documented in the corresponding webhook sections.
|
||||||
@@ -300,13 +288,3 @@ Available fields correspond to the fields for webhooks and are documented in the
|
|||||||
The notifications will look as follows by default.
|
The notifications will look as follows by default.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
Custom messages can be sent from a strategy to Discord endpoints via the dataprovider.send_msg() function. To enable this, set the `allow_custom_messages` option to `true`:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"discord": {
|
|
||||||
"enabled": true,
|
|
||||||
"webhook_url": "https://discord.com/api/webhooks/<Your webhook URL ...>",
|
|
||||||
"allow_custom_messages": true,
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
@@ -3,16 +3,15 @@
|
|||||||
We **strongly** recommend that Windows users use [Docker](docker_quickstart.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, please follow the instructions below.
|
Otherwise, try the instructions below.
|
||||||
|
|
||||||
## Install freqtrade manually
|
## Install freqtrade manually
|
||||||
|
|
||||||
!!! Note "64bit Python version"
|
!!! Note
|
||||||
Please make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
|
Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
|
||||||
32bit python versions are no longer supported under Windows.
|
|
||||||
|
|
||||||
!!! Hint
|
!!! Hint
|
||||||
Using the [Anaconda Distribution](https://www.anaconda.com/distribution/) under Windows can greatly help with installation problems. Check out the [Anaconda installation section](installation.md#installation-with-conda) in the documentation for more information.
|
Using the [Anaconda Distribution](https://www.anaconda.com/distribution/) under Windows can greatly help with installation problems. Check out the [Anaconda installation section](installation.md#Anaconda) in this document for more information.
|
||||||
|
|
||||||
### 1. Clone the git repository
|
### 1. Clone the git repository
|
||||||
|
|
||||||
@@ -24,7 +23,7 @@ git clone https://github.com/freqtrade/freqtrade.git
|
|||||||
|
|
||||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||||
|
|
||||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which need to be downloaded and installed using `pip install TA_Lib-0.4.25-cp38-cp38-win_amd64.whl` (make sure to use the version matching your python version).
|
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which need to be downloaded and installed using `pip install TA_Lib-0.4.24-cp38-cp38-win_amd64.whl` (make sure to use the version matching your python version).
|
||||||
|
|
||||||
Freqtrade provides these dependencies for the latest 3 Python versions (3.8, 3.9 and 3.10) and for 64bit Windows.
|
Freqtrade provides these dependencies for the latest 3 Python versions (3.8, 3.9 and 3.10) and for 64bit Windows.
|
||||||
Other versions must be downloaded from the above link.
|
Other versions must be downloaded from the above link.
|
||||||
@@ -35,7 +34,7 @@ python -m venv .env
|
|||||||
.env\Scripts\activate.ps1
|
.env\Scripts\activate.ps1
|
||||||
# optionally install ta-lib from wheel
|
# optionally install ta-lib from wheel
|
||||||
# Eventually adjust the below filename to match the downloaded wheel
|
# Eventually adjust the below filename to match the downloaded wheel
|
||||||
pip install --find-links build_helpers\ TA-Lib -U
|
pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
pip install -e .
|
pip install -e .
|
||||||
freqtrade
|
freqtrade
|
||||||
|
@@ -34,7 +34,6 @@ dependencies:
|
|||||||
- schedule
|
- schedule
|
||||||
- python-dateutil
|
- python-dateutil
|
||||||
- joblib
|
- joblib
|
||||||
- pyarrow
|
|
||||||
|
|
||||||
|
|
||||||
# ============================
|
# ============================
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
""" Freqtrade bot """
|
""" Freqtrade bot """
|
||||||
__version__ = '2022.11'
|
__version__ = '2022.8.dev'
|
||||||
|
|
||||||
if 'dev' in __version__:
|
if 'dev' in __version__:
|
||||||
try:
|
try:
|
||||||
@@ -16,6 +16,6 @@ if 'dev' in __version__:
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
versionfile = Path('./freqtrade_commit')
|
versionfile = Path('./freqtrade_commit')
|
||||||
if versionfile.is_file():
|
if versionfile.is_file():
|
||||||
__version__ = f"docker-{__version__}-{versionfile.read_text()[:8]}"
|
__version__ = f"docker-{versionfile.read_text()[:8]}"
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
@@ -15,9 +15,9 @@ from freqtrade.commands.db_commands import start_convert_db
|
|||||||
from freqtrade.commands.deploy_commands import (start_create_userdir, start_install_ui,
|
from freqtrade.commands.deploy_commands import (start_create_userdir, start_install_ui,
|
||||||
start_new_strategy)
|
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_freqAI_models,
|
from freqtrade.commands.list_commands import (start_list_exchanges, start_list_markets,
|
||||||
start_list_markets, start_list_strategies,
|
start_list_strategies, start_list_timeframes,
|
||||||
start_list_timeframes, start_show_trades)
|
start_show_trades)
|
||||||
from freqtrade.commands.optimize_commands import (start_backtesting, start_backtesting_show,
|
from freqtrade.commands.optimize_commands import (start_backtesting, start_backtesting_show,
|
||||||
start_edge, start_hyperopt)
|
start_edge, start_hyperopt)
|
||||||
from freqtrade.commands.pairlist_commands import start_test_pairlist
|
from freqtrade.commands.pairlist_commands import start_test_pairlist
|
||||||
|
@@ -25,8 +25,7 @@ ARGS_COMMON_OPTIMIZE = ["timeframe", "timerange", "dataformat_ohlcv",
|
|||||||
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
||||||
"enable_protections", "dry_run_wallet", "timeframe_detail",
|
"enable_protections", "dry_run_wallet", "timeframe_detail",
|
||||||
"strategy_list", "export", "exportfilename",
|
"strategy_list", "export", "exportfilename",
|
||||||
"backtest_breakdown", "backtest_cache",
|
"backtest_breakdown", "backtest_cache"]
|
||||||
"freqai_backtest_live_models"]
|
|
||||||
|
|
||||||
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",
|
||||||
@@ -35,15 +34,13 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
|||||||
"print_colorized", "print_json", "hyperopt_jobs",
|
"print_colorized", "print_json", "hyperopt_jobs",
|
||||||
"hyperopt_random_state", "hyperopt_min_trades",
|
"hyperopt_random_state", "hyperopt_min_trades",
|
||||||
"hyperopt_loss", "disableparamexport",
|
"hyperopt_loss", "disableparamexport",
|
||||||
"hyperopt_ignore_missing_space", "analyze_per_epoch"]
|
"hyperopt_ignore_missing_space"]
|
||||||
|
|
||||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||||
|
|
||||||
ARGS_LIST_STRATEGIES = ["strategy_path", "print_one_column", "print_colorized",
|
ARGS_LIST_STRATEGIES = ["strategy_path", "print_one_column", "print_colorized",
|
||||||
"recursive_strategy_search"]
|
"recursive_strategy_search"]
|
||||||
|
|
||||||
ARGS_LIST_FREQAIMODELS = ["freqaimodel_path", "print_one_column", "print_colorized"]
|
|
||||||
|
|
||||||
ARGS_LIST_HYPEROPTS = ["hyperopt_path", "print_one_column", "print_colorized"]
|
ARGS_LIST_HYPEROPTS = ["hyperopt_path", "print_one_column", "print_colorized"]
|
||||||
|
|
||||||
ARGS_BACKTEST_SHOW = ["exportfilename", "backtest_show_pair_list"]
|
ARGS_BACKTEST_SHOW = ["exportfilename", "backtest_show_pair_list"]
|
||||||
@@ -56,8 +53,8 @@ ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one
|
|||||||
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all",
|
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all",
|
||||||
"trading_mode"]
|
"trading_mode"]
|
||||||
|
|
||||||
ARGS_TEST_PAIRLIST = ["user_data_dir", "verbosity", "config", "quote_currencies",
|
ARGS_TEST_PAIRLIST = ["verbosity", "config", "quote_currencies", "print_one_column",
|
||||||
"print_one_column", "list_pairs_print_json", "exchange"]
|
"list_pairs_print_json", "exchange"]
|
||||||
|
|
||||||
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||||
|
|
||||||
@@ -65,14 +62,14 @@ ARGS_BUILD_CONFIG = ["config"]
|
|||||||
|
|
||||||
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||||
|
|
||||||
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase", "exchange"]
|
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase"]
|
||||||
|
|
||||||
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "trading_mode",
|
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "exchange", "trading_mode",
|
||||||
"candle_types"]
|
"candle_types"]
|
||||||
|
|
||||||
ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"]
|
ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"]
|
||||||
|
|
||||||
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode", "show_timerange"]
|
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode"]
|
||||||
|
|
||||||
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "new_pairs_days", "include_inactive",
|
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "new_pairs_days", "include_inactive",
|
||||||
"timerange", "download_trades", "exchange", "timeframes",
|
"timerange", "download_trades", "exchange", "timeframes",
|
||||||
@@ -109,8 +106,8 @@ ARGS_ANALYZE_ENTRIES_EXITS = ["exportfilename", "analysis_groups", "enter_reason
|
|||||||
"exit_reason_list", "indicator_list"]
|
"exit_reason_list", "indicator_list"]
|
||||||
|
|
||||||
NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes",
|
NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes",
|
||||||
"list-markets", "list-pairs", "list-strategies", "list-freqaimodels",
|
"list-markets", "list-pairs", "list-strategies", "list-data",
|
||||||
"list-data", "hyperopt-list", "hyperopt-show", "backtest-filter",
|
"hyperopt-list", "hyperopt-show", "backtest-filter",
|
||||||
"plot-dataframe", "plot-profit", "show-trades", "trades-to-ohlcv"]
|
"plot-dataframe", "plot-profit", "show-trades", "trades-to-ohlcv"]
|
||||||
|
|
||||||
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-strategy"]
|
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-strategy"]
|
||||||
@@ -195,11 +192,10 @@ class Arguments:
|
|||||||
start_create_userdir, start_download_data, start_edge,
|
start_create_userdir, start_download_data, start_edge,
|
||||||
start_hyperopt, start_hyperopt_list, start_hyperopt_show,
|
start_hyperopt, start_hyperopt_list, start_hyperopt_show,
|
||||||
start_install_ui, start_list_data, start_list_exchanges,
|
start_install_ui, start_list_data, start_list_exchanges,
|
||||||
start_list_freqAI_models, start_list_markets,
|
start_list_markets, start_list_strategies,
|
||||||
start_list_strategies, start_list_timeframes,
|
start_list_timeframes, start_new_config, start_new_strategy,
|
||||||
start_new_config, start_new_strategy, start_plot_dataframe,
|
start_plot_dataframe, start_plot_profit, start_show_trades,
|
||||||
start_plot_profit, start_show_trades, start_test_pairlist,
|
start_test_pairlist, start_trading, start_webserver)
|
||||||
start_trading, start_webserver)
|
|
||||||
|
|
||||||
subparsers = self.parser.add_subparsers(dest='command',
|
subparsers = self.parser.add_subparsers(dest='command',
|
||||||
# Use custom message when no subhandler is added
|
# Use custom message when no subhandler is added
|
||||||
@@ -366,15 +362,6 @@ class Arguments:
|
|||||||
list_strategies_cmd.set_defaults(func=start_list_strategies)
|
list_strategies_cmd.set_defaults(func=start_list_strategies)
|
||||||
self._build_args(optionlist=ARGS_LIST_STRATEGIES, parser=list_strategies_cmd)
|
self._build_args(optionlist=ARGS_LIST_STRATEGIES, parser=list_strategies_cmd)
|
||||||
|
|
||||||
# Add list-freqAI Models subcommand
|
|
||||||
list_freqaimodels_cmd = subparsers.add_parser(
|
|
||||||
'list-freqaimodels',
|
|
||||||
help='Print available freqAI models.',
|
|
||||||
parents=[_common_parser],
|
|
||||||
)
|
|
||||||
list_freqaimodels_cmd.set_defaults(func=start_list_freqAI_models)
|
|
||||||
self._build_args(optionlist=ARGS_LIST_FREQAIMODELS, parser=list_freqaimodels_cmd)
|
|
||||||
|
|
||||||
# Add list-timeframes subcommand
|
# Add list-timeframes subcommand
|
||||||
list_timeframes_cmd = subparsers.add_parser(
|
list_timeframes_cmd = subparsers.add_parser(
|
||||||
'list-timeframes',
|
'list-timeframes',
|
||||||
|
@@ -108,6 +108,7 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
"binance",
|
"binance",
|
||||||
"binanceus",
|
"binanceus",
|
||||||
"bittrex",
|
"bittrex",
|
||||||
|
"ftx",
|
||||||
"gateio",
|
"gateio",
|
||||||
"huobi",
|
"huobi",
|
||||||
"kraken",
|
"kraken",
|
||||||
@@ -210,7 +211,6 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
)
|
)
|
||||||
# Force JWT token to be a random string
|
# Force JWT token to be a random string
|
||||||
answers['api_server_jwt_key'] = secrets.token_hex()
|
answers['api_server_jwt_key'] = secrets.token_hex()
|
||||||
answers['api_server_ws_token'] = secrets.token_urlsafe(25)
|
|
||||||
|
|
||||||
return answers
|
return answers
|
||||||
|
|
||||||
|
@@ -49,7 +49,7 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
default=0,
|
default=0,
|
||||||
),
|
),
|
||||||
"logfile": Arg(
|
"logfile": Arg(
|
||||||
'--logfile', '--log-file',
|
'--logfile',
|
||||||
help="Log to the file specified. Special values are: 'syslog', 'journald'. "
|
help="Log to the file specified. Special values are: 'syslog', 'journald'. "
|
||||||
"See the documentation for more details.",
|
"See the documentation for more details.",
|
||||||
metavar='FILE',
|
metavar='FILE',
|
||||||
@@ -69,7 +69,7 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
"datadir": Arg(
|
"datadir": Arg(
|
||||||
'-d', '--datadir', '--data-dir',
|
'-d', '--datadir',
|
||||||
help='Path to directory with historical backtesting data.',
|
help='Path to directory with historical backtesting data.',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
@@ -255,13 +255,6 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
nargs='+',
|
nargs='+',
|
||||||
default='default',
|
default='default',
|
||||||
),
|
),
|
||||||
"analyze_per_epoch": Arg(
|
|
||||||
'--analyze-per-epoch',
|
|
||||||
help='Run populate_indicators once per epoch.',
|
|
||||||
action='store_true',
|
|
||||||
default=False,
|
|
||||||
),
|
|
||||||
|
|
||||||
"print_all": Arg(
|
"print_all": Arg(
|
||||||
'--print-all',
|
'--print-all',
|
||||||
help='Print all results, not only the best ones.',
|
help='Print all results, not only the best ones.',
|
||||||
@@ -374,7 +367,7 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
metavar='BASE_CURRENCY',
|
metavar='BASE_CURRENCY',
|
||||||
),
|
),
|
||||||
"trading_mode": Arg(
|
"trading_mode": Arg(
|
||||||
'--trading-mode', '--tradingmode',
|
'--trading-mode',
|
||||||
help='Select Trading mode',
|
help='Select Trading mode',
|
||||||
choices=constants.TRADING_MODES,
|
choices=constants.TRADING_MODES,
|
||||||
),
|
),
|
||||||
@@ -393,8 +386,7 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
# Download data
|
# Download data
|
||||||
"pairs_file": Arg(
|
"pairs_file": Arg(
|
||||||
'--pairs-file',
|
'--pairs-file',
|
||||||
help='File containing a list of pairs. '
|
help='File containing a list of pairs to download.',
|
||||||
'Takes precedence over --pairs or pairs configured in the configuration.',
|
|
||||||
metavar='FILE',
|
metavar='FILE',
|
||||||
),
|
),
|
||||||
"days": Arg(
|
"days": Arg(
|
||||||
@@ -440,12 +432,7 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
"dataformat_trades": Arg(
|
"dataformat_trades": Arg(
|
||||||
'--data-format-trades',
|
'--data-format-trades',
|
||||||
help='Storage format for downloaded trades data. (default: `jsongz`).',
|
help='Storage format for downloaded trades data. (default: `jsongz`).',
|
||||||
choices=constants.AVAILABLE_DATAHANDLERS_TRADES,
|
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||||
),
|
|
||||||
"show_timerange": Arg(
|
|
||||||
'--show-timerange',
|
|
||||||
help='Show timerange available for available data. (May take a while to calculate).',
|
|
||||||
action='store_true',
|
|
||||||
),
|
),
|
||||||
"exchange": Arg(
|
"exchange": Arg(
|
||||||
'--exchange',
|
'--exchange',
|
||||||
@@ -456,12 +443,14 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
'-t', '--timeframes',
|
'-t', '--timeframes',
|
||||||
help='Specify which tickers to download. Space-separated list. '
|
help='Specify which tickers to download. Space-separated list. '
|
||||||
'Default: `1m 5m`.',
|
'Default: `1m 5m`.',
|
||||||
|
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||||
|
'6h', '8h', '12h', '1d', '3d', '1w', '2w', '1M', '1y'],
|
||||||
default=['1m', '5m'],
|
default=['1m', '5m'],
|
||||||
nargs='+',
|
nargs='+',
|
||||||
),
|
),
|
||||||
"prepend_data": Arg(
|
"prepend_data": Arg(
|
||||||
'--prepend',
|
'--prepend',
|
||||||
help='Allow data prepending. (Data-appending is disabled)',
|
help='Allow data prepending.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
"erase": Arg(
|
"erase": Arg(
|
||||||
@@ -668,9 +657,4 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Specify additional lookup path for freqaimodels.',
|
help='Specify additional lookup path for freqaimodels.',
|
||||||
metavar='PATH',
|
metavar='PATH',
|
||||||
),
|
),
|
||||||
"freqai_backtest_live_models": Arg(
|
|
||||||
'--freqai-backtest-live-models',
|
|
||||||
help='Run backtest with ready models.',
|
|
||||||
action='store_true'
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
@@ -5,13 +5,13 @@ from datetime import datetime, timedelta
|
|||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||||
from freqtrade.constants import DATETIME_PRINT_FORMAT
|
|
||||||
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format
|
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format
|
||||||
from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data,
|
from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data,
|
||||||
refresh_backtest_trades_data)
|
refresh_backtest_trades_data)
|
||||||
from freqtrade.enums import CandleType, RunMode, TradingMode
|
from freqtrade.enums import CandleType, RunMode, TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import market_is_active, timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
from freqtrade.exchange.exchange import market_is_active
|
||||||
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist
|
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist
|
||||||
from freqtrade.resolvers import ExchangeResolver
|
from freqtrade.resolvers import ExchangeResolver
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
|||||||
data_format_trades=config['dataformat_trades'],
|
data_format_trades=config['dataformat_trades'],
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
if not exchange.get_option('ohlcv_has_history', True):
|
if not exchange._ft_has.get('ohlcv_has_history', True):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f"Historic klines not available for {exchange.name}. "
|
f"Historic klines not available for {exchange.name}. "
|
||||||
"Please use `--dl-trades` instead for this exchange "
|
"Please use `--dl-trades` instead for this exchange "
|
||||||
@@ -177,31 +177,17 @@ def start_list_data(args: Dict[str, Any]) -> None:
|
|||||||
paircombs = [comb for comb in paircombs if comb[0] in args['pairs']]
|
paircombs = [comb for comb in paircombs if comb[0] in args['pairs']]
|
||||||
|
|
||||||
print(f"Found {len(paircombs)} pair / timeframe combinations.")
|
print(f"Found {len(paircombs)} pair / timeframe combinations.")
|
||||||
if not config.get('show_timerange'):
|
groupedpair = defaultdict(list)
|
||||||
groupedpair = defaultdict(list)
|
for pair, timeframe, candle_type in sorted(
|
||||||
for pair, timeframe, candle_type in sorted(
|
paircombs,
|
||||||
paircombs,
|
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
|
||||||
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
|
):
|
||||||
):
|
groupedpair[(pair, candle_type)].append(timeframe)
|
||||||
groupedpair[(pair, candle_type)].append(timeframe)
|
|
||||||
|
|
||||||
if groupedpair:
|
if groupedpair:
|
||||||
print(tabulate([
|
|
||||||
(pair, ', '.join(timeframes), candle_type)
|
|
||||||
for (pair, candle_type), timeframes in groupedpair.items()
|
|
||||||
],
|
|
||||||
headers=("Pair", "Timeframe", "Type"),
|
|
||||||
tablefmt='psql', stralign='right'))
|
|
||||||
else:
|
|
||||||
paircombs1 = [(
|
|
||||||
pair, timeframe, candle_type,
|
|
||||||
*dhc.ohlcv_data_min_max(pair, timeframe, candle_type)
|
|
||||||
) for pair, timeframe, candle_type in paircombs]
|
|
||||||
print(tabulate([
|
print(tabulate([
|
||||||
(pair, timeframe, candle_type,
|
(pair, ', '.join(timeframes), candle_type)
|
||||||
start.strftime(DATETIME_PRINT_FORMAT),
|
for (pair, candle_type), timeframes in groupedpair.items()
|
||||||
end.strftime(DATETIME_PRINT_FORMAT))
|
],
|
||||||
for pair, timeframe, candle_type, start, end in paircombs1
|
headers=("Pair", "Timeframe", "Type"),
|
||||||
],
|
|
||||||
headers=("Pair", "Timeframe", "Type", 'From', 'To'),
|
|
||||||
tablefmt='psql', stralign='right'))
|
tablefmt='psql', stralign='right'))
|
||||||
|
@@ -4,7 +4,7 @@ from typing import Any, Dict
|
|||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
||||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||||
from freqtrade.enums import RunMode
|
from freqtrade.enums.runmode import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
@@ -36,24 +36,24 @@ def deploy_new_strategy(strategy_name: str, strategy_path: Path, subtemplate: st
|
|||||||
"""
|
"""
|
||||||
fallback = 'full'
|
fallback = 'full'
|
||||||
indicators = render_template_with_fallback(
|
indicators = render_template_with_fallback(
|
||||||
templatefile=f"strategy_subtemplates/indicators_{subtemplate}.j2",
|
templatefile=f"subtemplates/indicators_{subtemplate}.j2",
|
||||||
templatefallbackfile=f"strategy_subtemplates/indicators_{fallback}.j2",
|
templatefallbackfile=f"subtemplates/indicators_{fallback}.j2",
|
||||||
)
|
)
|
||||||
buy_trend = render_template_with_fallback(
|
buy_trend = render_template_with_fallback(
|
||||||
templatefile=f"strategy_subtemplates/buy_trend_{subtemplate}.j2",
|
templatefile=f"subtemplates/buy_trend_{subtemplate}.j2",
|
||||||
templatefallbackfile=f"strategy_subtemplates/buy_trend_{fallback}.j2",
|
templatefallbackfile=f"subtemplates/buy_trend_{fallback}.j2",
|
||||||
)
|
)
|
||||||
sell_trend = render_template_with_fallback(
|
sell_trend = render_template_with_fallback(
|
||||||
templatefile=f"strategy_subtemplates/sell_trend_{subtemplate}.j2",
|
templatefile=f"subtemplates/sell_trend_{subtemplate}.j2",
|
||||||
templatefallbackfile=f"strategy_subtemplates/sell_trend_{fallback}.j2",
|
templatefallbackfile=f"subtemplates/sell_trend_{fallback}.j2",
|
||||||
)
|
)
|
||||||
plot_config = render_template_with_fallback(
|
plot_config = render_template_with_fallback(
|
||||||
templatefile=f"strategy_subtemplates/plot_config_{subtemplate}.j2",
|
templatefile=f"subtemplates/plot_config_{subtemplate}.j2",
|
||||||
templatefallbackfile=f"strategy_subtemplates/plot_config_{fallback}.j2",
|
templatefallbackfile=f"subtemplates/plot_config_{fallback}.j2",
|
||||||
)
|
)
|
||||||
additional_methods = render_template_with_fallback(
|
additional_methods = render_template_with_fallback(
|
||||||
templatefile=f"strategy_subtemplates/strategy_methods_{subtemplate}.j2",
|
templatefile=f"subtemplates/strategy_methods_{subtemplate}.j2",
|
||||||
templatefallbackfile="strategy_subtemplates/strategy_methods_empty.j2",
|
templatefallbackfile="subtemplates/strategy_methods_empty.j2",
|
||||||
)
|
)
|
||||||
|
|
||||||
strategy_text = render_template(templatefile='base_strategy.py.j2',
|
strategy_text = render_template(templatefile='base_strategy.py.j2',
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
import csv
|
import csv
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
import rapidjson
|
import rapidjson
|
||||||
@@ -9,6 +10,7 @@ from colorama import init as colorama_init
|
|||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
|
|
||||||
from freqtrade.configuration import setup_utils_configuration
|
from freqtrade.configuration import setup_utils_configuration
|
||||||
|
from freqtrade.constants import USERPATH_STRATEGIES
|
||||||
from freqtrade.enums import RunMode
|
from freqtrade.enums import RunMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import market_is_active, validate_exchanges
|
from freqtrade.exchange import market_is_active, validate_exchanges
|
||||||
@@ -39,7 +41,7 @@ def start_list_exchanges(args: Dict[str, Any]) -> None:
|
|||||||
print(tabulate(exchanges, headers=['Exchange name', 'Valid', 'reason']))
|
print(tabulate(exchanges, headers=['Exchange name', 'Valid', 'reason']))
|
||||||
|
|
||||||
|
|
||||||
def _print_objs_tabular(objs: List, print_colorized: bool) -> None:
|
def _print_objs_tabular(objs: List, print_colorized: bool, base_dir: Path) -> None:
|
||||||
if print_colorized:
|
if print_colorized:
|
||||||
colorama_init(autoreset=True)
|
colorama_init(autoreset=True)
|
||||||
red = Fore.RED
|
red = Fore.RED
|
||||||
@@ -53,7 +55,7 @@ def _print_objs_tabular(objs: List, print_colorized: bool) -> None:
|
|||||||
names = [s['name'] for s in objs]
|
names = [s['name'] for s in objs]
|
||||||
objs_to_print = [{
|
objs_to_print = [{
|
||||||
'name': s['name'] if s['name'] else "--",
|
'name': s['name'] if s['name'] else "--",
|
||||||
'location': s['location_rel'],
|
'location': s['location'].relative_to(base_dir),
|
||||||
'status': (red + "LOAD FAILED" + reset if s['class'] is None
|
'status': (red + "LOAD FAILED" + reset if s['class'] is None
|
||||||
else "OK" if names.count(s['name']) == 1
|
else "OK" if names.count(s['name']) == 1
|
||||||
else yellow + "DUPLICATE NAME" + reset)
|
else yellow + "DUPLICATE NAME" + reset)
|
||||||
@@ -74,8 +76,9 @@ def start_list_strategies(args: Dict[str, Any]) -> None:
|
|||||||
"""
|
"""
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
|
|
||||||
|
directory = Path(config.get('strategy_path', config['user_data_dir'] / USERPATH_STRATEGIES))
|
||||||
strategy_objs = StrategyResolver.search_all_objects(
|
strategy_objs = StrategyResolver.search_all_objects(
|
||||||
config, not args['print_one_column'], config.get('recursive_strategy_search', False))
|
directory, not args['print_one_column'], config.get('recursive_strategy_search', False))
|
||||||
# Sort alphabetically
|
# Sort alphabetically
|
||||||
strategy_objs = sorted(strategy_objs, key=lambda x: x['name'])
|
strategy_objs = sorted(strategy_objs, key=lambda x: x['name'])
|
||||||
for obj in strategy_objs:
|
for obj in strategy_objs:
|
||||||
@@ -87,22 +90,7 @@ def start_list_strategies(args: Dict[str, Any]) -> None:
|
|||||||
if args['print_one_column']:
|
if args['print_one_column']:
|
||||||
print('\n'.join([s['name'] for s in strategy_objs]))
|
print('\n'.join([s['name'] for s in strategy_objs]))
|
||||||
else:
|
else:
|
||||||
_print_objs_tabular(strategy_objs, config.get('print_colorized', False))
|
_print_objs_tabular(strategy_objs, config.get('print_colorized', False), directory)
|
||||||
|
|
||||||
|
|
||||||
def start_list_freqAI_models(args: Dict[str, Any]) -> None:
|
|
||||||
"""
|
|
||||||
Print files with FreqAI models custom classes available in the directory
|
|
||||||
"""
|
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
|
||||||
from freqtrade.resolvers.freqaimodel_resolver import FreqaiModelResolver
|
|
||||||
model_objs = FreqaiModelResolver.search_all_objects(config, not args['print_one_column'])
|
|
||||||
# Sort alphabetically
|
|
||||||
model_objs = sorted(model_objs, key=lambda x: x['name'])
|
|
||||||
if args['print_one_column']:
|
|
||||||
print('\n'.join([s['name'] for s in model_objs]))
|
|
||||||
else:
|
|
||||||
_print_objs_tabular(model_objs, config.get('print_colorized', False))
|
|
||||||
|
|
||||||
|
|
||||||
def start_list_timeframes(args: Dict[str, Any]) -> None:
|
def start_list_timeframes(args: Dict[str, Any]) -> None:
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
# flake8: noqa: F401
|
# flake8: noqa: F401
|
||||||
|
|
||||||
|
from freqtrade.configuration.check_exchange import check_exchange
|
||||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||||
from freqtrade.configuration.config_validation import validate_config_consistency
|
from freqtrade.configuration.config_validation import validate_config_consistency
|
||||||
from freqtrade.configuration.configuration import Configuration
|
from freqtrade.configuration.configuration import Configuration
|
||||||
|
@@ -1,16 +1,16 @@
|
|||||||
import logging
|
import logging
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
from freqtrade.constants import Config
|
|
||||||
from freqtrade.enums import RunMode
|
from freqtrade.enums import RunMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import available_exchanges, is_exchange_known_ccxt, validate_exchange
|
from freqtrade.exchange import (available_exchanges, is_exchange_known_ccxt,
|
||||||
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS, SUPPORTED_EXCHANGES
|
is_exchange_officially_supported, validate_exchange)
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def check_exchange(config: Config, check_for_bad: bool = True) -> bool:
|
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if the exchange name in the config file is supported by Freqtrade
|
Check if the exchange name in the config file is supported by Freqtrade
|
||||||
:param check_for_bad: if True, check the exchange against the list of known 'bad'
|
:param check_for_bad: if True, check the exchange against the list of known 'bad'
|
||||||
@@ -52,7 +52,7 @@ def check_exchange(config: Config, check_for_bad: bool = True) -> bool:
|
|||||||
else:
|
else:
|
||||||
logger.warning(f'Exchange "{exchange}" will not work with Freqtrade. Reason: {reason}')
|
logger.warning(f'Exchange "{exchange}" will not work with Freqtrade. Reason: {reason}')
|
||||||
|
|
||||||
if MAP_EXCHANGE_CHILDCLASS.get(exchange, exchange) in SUPPORTED_EXCHANGES:
|
if is_exchange_officially_supported(exchange):
|
||||||
logger.info(f'Exchange "{exchange}" is officially supported '
|
logger.info(f'Exchange "{exchange}" is officially supported '
|
||||||
f'by the Freqtrade development team.')
|
f'by the Freqtrade development team.')
|
||||||
else:
|
else:
|
@@ -1,5 +1,4 @@
|
|||||||
import logging
|
import logging
|
||||||
from collections import Counter
|
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
@@ -85,10 +84,6 @@ def validate_config_consistency(conf: Dict[str, Any], preliminary: bool = False)
|
|||||||
_validate_protections(conf)
|
_validate_protections(conf)
|
||||||
_validate_unlimited_amount(conf)
|
_validate_unlimited_amount(conf)
|
||||||
_validate_ask_orderbook(conf)
|
_validate_ask_orderbook(conf)
|
||||||
_validate_freqai_hyperopt(conf)
|
|
||||||
_validate_freqai_backtest(conf)
|
|
||||||
_validate_freqai_include_timeframes(conf)
|
|
||||||
_validate_consumers(conf)
|
|
||||||
validate_migrated_strategy_settings(conf)
|
validate_migrated_strategy_settings(conf)
|
||||||
|
|
||||||
# validate configuration before returning
|
# validate configuration before returning
|
||||||
@@ -328,71 +323,6 @@ def _validate_pricing_rules(conf: Dict[str, Any]) -> None:
|
|||||||
del conf['ask_strategy']
|
del conf['ask_strategy']
|
||||||
|
|
||||||
|
|
||||||
def _validate_freqai_hyperopt(conf: Dict[str, Any]) -> None:
|
|
||||||
freqai_enabled = conf.get('freqai', {}).get('enabled', False)
|
|
||||||
analyze_per_epoch = conf.get('analyze_per_epoch', False)
|
|
||||||
if analyze_per_epoch and freqai_enabled:
|
|
||||||
raise OperationalException(
|
|
||||||
'Using analyze-per-epoch parameter is not supported with a FreqAI strategy.')
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_freqai_include_timeframes(conf: Dict[str, Any]) -> None:
|
|
||||||
freqai_enabled = conf.get('freqai', {}).get('enabled', False)
|
|
||||||
if freqai_enabled:
|
|
||||||
main_tf = conf.get('timeframe', '5m')
|
|
||||||
freqai_include_timeframes = conf.get('freqai', {}).get('feature_parameters', {}
|
|
||||||
).get('include_timeframes', [])
|
|
||||||
|
|
||||||
from freqtrade.exchange import timeframe_to_seconds
|
|
||||||
main_tf_s = timeframe_to_seconds(main_tf)
|
|
||||||
offending_lines = []
|
|
||||||
for tf in freqai_include_timeframes:
|
|
||||||
tf_s = timeframe_to_seconds(tf)
|
|
||||||
if tf_s < main_tf_s:
|
|
||||||
offending_lines.append(tf)
|
|
||||||
if offending_lines:
|
|
||||||
raise OperationalException(
|
|
||||||
f"Main timeframe of {main_tf} must be smaller or equal to FreqAI "
|
|
||||||
f"`include_timeframes`.Offending include-timeframes: {', '.join(offending_lines)}")
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_freqai_backtest(conf: Dict[str, Any]) -> None:
|
|
||||||
if conf.get('runmode', RunMode.OTHER) == RunMode.BACKTEST:
|
|
||||||
freqai_enabled = conf.get('freqai', {}).get('enabled', False)
|
|
||||||
timerange = conf.get('timerange')
|
|
||||||
freqai_backtest_live_models = conf.get('freqai_backtest_live_models', False)
|
|
||||||
if freqai_backtest_live_models and freqai_enabled and timerange:
|
|
||||||
raise OperationalException(
|
|
||||||
'Using timerange parameter is not supported with '
|
|
||||||
'--freqai-backtest-live-models parameter.')
|
|
||||||
|
|
||||||
if freqai_backtest_live_models and not freqai_enabled:
|
|
||||||
raise OperationalException(
|
|
||||||
'Using --freqai-backtest-live-models parameter is only '
|
|
||||||
'supported with a FreqAI strategy.')
|
|
||||||
|
|
||||||
if freqai_enabled and not freqai_backtest_live_models and not timerange:
|
|
||||||
raise OperationalException(
|
|
||||||
'Please pass --timerange if you intend to use FreqAI for backtesting.')
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_consumers(conf: Dict[str, Any]) -> None:
|
|
||||||
emc_conf = conf.get('external_message_consumer', {})
|
|
||||||
if emc_conf.get('enabled', False):
|
|
||||||
if len(emc_conf.get('producers', [])) < 1:
|
|
||||||
raise OperationalException("You must specify at least 1 Producer to connect to.")
|
|
||||||
|
|
||||||
producer_names = [p['name'] for p in emc_conf.get('producers', [])]
|
|
||||||
duplicates = [item for item, count in Counter(producer_names).items() if count > 1]
|
|
||||||
if duplicates:
|
|
||||||
raise OperationalException(
|
|
||||||
f"Producer names must be unique. Duplicate: {', '.join(duplicates)}")
|
|
||||||
if conf.get('process_only_new_candles', True):
|
|
||||||
# Warning here or require it?
|
|
||||||
logger.warning("To receive best performance with external data, "
|
|
||||||
"please set `process_only_new_candles` to False")
|
|
||||||
|
|
||||||
|
|
||||||
def _strategy_settings(conf: Dict[str, Any]) -> None:
|
def _strategy_settings(conf: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
process_deprecated_setting(conf, None, 'use_sell_signal', None, 'use_exit_signal')
|
process_deprecated_setting(conf, None, 'use_sell_signal', None, 'use_exit_signal')
|
||||||
|
@@ -8,11 +8,11 @@ from pathlib import Path
|
|||||||
from typing import Any, Callable, Dict, List, Optional
|
from typing import Any, Callable, Dict, List, Optional
|
||||||
|
|
||||||
from freqtrade import constants
|
from freqtrade import constants
|
||||||
|
from freqtrade.configuration.check_exchange import check_exchange
|
||||||
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||||
from freqtrade.configuration.directory_operations import create_datadir, create_userdata_dir
|
from freqtrade.configuration.directory_operations import create_datadir, create_userdata_dir
|
||||||
from freqtrade.configuration.environment_vars import enironment_vars_to_dict
|
from freqtrade.configuration.environment_vars import enironment_vars_to_dict
|
||||||
from freqtrade.configuration.load_config import load_file, load_from_files
|
from freqtrade.configuration.load_config import load_file, load_from_files
|
||||||
from freqtrade.constants import Config
|
|
||||||
from freqtrade.enums import NON_UTIL_MODES, TRADING_MODES, CandleType, RunMode, TradingMode
|
from freqtrade.enums import NON_UTIL_MODES, TRADING_MODES, CandleType, RunMode, TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.loggers import setup_logging
|
from freqtrade.loggers import setup_logging
|
||||||
@@ -30,10 +30,10 @@ class Configuration:
|
|||||||
|
|
||||||
def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None:
|
def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None:
|
||||||
self.args = args
|
self.args = args
|
||||||
self.config: Optional[Config] = None
|
self.config: Optional[Dict[str, Any]] = None
|
||||||
self.runmode = runmode
|
self.runmode = runmode
|
||||||
|
|
||||||
def get_config(self) -> Config:
|
def get_config(self) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Return the config. Use this method to get the bot config
|
Return the config. Use this method to get the bot config
|
||||||
:return: Dict: Bot config
|
:return: Dict: Bot config
|
||||||
@@ -65,7 +65,7 @@ class Configuration:
|
|||||||
:return: Configuration dictionary
|
:return: Configuration dictionary
|
||||||
"""
|
"""
|
||||||
# Load all configs
|
# Load all configs
|
||||||
config: Config = load_from_files(self.args.get("config", []))
|
config: Dict[str, Any] = load_from_files(self.args.get("config", []))
|
||||||
|
|
||||||
# Load environment variables
|
# Load environment variables
|
||||||
env_data = enironment_vars_to_dict()
|
env_data = enironment_vars_to_dict()
|
||||||
@@ -99,9 +99,6 @@ class Configuration:
|
|||||||
|
|
||||||
self._process_freqai_options(config)
|
self._process_freqai_options(config)
|
||||||
|
|
||||||
# Import check_exchange here to avoid import cycle problems
|
|
||||||
from freqtrade.exchange.check_exchange import check_exchange
|
|
||||||
|
|
||||||
# Check if the exchange set by the user is supported
|
# Check if the exchange set by the user is supported
|
||||||
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
||||||
|
|
||||||
@@ -111,7 +108,7 @@ class Configuration:
|
|||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
def _process_logging_options(self, config: Config) -> None:
|
def _process_logging_options(self, config: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Extract information for sys.argv and load logging configuration:
|
Extract information for sys.argv and load logging configuration:
|
||||||
the -v/--verbose, --logfile options
|
the -v/--verbose, --logfile options
|
||||||
@@ -124,7 +121,7 @@ class Configuration:
|
|||||||
|
|
||||||
setup_logging(config)
|
setup_logging(config)
|
||||||
|
|
||||||
def _process_trading_options(self, config: Config) -> None:
|
def _process_trading_options(self, config: Dict[str, Any]) -> None:
|
||||||
if config['runmode'] not in TRADING_MODES:
|
if config['runmode'] not in TRADING_MODES:
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -140,7 +137,7 @@ class Configuration:
|
|||||||
|
|
||||||
logger.info(f'Using DB: "{parse_db_uri_for_logging(config["db_url"])}"')
|
logger.info(f'Using DB: "{parse_db_uri_for_logging(config["db_url"])}"')
|
||||||
|
|
||||||
def _process_common_options(self, config: Config) -> None:
|
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# Set strategy if not specified in config and or if it's non default
|
# Set strategy if not specified in config and or if it's non default
|
||||||
if self.args.get('strategy') or not config.get('strategy'):
|
if self.args.get('strategy') or not config.get('strategy'):
|
||||||
@@ -164,7 +161,7 @@ class Configuration:
|
|||||||
if 'sd_notify' in self.args and self.args['sd_notify']:
|
if 'sd_notify' in self.args and self.args['sd_notify']:
|
||||||
config['internals'].update({'sd_notify': True})
|
config['internals'].update({'sd_notify': True})
|
||||||
|
|
||||||
def _process_datadir_options(self, config: Config) -> None:
|
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Extract information for sys.argv and load directory configurations
|
Extract information for sys.argv and load directory configurations
|
||||||
--user-data, --datadir
|
--user-data, --datadir
|
||||||
@@ -198,7 +195,7 @@ class Configuration:
|
|||||||
config['exportfilename'] = (config['user_data_dir']
|
config['exportfilename'] = (config['user_data_dir']
|
||||||
/ 'backtest_results')
|
/ 'backtest_results')
|
||||||
|
|
||||||
def _process_optimize_options(self, config: Config) -> None:
|
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# This will override the strategy configuration
|
# This will override the strategy configuration
|
||||||
self._args_to_config(config, argname='timeframe',
|
self._args_to_config(config, argname='timeframe',
|
||||||
@@ -279,9 +276,6 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='disableparamexport',
|
self._args_to_config(config, argname='disableparamexport',
|
||||||
logstring='Parameter --disableparamexport detected: {} ...')
|
logstring='Parameter --disableparamexport detected: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='freqai_backtest_live_models',
|
|
||||||
logstring='Parameter --freqai-backtest-live-models detected ...')
|
|
||||||
|
|
||||||
# Edge section:
|
# Edge section:
|
||||||
if 'stoploss_range' in self.args and self.args["stoploss_range"]:
|
if 'stoploss_range' in self.args and self.args["stoploss_range"]:
|
||||||
txt_range = eval(self.args["stoploss_range"])
|
txt_range = eval(self.args["stoploss_range"])
|
||||||
@@ -308,9 +302,6 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='spaces',
|
self._args_to_config(config, argname='spaces',
|
||||||
logstring='Parameter -s/--spaces detected: {}')
|
logstring='Parameter -s/--spaces detected: {}')
|
||||||
|
|
||||||
self._args_to_config(config, argname='analyze_per_epoch',
|
|
||||||
logstring='Parameter --analyze-per-epoch detected.')
|
|
||||||
|
|
||||||
self._args_to_config(config, argname='print_all',
|
self._args_to_config(config, argname='print_all',
|
||||||
logstring='Parameter --print-all detected ...')
|
logstring='Parameter --print-all detected ...')
|
||||||
|
|
||||||
@@ -386,7 +377,7 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname="hyperopt_ignore_missing_space",
|
self._args_to_config(config, argname="hyperopt_ignore_missing_space",
|
||||||
logstring="Paramter --ignore-missing-space detected: {}")
|
logstring="Paramter --ignore-missing-space detected: {}")
|
||||||
|
|
||||||
def _process_plot_options(self, config: Config) -> None:
|
def _process_plot_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
self._args_to_config(config, argname='pairs',
|
self._args_to_config(config, argname='pairs',
|
||||||
logstring='Using pairs {}')
|
logstring='Using pairs {}')
|
||||||
@@ -435,10 +426,7 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='dataformat_trades',
|
self._args_to_config(config, argname='dataformat_trades',
|
||||||
logstring='Using "{}" to store trades data.')
|
logstring='Using "{}" to store trades data.')
|
||||||
|
|
||||||
self._args_to_config(config, argname='show_timerange',
|
def _process_data_options(self, config: Dict[str, Any]) -> None:
|
||||||
logstring='Detected --show-timerange')
|
|
||||||
|
|
||||||
def _process_data_options(self, config: Config) -> None:
|
|
||||||
self._args_to_config(config, argname='new_pairs_days',
|
self._args_to_config(config, argname='new_pairs_days',
|
||||||
logstring='Detected --new-pairs-days: {}')
|
logstring='Detected --new-pairs-days: {}')
|
||||||
self._args_to_config(config, argname='trading_mode',
|
self._args_to_config(config, argname='trading_mode',
|
||||||
@@ -449,7 +437,7 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='candle_types',
|
self._args_to_config(config, argname='candle_types',
|
||||||
logstring='Detected --candle-types: {}')
|
logstring='Detected --candle-types: {}')
|
||||||
|
|
||||||
def _process_analyze_options(self, config: Config) -> None:
|
def _process_analyze_options(self, config: Dict[str, Any]) -> None:
|
||||||
self._args_to_config(config, argname='analysis_groups',
|
self._args_to_config(config, argname='analysis_groups',
|
||||||
logstring='Analysis reason groups: {}')
|
logstring='Analysis reason groups: {}')
|
||||||
|
|
||||||
@@ -462,7 +450,7 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='indicator_list',
|
self._args_to_config(config, argname='indicator_list',
|
||||||
logstring='Analysis indicator list: {}')
|
logstring='Analysis indicator list: {}')
|
||||||
|
|
||||||
def _process_runmode(self, config: Config) -> None:
|
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
self._args_to_config(config, argname='dry_run',
|
self._args_to_config(config, argname='dry_run',
|
||||||
logstring='Parameter --dry-run detected, '
|
logstring='Parameter --dry-run detected, '
|
||||||
@@ -475,7 +463,7 @@ class Configuration:
|
|||||||
|
|
||||||
config.update({'runmode': self.runmode})
|
config.update({'runmode': self.runmode})
|
||||||
|
|
||||||
def _process_freqai_options(self, config: Config) -> None:
|
def _process_freqai_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
self._args_to_config(config, argname='freqaimodel',
|
self._args_to_config(config, argname='freqaimodel',
|
||||||
logstring='Using freqaimodel class name: {}')
|
logstring='Using freqaimodel class name: {}')
|
||||||
@@ -485,7 +473,7 @@ class Configuration:
|
|||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
def _args_to_config(self, config: Config, argname: str,
|
def _args_to_config(self, config: Dict[str, Any], argname: str,
|
||||||
logstring: str, logfun: Optional[Callable] = None,
|
logstring: str, logfun: Optional[Callable] = None,
|
||||||
deprecated_msg: Optional[str] = None) -> None:
|
deprecated_msg: Optional[str] = None) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -508,7 +496,7 @@ class Configuration:
|
|||||||
if deprecated_msg:
|
if deprecated_msg:
|
||||||
warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning)
|
warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning)
|
||||||
|
|
||||||
def _resolve_pairs_list(self, config: Config) -> None:
|
def _resolve_pairs_list(self, config: Dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
Helper for download script.
|
Helper for download script.
|
||||||
Takes first found:
|
Takes first found:
|
||||||
|
@@ -3,16 +3,15 @@ Functions to handle deprecated settings
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from typing import Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
from freqtrade.constants import Config
|
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def check_conflicting_settings(config: Config,
|
def check_conflicting_settings(config: Dict[str, Any],
|
||||||
section_old: Optional[str], name_old: str,
|
section_old: Optional[str], name_old: str,
|
||||||
section_new: Optional[str], name_new: str) -> None:
|
section_new: Optional[str], name_new: str) -> None:
|
||||||
section_new_config = config.get(section_new, {}) if section_new else config
|
section_new_config = config.get(section_new, {}) if section_new else config
|
||||||
@@ -29,7 +28,7 @@ def check_conflicting_settings(config: Config,
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def process_removed_setting(config: Config,
|
def process_removed_setting(config: Dict[str, Any],
|
||||||
section1: str, name1: str,
|
section1: str, name1: str,
|
||||||
section2: Optional[str], name2: str) -> None:
|
section2: Optional[str], name2: str) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -48,7 +47,7 @@ def process_removed_setting(config: Config,
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def process_deprecated_setting(config: Config,
|
def process_deprecated_setting(config: Dict[str, Any],
|
||||||
section_old: Optional[str], name_old: str,
|
section_old: Optional[str], name_old: str,
|
||||||
section_new: Optional[str], name_new: str
|
section_new: Optional[str], name_new: str
|
||||||
) -> None:
|
) -> None:
|
||||||
@@ -70,7 +69,7 @@ def process_deprecated_setting(config: Config,
|
|||||||
del section_old_config[name_old]
|
del section_old_config[name_old]
|
||||||
|
|
||||||
|
|
||||||
def process_temporary_deprecated_settings(config: Config) -> None:
|
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# Kept for future deprecated / moved settings
|
# Kept for future deprecated / moved settings
|
||||||
# check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
# check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||||
|
@@ -1,17 +1,16 @@
|
|||||||
import logging
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
from freqtrade.constants import (USER_DATA_FILES, USERPATH_FREQAIMODELS, USERPATH_HYPEROPTS,
|
from freqtrade.constants import USER_DATA_FILES
|
||||||
USERPATH_NOTEBOOKS, USERPATH_STRATEGIES, Config)
|
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def create_datadir(config: Config, datadir: Optional[str] = None) -> Path:
|
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> Path:
|
||||||
|
|
||||||
folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data")
|
folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data")
|
||||||
if not datadir:
|
if not datadir:
|
||||||
@@ -50,8 +49,8 @@ def create_userdata_dir(directory: str, create_dir: bool = False) -> Path:
|
|||||||
:param create_dir: Create directory if it does not exist.
|
:param create_dir: Create directory if it does not exist.
|
||||||
:return: Path object containing the directory
|
:return: Path object containing the directory
|
||||||
"""
|
"""
|
||||||
sub_dirs = ["backtest_results", "data", USERPATH_HYPEROPTS, "hyperopt_results", "logs",
|
sub_dirs = ["backtest_results", "data", "hyperopts", "hyperopt_results", "logs",
|
||||||
USERPATH_NOTEBOOKS, "plot", USERPATH_STRATEGIES, USERPATH_FREQAIMODELS]
|
"notebooks", "plot", "strategies", ]
|
||||||
folder = Path(directory)
|
folder = Path(directory)
|
||||||
chown_user_directory(folder)
|
chown_user_directory(folder)
|
||||||
if not folder.is_dir():
|
if not folder.is_dir():
|
||||||
|
@@ -10,7 +10,7 @@ from typing import Any, Dict, List
|
|||||||
|
|
||||||
import rapidjson
|
import rapidjson
|
||||||
|
|
||||||
from freqtrade.constants import MINIMAL_CONFIG, Config
|
from freqtrade.constants import MINIMAL_CONFIG
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.misc import deep_merge_dicts
|
from freqtrade.misc import deep_merge_dicts
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ def load_from_files(files: List[str], base_path: Path = None, level: int = 0) ->
|
|||||||
Recursively load configuration files if specified.
|
Recursively load configuration files if specified.
|
||||||
Sub-files are assumed to be relative to the initial config.
|
Sub-files are assumed to be relative to the initial config.
|
||||||
"""
|
"""
|
||||||
config: Config = {}
|
config: Dict[str, Any] = {}
|
||||||
if level > 5:
|
if level > 5:
|
||||||
raise OperationalException("Config loop detected.")
|
raise OperationalException("Config loop detected.")
|
||||||
|
|
||||||
|
@@ -3,12 +3,11 @@ This module contains the argument manager class
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
|
|
||||||
from freqtrade.constants import DATETIME_PRINT_FORMAT
|
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
@@ -30,52 +29,6 @@ class TimeRange:
|
|||||||
self.startts: int = startts
|
self.startts: int = startts
|
||||||
self.stopts: int = stopts
|
self.stopts: int = stopts
|
||||||
|
|
||||||
@property
|
|
||||||
def startdt(self) -> Optional[datetime]:
|
|
||||||
if self.startts:
|
|
||||||
return datetime.fromtimestamp(self.startts, tz=timezone.utc)
|
|
||||||
return None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def stopdt(self) -> Optional[datetime]:
|
|
||||||
if self.stopts:
|
|
||||||
return datetime.fromtimestamp(self.stopts, tz=timezone.utc)
|
|
||||||
return None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def timerange_str(self) -> str:
|
|
||||||
"""
|
|
||||||
Returns a string representation of the timerange as used by parse_timerange.
|
|
||||||
Follows the format yyyymmdd-yyyymmdd - leaving out the parts that are not set.
|
|
||||||
"""
|
|
||||||
start = ''
|
|
||||||
stop = ''
|
|
||||||
if startdt := self.startdt:
|
|
||||||
start = startdt.strftime('%Y%m%d')
|
|
||||||
if stopdt := self.stopdt:
|
|
||||||
stop = stopdt.strftime('%Y%m%d')
|
|
||||||
return f"{start}-{stop}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def start_fmt(self) -> str:
|
|
||||||
"""
|
|
||||||
Returns a string representation of the start date
|
|
||||||
"""
|
|
||||||
val = 'unbounded'
|
|
||||||
if (startdt := self.startdt) is not None:
|
|
||||||
val = startdt.strftime(DATETIME_PRINT_FORMAT)
|
|
||||||
return val
|
|
||||||
|
|
||||||
@property
|
|
||||||
def stop_fmt(self) -> str:
|
|
||||||
"""
|
|
||||||
Returns a string representation of the stop date
|
|
||||||
"""
|
|
||||||
val = 'unbounded'
|
|
||||||
if (stopdt := self.stopdt) is not None:
|
|
||||||
val = stopdt.strftime(DATETIME_PRINT_FORMAT)
|
|
||||||
return val
|
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
"""Override the default Equals behavior"""
|
"""Override the default Equals behavior"""
|
||||||
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
||||||
|
@@ -3,9 +3,9 @@
|
|||||||
"""
|
"""
|
||||||
bot constants
|
bot constants
|
||||||
"""
|
"""
|
||||||
from typing import Any, Dict, List, Literal, Tuple
|
from typing import List, Literal, Tuple
|
||||||
|
|
||||||
from freqtrade.enums import CandleType, RPCMessageType
|
from freqtrade.enums import CandleType
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_CONFIG = 'config.json'
|
DEFAULT_CONFIG = 'config.json'
|
||||||
@@ -23,21 +23,19 @@ REQUIRED_ORDERTIF = ['entry', 'exit']
|
|||||||
REQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']
|
REQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']
|
||||||
PRICING_SIDES = ['ask', 'bid', 'same', 'other']
|
PRICING_SIDES = ['ask', 'bid', 'same', 'other']
|
||||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||||
_ORDERTIF_POSSIBILITIES = ['GTC', 'FOK', 'IOC', 'PO']
|
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||||
ORDERTIF_POSSIBILITIES = _ORDERTIF_POSSIBILITIES + [t.lower() for t in _ORDERTIF_POSSIBILITIES]
|
|
||||||
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
||||||
'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',
|
'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',
|
||||||
'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily',
|
'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily',
|
||||||
'CalmarHyperOptLoss',
|
'CalmarHyperOptLoss',
|
||||||
'MaxDrawDownHyperOptLoss', 'MaxDrawDownRelativeHyperOptLoss',
|
'MaxDrawDownHyperOptLoss', 'MaxDrawDownRelativeHyperOptLoss',
|
||||||
'ProfitDrawDownHyperOptLoss']
|
'ProfitDrawDownHyperOptLoss']
|
||||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'ProducerPairList',
|
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList',
|
||||||
'AgeFilter', 'OffsetFilter', 'PerformanceFilter',
|
'AgeFilter', 'OffsetFilter', 'PerformanceFilter',
|
||||||
'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter',
|
'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter',
|
||||||
'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter']
|
'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter']
|
||||||
AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard']
|
AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard']
|
||||||
AVAILABLE_DATAHANDLERS_TRADES = ['json', 'jsongz', 'hdf5']
|
AVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5']
|
||||||
AVAILABLE_DATAHANDLERS = AVAILABLE_DATAHANDLERS_TRADES + ['feather', 'parquet']
|
|
||||||
BACKTEST_BREAKDOWNS = ['day', 'week', 'month']
|
BACKTEST_BREAKDOWNS = ['day', 'week', 'month']
|
||||||
BACKTEST_CACHE_AGE = ['none', 'day', 'week', 'month']
|
BACKTEST_CACHE_AGE = ['none', 'day', 'week', 'month']
|
||||||
BACKTEST_CACHE_DEFAULT = 'day'
|
BACKTEST_CACHE_DEFAULT = 'day'
|
||||||
@@ -159,7 +157,6 @@ CONF_SCHEMA = {
|
|||||||
'ignore_buying_expired_candle_after': {'type': 'number'},
|
'ignore_buying_expired_candle_after': {'type': 'number'},
|
||||||
'trading_mode': {'type': 'string', 'enum': TRADING_MODES},
|
'trading_mode': {'type': 'string', 'enum': TRADING_MODES},
|
||||||
'margin_mode': {'type': 'string', 'enum': MARGIN_MODES},
|
'margin_mode': {'type': 'string', 'enum': MARGIN_MODES},
|
||||||
'reduce_df_footprint': {'type': 'boolean', 'default': False},
|
|
||||||
'liquidation_buffer': {'type': 'number', 'minimum': 0.0, 'maximum': 0.99},
|
'liquidation_buffer': {'type': 'number', 'minimum': 0.0, 'maximum': 0.99},
|
||||||
'backtest_breakdown': {
|
'backtest_breakdown': {
|
||||||
'type': 'array',
|
'type': 'array',
|
||||||
@@ -245,7 +242,6 @@ CONF_SCHEMA = {
|
|||||||
'exchange': {'$ref': '#/definitions/exchange'},
|
'exchange': {'$ref': '#/definitions/exchange'},
|
||||||
'edge': {'$ref': '#/definitions/edge'},
|
'edge': {'$ref': '#/definitions/edge'},
|
||||||
'freqai': {'$ref': '#/definitions/freqai'},
|
'freqai': {'$ref': '#/definitions/freqai'},
|
||||||
'external_message_consumer': {'$ref': '#/definitions/external_message_consumer'},
|
|
||||||
'experimental': {
|
'experimental': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -283,7 +279,6 @@ CONF_SCHEMA = {
|
|||||||
'enabled': {'type': 'boolean'},
|
'enabled': {'type': 'boolean'},
|
||||||
'token': {'type': 'string'},
|
'token': {'type': 'string'},
|
||||||
'chat_id': {'type': 'string'},
|
'chat_id': {'type': 'string'},
|
||||||
'allow_custom_messages': {'type': 'boolean', 'default': True},
|
|
||||||
'balance_dust_level': {'type': 'number', 'minimum': 0.0},
|
'balance_dust_level': {'type': 'number', 'minimum': 0.0},
|
||||||
'notification_settings': {
|
'notification_settings': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@@ -293,12 +288,11 @@ CONF_SCHEMA = {
|
|||||||
'warning': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'warning': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'startup': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'startup': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'entry': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'entry': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'entry_fill': {
|
'entry_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'type': 'string',
|
'entry_fill': {'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
'default': 'off'
|
'default': 'off'
|
||||||
},
|
},
|
||||||
'entry_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS, },
|
|
||||||
'exit': {
|
'exit': {
|
||||||
'type': ['string', 'object'],
|
'type': ['string', 'object'],
|
||||||
'additionalProperties': {
|
'additionalProperties': {
|
||||||
@@ -306,12 +300,12 @@ CONF_SCHEMA = {
|
|||||||
'enum': TELEGRAM_SETTING_OPTIONS
|
'enum': TELEGRAM_SETTING_OPTIONS
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
'exit_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'exit_fill': {
|
'exit_fill': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
'default': 'on'
|
'default': 'on'
|
||||||
},
|
},
|
||||||
'exit_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
|
||||||
'protection_trigger': {
|
'protection_trigger': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
@@ -320,17 +314,14 @@ CONF_SCHEMA = {
|
|||||||
'protection_trigger_global': {
|
'protection_trigger_global': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
'default': 'on'
|
|
||||||
},
|
},
|
||||||
'show_candle': {
|
'show_candle': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': ['off', 'ohlc'],
|
'enum': ['off', 'ohlc'],
|
||||||
'default': 'off'
|
|
||||||
},
|
},
|
||||||
'strategy_msg': {
|
'strategy_msg': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
'default': 'on'
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -346,8 +337,6 @@ CONF_SCHEMA = {
|
|||||||
'format': {'type': 'string', 'enum': WEBHOOK_FORMAT_OPTIONS, 'default': 'form'},
|
'format': {'type': 'string', 'enum': WEBHOOK_FORMAT_OPTIONS, 'default': 'form'},
|
||||||
'retries': {'type': 'integer', 'minimum': 0},
|
'retries': {'type': 'integer', 'minimum': 0},
|
||||||
'retry_delay': {'type': 'number', 'minimum': 0},
|
'retry_delay': {'type': 'number', 'minimum': 0},
|
||||||
**dict([(x, {'type': 'object'}) for x in RPCMessageType]),
|
|
||||||
# Below -> Deprecated
|
|
||||||
'webhookentry': {'type': 'object'},
|
'webhookentry': {'type': 'object'},
|
||||||
'webhookentrycancel': {'type': 'object'},
|
'webhookentrycancel': {'type': 'object'},
|
||||||
'webhookentryfill': {'type': 'object'},
|
'webhookentryfill': {'type': 'object'},
|
||||||
@@ -410,7 +399,6 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'username': {'type': 'string'},
|
'username': {'type': 'string'},
|
||||||
'password': {'type': 'string'},
|
'password': {'type': 'string'},
|
||||||
'ws_token': {'type': ['string', 'array'], 'items': {'type': 'string'}},
|
|
||||||
'jwt_secret_key': {'type': 'string'},
|
'jwt_secret_key': {'type': 'string'},
|
||||||
'CORS_origins': {'type': 'array', 'items': {'type': 'string'}},
|
'CORS_origins': {'type': 'array', 'items': {'type': 'string'}},
|
||||||
'verbosity': {'type': 'string', 'enum': ['error', 'info']},
|
'verbosity': {'type': 'string', 'enum': ['error', 'info']},
|
||||||
@@ -439,7 +427,7 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'dataformat_trades': {
|
'dataformat_trades': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': AVAILABLE_DATAHANDLERS_TRADES,
|
'enum': AVAILABLE_DATAHANDLERS,
|
||||||
'default': 'jsongz'
|
'default': 'jsongz'
|
||||||
},
|
},
|
||||||
'position_adjustment_enable': {'type': 'boolean'},
|
'position_adjustment_enable': {'type': 'boolean'},
|
||||||
@@ -495,56 +483,12 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'required': ['process_throttle_secs', 'allowed_risk']
|
'required': ['process_throttle_secs', 'allowed_risk']
|
||||||
},
|
},
|
||||||
'external_message_consumer': {
|
|
||||||
'type': 'object',
|
|
||||||
'properties': {
|
|
||||||
'enabled': {'type': 'boolean', 'default': False},
|
|
||||||
'producers': {
|
|
||||||
'type': 'array',
|
|
||||||
'items': {
|
|
||||||
'type': 'object',
|
|
||||||
'properties': {
|
|
||||||
'name': {'type': 'string'},
|
|
||||||
'host': {'type': 'string'},
|
|
||||||
'port': {
|
|
||||||
'type': 'integer',
|
|
||||||
'default': 8080,
|
|
||||||
'minimum': 0,
|
|
||||||
'maximum': 65535
|
|
||||||
},
|
|
||||||
'secure': {'type': 'boolean', 'default': False},
|
|
||||||
'ws_token': {'type': 'string'},
|
|
||||||
},
|
|
||||||
'required': ['name', 'host', 'ws_token']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'wait_timeout': {'type': 'integer', 'minimum': 0},
|
|
||||||
'sleep_time': {'type': 'integer', 'minimum': 0},
|
|
||||||
'ping_timeout': {'type': 'integer', 'minimum': 0},
|
|
||||||
'remove_entry_exit_signals': {'type': 'boolean', 'default': False},
|
|
||||||
'initial_candle_limit': {
|
|
||||||
'type': 'integer',
|
|
||||||
'minimum': 0,
|
|
||||||
'maximum': 1500,
|
|
||||||
'default': 1500
|
|
||||||
},
|
|
||||||
'message_size_limit': { # In megabytes
|
|
||||||
'type': 'integer',
|
|
||||||
'minimum': 1,
|
|
||||||
'maxmium': 20,
|
|
||||||
'default': 8,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'required': ['producers']
|
|
||||||
},
|
|
||||||
"freqai": {
|
"freqai": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"enabled": {"type": "boolean", "default": False},
|
"enabled": {"type": "boolean", "default": False},
|
||||||
"keras": {"type": "boolean", "default": False},
|
"keras": {"type": "boolean", "default": False},
|
||||||
"write_metrics_to_disk": {"type": "boolean", "default": False},
|
"conv_width": {"type": "integer", "default": 2},
|
||||||
"purge_old_models": {"type": "boolean", "default": True},
|
|
||||||
"conv_width": {"type": "integer", "default": 1},
|
|
||||||
"train_period_days": {"type": "integer", "default": 0},
|
"train_period_days": {"type": "integer", "default": 0},
|
||||||
"backtest_period_days": {"type": "number", "default": 7},
|
"backtest_period_days": {"type": "number", "default": 7},
|
||||||
"identifier": {"type": "string", "default": "example"},
|
"identifier": {"type": "string", "default": "example"},
|
||||||
@@ -559,7 +503,6 @@ CONF_SCHEMA = {
|
|||||||
"weight_factor": {"type": "number", "default": 0},
|
"weight_factor": {"type": "number", "default": 0},
|
||||||
"principal_component_analysis": {"type": "boolean", "default": False},
|
"principal_component_analysis": {"type": "boolean", "default": False},
|
||||||
"use_SVM_to_remove_outliers": {"type": "boolean", "default": False},
|
"use_SVM_to_remove_outliers": {"type": "boolean", "default": False},
|
||||||
"plot_feature_importances": {"type": "integer", "default": 0},
|
|
||||||
"svm_params": {"type": "object",
|
"svm_params": {"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"shuffle": {"type": "boolean", "default": False},
|
"shuffle": {"type": "boolean", "default": False},
|
||||||
@@ -574,7 +517,6 @@ CONF_SCHEMA = {
|
|||||||
"properties": {
|
"properties": {
|
||||||
"test_size": {"type": "number"},
|
"test_size": {"type": "number"},
|
||||||
"random_state": {"type": "integer"},
|
"random_state": {"type": "integer"},
|
||||||
"shuffle": {"type": "boolean", "default": False}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"model_training_parameters": {
|
"model_training_parameters": {
|
||||||
@@ -660,6 +602,3 @@ LongShort = Literal['long', 'short']
|
|||||||
EntryExit = Literal['entry', 'exit']
|
EntryExit = Literal['entry', 'exit']
|
||||||
BuySell = Literal['buy', 'sell']
|
BuySell = Literal['buy', 'sell']
|
||||||
MakerTaker = Literal['maker', 'taker']
|
MakerTaker = Literal['maker', 'taker']
|
||||||
BidAsk = Literal['bid', 'ask']
|
|
||||||
|
|
||||||
Config = Dict[str, Any]
|
|
||||||
|
@@ -26,7 +26,7 @@ BT_DATA_COLUMNS = ['pair', 'stake_amount', 'amount', 'open_date', 'close_date',
|
|||||||
'profit_ratio', 'profit_abs', 'exit_reason',
|
'profit_ratio', 'profit_abs', 'exit_reason',
|
||||||
'initial_stop_loss_abs', 'initial_stop_loss_ratio', 'stop_loss_abs',
|
'initial_stop_loss_abs', 'initial_stop_loss_ratio', 'stop_loss_abs',
|
||||||
'stop_loss_ratio', 'min_rate', 'max_rate', 'is_open', 'enter_tag',
|
'stop_loss_ratio', 'min_rate', 'max_rate', 'is_open', 'enter_tag',
|
||||||
'leverage', 'is_short', 'open_timestamp', 'close_timestamp', 'orders'
|
'is_short', 'open_timestamp', 'close_timestamp', 'orders'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -280,13 +280,11 @@ def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = Non
|
|||||||
# Compatibility support for pre short Columns
|
# Compatibility support for pre short Columns
|
||||||
if 'is_short' not in df.columns:
|
if 'is_short' not in df.columns:
|
||||||
df['is_short'] = 0
|
df['is_short'] = 0
|
||||||
if 'leverage' not in df.columns:
|
|
||||||
df['leverage'] = 1.0
|
|
||||||
if 'enter_tag' not in df.columns:
|
if 'enter_tag' not in df.columns:
|
||||||
df['enter_tag'] = df['buy_tag']
|
df['enter_tag'] = df['buy_tag']
|
||||||
df = df.drop(['buy_tag'], axis=1)
|
df = df.drop(['buy_tag'], axis=1)
|
||||||
if 'orders' not in df.columns:
|
if 'orders' not in df.columns:
|
||||||
df['orders'] = None
|
df.loc[:, 'orders'] = None
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# old format - only with lists.
|
# old format - only with lists.
|
||||||
@@ -343,9 +341,9 @@ def trade_list_to_dataframe(trades: List[LocalTrade]) -> pd.DataFrame:
|
|||||||
"""
|
"""
|
||||||
df = pd.DataFrame.from_records([t.to_json(True) for t in trades], columns=BT_DATA_COLUMNS)
|
df = pd.DataFrame.from_records([t.to_json(True) for t in trades], columns=BT_DATA_COLUMNS)
|
||||||
if len(df) > 0:
|
if len(df) > 0:
|
||||||
df['close_date'] = pd.to_datetime(df['close_date'], utc=True)
|
df.loc[:, 'close_date'] = pd.to_datetime(df['close_date'], utc=True)
|
||||||
df['open_date'] = pd.to_datetime(df['open_date'], utc=True)
|
df.loc[:, 'open_date'] = pd.to_datetime(df['open_date'], utc=True)
|
||||||
df['close_rate'] = df['close_rate'].astype('float64')
|
df.loc[:, 'close_rate'] = df['close_rate'].astype('float64')
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
@@ -3,14 +3,14 @@ Functions to convert data from one format to another
|
|||||||
"""
|
"""
|
||||||
import itertools
|
import itertools
|
||||||
import logging
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
from typing import Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas import DataFrame, to_datetime
|
from pandas import DataFrame, to_datetime
|
||||||
|
|
||||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, Config, TradeList
|
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
|
||||||
from freqtrade.enums import CandleType
|
from freqtrade.enums import CandleType
|
||||||
|
|
||||||
|
|
||||||
@@ -47,7 +47,8 @@ def ohlcv_to_dataframe(ohlcv: list, timeframe: str, pair: str, *,
|
|||||||
|
|
||||||
|
|
||||||
def clean_ohlcv_dataframe(data: DataFrame, timeframe: str, pair: str, *,
|
def clean_ohlcv_dataframe(data: DataFrame, timeframe: str, pair: str, *,
|
||||||
fill_missing: bool, drop_incomplete: bool) -> DataFrame:
|
fill_missing: bool = True,
|
||||||
|
drop_incomplete: bool = True) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Cleanse a OHLCV dataframe by
|
Cleanse a OHLCV dataframe by
|
||||||
* Grouping it by date (removes duplicate tics)
|
* Grouping it by date (removes duplicate tics)
|
||||||
@@ -137,9 +138,11 @@ def trim_dataframe(df: DataFrame, timerange, df_date_col: str = 'date',
|
|||||||
df = df.iloc[startup_candles:, :]
|
df = df.iloc[startup_candles:, :]
|
||||||
else:
|
else:
|
||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
df = df.loc[df[df_date_col] >= timerange.startdt, :]
|
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||||
|
df = df.loc[df[df_date_col] >= start, :]
|
||||||
if timerange.stoptype == 'date':
|
if timerange.stoptype == 'date':
|
||||||
df = df.loc[df[df_date_col] <= timerange.stopdt, :]
|
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||||
|
df = df.loc[df[df_date_col] <= stop, :]
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
@@ -234,7 +237,7 @@ def trades_to_ohlcv(trades: TradeList, timeframe: str) -> DataFrame:
|
|||||||
return df_new.loc[:, DEFAULT_DATAFRAME_COLUMNS]
|
return df_new.loc[:, DEFAULT_DATAFRAME_COLUMNS]
|
||||||
|
|
||||||
|
|
||||||
def convert_trades_format(config: Config, convert_from: str, convert_to: str, erase: bool):
|
def convert_trades_format(config: Dict[str, Any], convert_from: str, convert_to: str, erase: bool):
|
||||||
"""
|
"""
|
||||||
Convert trades from one format to another format.
|
Convert trades from one format to another format.
|
||||||
:param config: Config dictionary
|
:param config: Config dictionary
|
||||||
@@ -260,7 +263,7 @@ def convert_trades_format(config: Config, convert_from: str, convert_to: str, er
|
|||||||
|
|
||||||
|
|
||||||
def convert_ohlcv_format(
|
def convert_ohlcv_format(
|
||||||
config: Config,
|
config: Dict[str, Any],
|
||||||
convert_from: str,
|
convert_from: str,
|
||||||
convert_to: str,
|
convert_to: str,
|
||||||
erase: bool,
|
erase: bool,
|
||||||
@@ -289,7 +292,6 @@ def convert_ohlcv_format(
|
|||||||
timeframe,
|
timeframe,
|
||||||
candle_type=candle_type
|
candle_type=candle_type
|
||||||
))
|
))
|
||||||
config['pairs'] = sorted(set(config['pairs']))
|
|
||||||
logger.info(f"Converting candle (OHLCV) data for {config['pairs']}")
|
logger.info(f"Converting candle (OHLCV) data for {config['pairs']}")
|
||||||
|
|
||||||
for timeframe in timeframes:
|
for timeframe in timeframes:
|
||||||
@@ -300,7 +302,7 @@ def convert_ohlcv_format(
|
|||||||
drop_incomplete=False,
|
drop_incomplete=False,
|
||||||
startup_candles=0,
|
startup_candles=0,
|
||||||
candle_type=candle_type)
|
candle_type=candle_type)
|
||||||
logger.info(f"Converting {len(data)} {timeframe} {candle_type} candles for {pair}")
|
logger.info(f"Converting {len(data)} {candle_type} candles for {pair}")
|
||||||
if len(data) > 0:
|
if len(data) > 0:
|
||||||
trg.ohlcv_store(
|
trg.ohlcv_store(
|
||||||
pair=pair,
|
pair=pair,
|
||||||
@@ -311,29 +313,3 @@ def convert_ohlcv_format(
|
|||||||
if erase and convert_from != convert_to:
|
if erase and convert_from != convert_to:
|
||||||
logger.info(f"Deleting source data for {pair} / {timeframe}")
|
logger.info(f"Deleting source data for {pair} / {timeframe}")
|
||||||
src.ohlcv_purge(pair=pair, timeframe=timeframe, candle_type=candle_type)
|
src.ohlcv_purge(pair=pair, timeframe=timeframe, candle_type=candle_type)
|
||||||
|
|
||||||
|
|
||||||
def reduce_dataframe_footprint(df: DataFrame) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Ensure all values are float32 in the incoming dataframe.
|
|
||||||
:param df: Dataframe to be converted to float/int 32s
|
|
||||||
:return: Dataframe converted to float/int 32s
|
|
||||||
"""
|
|
||||||
|
|
||||||
logger.debug(f"Memory usage of dataframe is "
|
|
||||||
f"{df.memory_usage().sum() / 1024**2:.2f} MB")
|
|
||||||
|
|
||||||
df_dtypes = df.dtypes
|
|
||||||
for column, dtype in df_dtypes.items():
|
|
||||||
if column in ['open', 'high', 'low', 'close', 'volume']:
|
|
||||||
continue
|
|
||||||
if dtype == np.float64:
|
|
||||||
df_dtypes[column] = np.float32
|
|
||||||
elif dtype == np.int64:
|
|
||||||
df_dtypes[column] = np.int32
|
|
||||||
df = df.astype(df_dtypes)
|
|
||||||
|
|
||||||
logger.debug(f"Memory usage after optimization is: "
|
|
||||||
f"{df.memory_usage().sum() / 1024**2:.2f} MB")
|
|
||||||
|
|
||||||
return df
|
|
||||||
|
@@ -12,12 +12,11 @@ from typing import Any, Dict, List, Optional, Tuple
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import Config, ListPairsWithTimeframes, PairWithTimeframe
|
from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe
|
||||||
from freqtrade.data.history import load_pair_history
|
from freqtrade.data.history import load_pair_history
|
||||||
from freqtrade.enums import CandleType, RPCMessageType, RunMode
|
from freqtrade.enums import CandleType, RunMode
|
||||||
from freqtrade.exceptions import ExchangeError, OperationalException
|
from freqtrade.exceptions import ExchangeError, OperationalException
|
||||||
from freqtrade.exchange import Exchange, timeframe_to_seconds
|
from freqtrade.exchange import Exchange, timeframe_to_seconds
|
||||||
from freqtrade.rpc import RPCManager
|
|
||||||
from freqtrade.util import PeriodicCache
|
from freqtrade.util import PeriodicCache
|
||||||
|
|
||||||
|
|
||||||
@@ -29,33 +28,17 @@ MAX_DATAFRAME_CANDLES = 1000
|
|||||||
|
|
||||||
class DataProvider:
|
class DataProvider:
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, config: dict, exchange: Optional[Exchange], pairlists=None) -> None:
|
||||||
self,
|
|
||||||
config: Config,
|
|
||||||
exchange: Optional[Exchange],
|
|
||||||
pairlists=None,
|
|
||||||
rpc: Optional[RPCManager] = None
|
|
||||||
) -> None:
|
|
||||||
self._config = config
|
self._config = config
|
||||||
self._exchange = exchange
|
self._exchange = exchange
|
||||||
self._pairlists = pairlists
|
self._pairlists = pairlists
|
||||||
self.__rpc = rpc
|
|
||||||
self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {}
|
self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {}
|
||||||
self.__slice_index: Optional[int] = None
|
self.__slice_index: Optional[int] = None
|
||||||
self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {}
|
self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {}
|
||||||
self.__producer_pairs_df: Dict[str,
|
|
||||||
Dict[PairWithTimeframe, Tuple[DataFrame, datetime]]] = {}
|
|
||||||
self.__producer_pairs: Dict[str, List[str]] = {}
|
|
||||||
self._msg_queue: deque = deque()
|
self._msg_queue: deque = deque()
|
||||||
|
|
||||||
self._default_candle_type = self._config.get('candle_type_def', CandleType.SPOT)
|
|
||||||
self._default_timeframe = self._config.get('timeframe', '1h')
|
|
||||||
|
|
||||||
self.__msg_cache = PeriodicCache(
|
self.__msg_cache = PeriodicCache(
|
||||||
maxsize=1000, ttl=timeframe_to_seconds(self._default_timeframe))
|
maxsize=1000, ttl=timeframe_to_seconds(self._config.get('timeframe', '1h')))
|
||||||
|
|
||||||
self.producers = self._config.get('external_message_consumer', {}).get('producers', [])
|
|
||||||
self.external_data_enabled = len(self.producers) > 0
|
|
||||||
|
|
||||||
def _set_dataframe_max_index(self, limit_index: int):
|
def _set_dataframe_max_index(self, limit_index: int):
|
||||||
"""
|
"""
|
||||||
@@ -80,110 +63,9 @@ class DataProvider:
|
|||||||
:param dataframe: analyzed dataframe
|
:param dataframe: analyzed dataframe
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
pair_key = (pair, timeframe, candle_type)
|
self.__cached_pairs[(pair, timeframe, candle_type)] = (
|
||||||
self.__cached_pairs[pair_key] = (
|
|
||||||
dataframe, datetime.now(timezone.utc))
|
dataframe, datetime.now(timezone.utc))
|
||||||
|
|
||||||
# For multiple producers we will want to merge the pairlists instead of overwriting
|
|
||||||
def _set_producer_pairs(self, pairlist: List[str], producer_name: str = "default"):
|
|
||||||
"""
|
|
||||||
Set the pairs received to later be used.
|
|
||||||
|
|
||||||
:param pairlist: List of pairs
|
|
||||||
"""
|
|
||||||
self.__producer_pairs[producer_name] = pairlist
|
|
||||||
|
|
||||||
def get_producer_pairs(self, producer_name: str = "default") -> List[str]:
|
|
||||||
"""
|
|
||||||
Get the pairs cached from the producer
|
|
||||||
|
|
||||||
:returns: List of pairs
|
|
||||||
"""
|
|
||||||
return self.__producer_pairs.get(producer_name, []).copy()
|
|
||||||
|
|
||||||
def _emit_df(
|
|
||||||
self,
|
|
||||||
pair_key: PairWithTimeframe,
|
|
||||||
dataframe: DataFrame
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Send this dataframe as an ANALYZED_DF message to RPC
|
|
||||||
|
|
||||||
:param pair_key: PairWithTimeframe tuple
|
|
||||||
:param data: Tuple containing the DataFrame and the datetime it was cached
|
|
||||||
"""
|
|
||||||
if self.__rpc:
|
|
||||||
self.__rpc.send_msg(
|
|
||||||
{
|
|
||||||
'type': RPCMessageType.ANALYZED_DF,
|
|
||||||
'data': {
|
|
||||||
'key': pair_key,
|
|
||||||
'df': dataframe,
|
|
||||||
'la': datetime.now(timezone.utc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
def _add_external_df(
|
|
||||||
self,
|
|
||||||
pair: str,
|
|
||||||
dataframe: DataFrame,
|
|
||||||
last_analyzed: datetime,
|
|
||||||
timeframe: str,
|
|
||||||
candle_type: CandleType,
|
|
||||||
producer_name: str = "default"
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Add the pair data to this class from an external source.
|
|
||||||
|
|
||||||
:param pair: pair to get the data for
|
|
||||||
:param timeframe: Timeframe to get data for
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
"""
|
|
||||||
pair_key = (pair, timeframe, candle_type)
|
|
||||||
|
|
||||||
if producer_name not in self.__producer_pairs_df:
|
|
||||||
self.__producer_pairs_df[producer_name] = {}
|
|
||||||
|
|
||||||
_last_analyzed = datetime.now(timezone.utc) if not last_analyzed else last_analyzed
|
|
||||||
|
|
||||||
self.__producer_pairs_df[producer_name][pair_key] = (dataframe, _last_analyzed)
|
|
||||||
logger.debug(f"External DataFrame for {pair_key} from {producer_name} added.")
|
|
||||||
|
|
||||||
def get_producer_df(
|
|
||||||
self,
|
|
||||||
pair: str,
|
|
||||||
timeframe: Optional[str] = None,
|
|
||||||
candle_type: Optional[CandleType] = None,
|
|
||||||
producer_name: str = "default"
|
|
||||||
) -> Tuple[DataFrame, datetime]:
|
|
||||||
"""
|
|
||||||
Get the pair data from producers.
|
|
||||||
|
|
||||||
:param pair: pair to get the data for
|
|
||||||
:param timeframe: Timeframe to get data for
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
:returns: Tuple of the DataFrame and last analyzed timestamp
|
|
||||||
"""
|
|
||||||
_timeframe = self._default_timeframe if not timeframe else timeframe
|
|
||||||
_candle_type = self._default_candle_type if not candle_type else candle_type
|
|
||||||
|
|
||||||
pair_key = (pair, _timeframe, _candle_type)
|
|
||||||
|
|
||||||
# If we have no data from this Producer yet
|
|
||||||
if producer_name not in self.__producer_pairs_df:
|
|
||||||
# We don't have this data yet, return empty DataFrame and datetime (01-01-1970)
|
|
||||||
return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc))
|
|
||||||
|
|
||||||
# If we do have data from that Producer, but no data on this pair_key
|
|
||||||
if pair_key not in self.__producer_pairs_df[producer_name]:
|
|
||||||
# We don't have this data yet, return empty DataFrame and datetime (01-01-1970)
|
|
||||||
return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc))
|
|
||||||
|
|
||||||
# We have it, return this data
|
|
||||||
df, la = self.__producer_pairs_df[producer_name][pair_key]
|
|
||||||
return (df.copy(), la)
|
|
||||||
|
|
||||||
def add_pairlisthandler(self, pairlists) -> None:
|
def add_pairlisthandler(self, pairlists) -> None:
|
||||||
"""
|
"""
|
||||||
Allow adding pairlisthandler after initialization
|
Allow adding pairlisthandler after initialization
|
||||||
@@ -204,16 +86,14 @@ class DataProvider:
|
|||||||
"""
|
"""
|
||||||
_candle_type = CandleType.from_string(
|
_candle_type = CandleType.from_string(
|
||||||
candle_type) if candle_type != '' else self._config['candle_type_def']
|
candle_type) if candle_type != '' else self._config['candle_type_def']
|
||||||
saved_pair: PairWithTimeframe = (pair, str(timeframe), _candle_type)
|
saved_pair = (pair, str(timeframe), _candle_type)
|
||||||
if saved_pair not in self.__cached_pairs_backtesting:
|
if saved_pair not in self.__cached_pairs_backtesting:
|
||||||
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')))
|
||||||
|
# Move informative start time respecting startup_candle_count
|
||||||
# It is not necessary to add the training candles, as they
|
timerange.subtract_start(
|
||||||
# were already added at the beginning of the backtest.
|
timeframe_to_seconds(str(timeframe)) * self._config.get('startup_candle_count', 0)
|
||||||
startup_candles = self.get_required_startup(str(timeframe), False)
|
)
|
||||||
tf_seconds = timeframe_to_seconds(str(timeframe))
|
|
||||||
timerange.subtract_start(tf_seconds * startup_candles)
|
|
||||||
self.__cached_pairs_backtesting[saved_pair] = load_pair_history(
|
self.__cached_pairs_backtesting[saved_pair] = load_pair_history(
|
||||||
pair=pair,
|
pair=pair,
|
||||||
timeframe=timeframe or self._config['timeframe'],
|
timeframe=timeframe or self._config['timeframe'],
|
||||||
@@ -225,23 +105,6 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
return self.__cached_pairs_backtesting[saved_pair].copy()
|
return self.__cached_pairs_backtesting[saved_pair].copy()
|
||||||
|
|
||||||
def get_required_startup(self, timeframe: str, add_train_candles: bool = True) -> int:
|
|
||||||
freqai_config = self._config.get('freqai', {})
|
|
||||||
if not freqai_config.get('enabled', False):
|
|
||||||
return self._config.get('startup_candle_count', 0)
|
|
||||||
else:
|
|
||||||
startup_candles = self._config.get('startup_candle_count', 0)
|
|
||||||
indicator_periods = freqai_config['feature_parameters']['indicator_periods_candles']
|
|
||||||
# make sure the startupcandles is at least the set maximum indicator periods
|
|
||||||
self._config['startup_candle_count'] = max(startup_candles, max(indicator_periods))
|
|
||||||
tf_seconds = timeframe_to_seconds(timeframe)
|
|
||||||
train_candles = 0
|
|
||||||
if add_train_candles:
|
|
||||||
train_candles = freqai_config['train_period_days'] * 86400 / tf_seconds
|
|
||||||
total_candles = int(self._config['startup_candle_count'] + train_candles)
|
|
||||||
logger.info(f'Increasing startup_candle_count for freqai to {total_candles}')
|
|
||||||
return total_candles
|
|
||||||
|
|
||||||
def get_pair_dataframe(
|
def get_pair_dataframe(
|
||||||
self,
|
self,
|
||||||
pair: str,
|
pair: str,
|
||||||
@@ -318,9 +181,7 @@ class DataProvider:
|
|||||||
Clear pair dataframe cache.
|
Clear pair dataframe cache.
|
||||||
"""
|
"""
|
||||||
self.__cached_pairs = {}
|
self.__cached_pairs = {}
|
||||||
# Don't reset backtesting pairs -
|
self.__cached_pairs_backtesting = {}
|
||||||
# otherwise they're reloaded each time during hyperopt due to with analyze_per_epoch
|
|
||||||
# self.__cached_pairs_backtesting = {}
|
|
||||||
self.__slice_index = 0
|
self.__slice_index = 0
|
||||||
|
|
||||||
# Exchange functions
|
# Exchange functions
|
||||||
|
@@ -1,130 +0,0 @@
|
|||||||
import logging
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from pandas import DataFrame, read_feather, to_datetime
|
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
|
||||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, TradeList
|
|
||||||
from freqtrade.enums import CandleType
|
|
||||||
|
|
||||||
from .idatahandler import IDataHandler
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class FeatherDataHandler(IDataHandler):
|
|
||||||
|
|
||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
|
||||||
|
|
||||||
def ohlcv_store(
|
|
||||||
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
|
||||||
"""
|
|
||||||
Store data in json format "values".
|
|
||||||
format looks as follows:
|
|
||||||
[[<date>,<open>,<high>,<low>,<close>]]
|
|
||||||
:param pair: Pair - used to generate filename
|
|
||||||
:param timeframe: Timeframe - used to generate filename
|
|
||||||
:param data: Dataframe containing OHLCV data
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
|
||||||
self.create_dir_if_needed(filename)
|
|
||||||
|
|
||||||
data.reset_index(drop=True).loc[:, self._columns].to_feather(
|
|
||||||
filename, compression_level=9, compression='lz4')
|
|
||||||
|
|
||||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
|
||||||
timerange: Optional[TimeRange], candle_type: CandleType
|
|
||||||
) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Internal method used to load data for one pair from disk.
|
|
||||||
Implements the loading and conversion to a Pandas dataframe.
|
|
||||||
Timerange trimming and dataframe validation happens outside of this method.
|
|
||||||
:param pair: Pair to load data
|
|
||||||
:param timeframe: Timeframe (e.g. "5m")
|
|
||||||
:param timerange: Limit data to be loaded to this timerange.
|
|
||||||
Optionally implemented by subclasses to avoid loading
|
|
||||||
all data where possible.
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
|
||||||
"""
|
|
||||||
filename = self._pair_data_filename(
|
|
||||||
self._datadir, pair, timeframe, candle_type=candle_type)
|
|
||||||
if not filename.exists():
|
|
||||||
# Fallback mode for 1M files
|
|
||||||
filename = self._pair_data_filename(
|
|
||||||
self._datadir, pair, timeframe, candle_type=candle_type, no_timeframe_modify=True)
|
|
||||||
if not filename.exists():
|
|
||||||
return DataFrame(columns=self._columns)
|
|
||||||
|
|
||||||
pairdata = read_feather(filename)
|
|
||||||
pairdata.columns = self._columns
|
|
||||||
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
|
||||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
|
||||||
pairdata['date'] = to_datetime(pairdata['date'],
|
|
||||||
unit='ms',
|
|
||||||
utc=True,
|
|
||||||
infer_datetime_format=True)
|
|
||||||
return pairdata
|
|
||||||
|
|
||||||
def ohlcv_append(
|
|
||||||
self,
|
|
||||||
pair: str,
|
|
||||||
timeframe: str,
|
|
||||||
data: DataFrame,
|
|
||||||
candle_type: CandleType
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Append data to existing data structures
|
|
||||||
:param pair: Pair
|
|
||||||
:param timeframe: Timeframe this ohlcv data is for
|
|
||||||
:param data: Data to append.
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
"""
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
|
||||||
"""
|
|
||||||
Store trades data (list of Dicts) to file
|
|
||||||
:param pair: Pair - used for filename
|
|
||||||
:param data: List of Lists containing trade data,
|
|
||||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
|
||||||
"""
|
|
||||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
|
||||||
|
|
||||||
raise NotImplementedError()
|
|
||||||
# array = pa.array(data)
|
|
||||||
# array
|
|
||||||
# feather.write_feather(data, filename)
|
|
||||||
|
|
||||||
def trades_append(self, pair: str, data: TradeList):
|
|
||||||
"""
|
|
||||||
Append data to existing files
|
|
||||||
:param pair: Pair - used for filename
|
|
||||||
:param data: List of Lists containing trade data,
|
|
||||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
|
||||||
"""
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
def _trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> TradeList:
|
|
||||||
"""
|
|
||||||
Load a pair from file, either .json.gz or .json
|
|
||||||
# TODO: respect timerange ...
|
|
||||||
:param pair: Load trades for this pair
|
|
||||||
:param timerange: Timerange to load trades for - currently not implemented
|
|
||||||
:return: List of trades
|
|
||||||
"""
|
|
||||||
raise NotImplementedError()
|
|
||||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
|
||||||
# tradesdata = misc.file_load_json(filename)
|
|
||||||
|
|
||||||
# if not tradesdata:
|
|
||||||
# return []
|
|
||||||
|
|
||||||
# return tradesdata
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _get_file_extension(cls):
|
|
||||||
return "feather"
|
|
@@ -1,5 +1,7 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Optional
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -18,6 +20,26 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
|
|
||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
|
for the specified timeframe
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:param timeframe: Timeframe to search pairs for
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
|
:return: List of Pairs
|
||||||
|
"""
|
||||||
|
candle = ""
|
||||||
|
if candle_type != CandleType.SPOT:
|
||||||
|
datadir = datadir.joinpath('futures')
|
||||||
|
candle = f"-{candle_type}"
|
||||||
|
|
||||||
|
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + '.h5)', p.name)
|
||||||
|
for p in datadir.glob(f"*{timeframe}{candle}.h5")]
|
||||||
|
# Check if regex found something and only return these results
|
||||||
|
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||||
|
|
||||||
def ohlcv_store(
|
def ohlcv_store(
|
||||||
self, pair: str, timeframe: str, data: pd.DataFrame, candle_type: CandleType) -> None:
|
self, pair: str, timeframe: str, data: pd.DataFrame, candle_type: CandleType) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -81,7 +103,6 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
raise ValueError("Wrong dataframe format")
|
raise ValueError("Wrong dataframe format")
|
||||||
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 = pairdata.reset_index(drop=True)
|
|
||||||
return pairdata
|
return pairdata
|
||||||
|
|
||||||
def ohlcv_append(
|
def ohlcv_append(
|
||||||
@@ -100,6 +121,18 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs for which trade data is available in this
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:return: List of Pairs
|
||||||
|
"""
|
||||||
|
_tmp = [re.search(r'^(\S+)(?=\-trades.h5)', p.name)
|
||||||
|
for p in datadir.glob("*trades.h5")]
|
||||||
|
# Check if regex found something and only return these results to avoid exceptions.
|
||||||
|
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||||
|
|
||||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||||
"""
|
"""
|
||||||
Store trades data (list of Dicts) to file
|
Store trades data (list of Dicts) to file
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
import logging
|
import logging
|
||||||
import operator
|
import operator
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ def load_pair_history(pair: str,
|
|||||||
datadir: Path, *,
|
datadir: Path, *,
|
||||||
timerange: Optional[TimeRange] = None,
|
timerange: Optional[TimeRange] = None,
|
||||||
fill_up_missing: bool = True,
|
fill_up_missing: bool = True,
|
||||||
drop_incomplete: bool = False,
|
drop_incomplete: bool = True,
|
||||||
startup_candles: int = 0,
|
startup_candles: int = 0,
|
||||||
data_format: str = None,
|
data_format: str = None,
|
||||||
data_handler: IDataHandler = None,
|
data_handler: IDataHandler = None,
|
||||||
@@ -160,9 +160,9 @@ def _load_cached_data_for_updating(
|
|||||||
end = None
|
end = None
|
||||||
if timerange:
|
if timerange:
|
||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
start = timerange.startdt
|
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||||
if timerange.stoptype == 'date':
|
if timerange.stoptype == 'date':
|
||||||
end = timerange.stopdt
|
end = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||||
|
|
||||||
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
||||||
data = data_handler.ohlcv_load(pair, timeframe=timeframe,
|
data = data_handler.ohlcv_load(pair, timeframe=timeframe,
|
||||||
@@ -228,9 +228,9 @@ def _download_pair_history(pair: str, *,
|
|||||||
)
|
)
|
||||||
|
|
||||||
logger.debug("Current Start: %s",
|
logger.debug("Current Start: %s",
|
||||||
f"{data.iloc[0]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||||
logger.debug("Current End: %s",
|
logger.debug("Current End: %s",
|
||||||
f"{data.iloc[-1]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||||
|
|
||||||
# Default since_ms to 30 days if nothing is given
|
# Default since_ms to 30 days if nothing is given
|
||||||
new_data = exchange.get_historic_ohlcv(pair=pair,
|
new_data = exchange.get_historic_ohlcv(pair=pair,
|
||||||
@@ -254,9 +254,9 @@ def _download_pair_history(pair: str, *,
|
|||||||
fill_missing=False, drop_incomplete=False)
|
fill_missing=False, drop_incomplete=False)
|
||||||
|
|
||||||
logger.debug("New Start: %s",
|
logger.debug("New Start: %s",
|
||||||
f"{data.iloc[0]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||||
logger.debug("New End: %s",
|
logger.debug("New End: %s",
|
||||||
f"{data.iloc[-1]['date']:DATETIME_PRINT_FORMAT}" if not data.empty else 'None')
|
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||||
|
|
||||||
data_handler.ohlcv_store(pair, timeframe, data=data, candle_type=candle_type)
|
data_handler.ohlcv_store(pair, timeframe, data=data, candle_type=candle_type)
|
||||||
return True
|
return True
|
||||||
@@ -302,8 +302,8 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
|
|||||||
if trading_mode == 'futures':
|
if trading_mode == 'futures':
|
||||||
# Predefined candletype (and timeframe) depending on exchange
|
# Predefined candletype (and timeframe) depending on exchange
|
||||||
# Downloads what is necessary to backtest based on futures data.
|
# Downloads what is necessary to backtest based on futures data.
|
||||||
tf_mark = exchange.get_option('mark_ohlcv_timeframe')
|
tf_mark = exchange._ft_has['mark_ohlcv_timeframe']
|
||||||
fr_candle_type = CandleType.from_string(exchange.get_option('mark_ohlcv_price'))
|
fr_candle_type = CandleType.from_string(exchange._ft_has['mark_ohlcv_price'])
|
||||||
# All exchanges need FundingRate for futures trading.
|
# All exchanges need FundingRate for futures trading.
|
||||||
# The timeframe is aligned to the mark-price timeframe.
|
# The timeframe is aligned to the mark-price timeframe.
|
||||||
for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type):
|
for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type):
|
||||||
@@ -330,12 +330,13 @@ def _download_trades_history(exchange: Exchange,
|
|||||||
try:
|
try:
|
||||||
|
|
||||||
until = None
|
until = None
|
||||||
since = 0
|
|
||||||
if timerange:
|
if timerange:
|
||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
since = timerange.startts * 1000
|
since = timerange.startts * 1000
|
||||||
if timerange.stoptype == 'date':
|
if timerange.stoptype == 'date':
|
||||||
until = timerange.stopts * 1000
|
until = timerange.stopts * 1000
|
||||||
|
else:
|
||||||
|
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
|
||||||
|
|
||||||
trades = data_handler.trades_load(pair)
|
trades = data_handler.trades_load(pair)
|
||||||
|
|
||||||
@@ -348,9 +349,6 @@ def _download_trades_history(exchange: Exchange,
|
|||||||
logger.info(f"Start earlier than available data. Redownloading trades for {pair}...")
|
logger.info(f"Start earlier than available data. Redownloading trades for {pair}...")
|
||||||
trades = []
|
trades = []
|
||||||
|
|
||||||
if not since:
|
|
||||||
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
|
|
||||||
|
|
||||||
from_id = trades[-1][1] if trades else None
|
from_id = trades[-1][1] if trades else None
|
||||||
if trades and since < trades[-1][0]:
|
if trades and since < trades[-1][0]:
|
||||||
# Reset since to the last available point
|
# Reset since to the last available point
|
||||||
|
@@ -9,7 +9,7 @@ from abc import ABC, abstractmethod
|
|||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional, Tuple, Type
|
from typing import List, Optional, Type
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class IDataHandler(ABC):
|
class IDataHandler(ABC):
|
||||||
|
|
||||||
_OHLCV_REGEX = r'^([a-zA-Z_\d-]+)\-(\d+[a-zA-Z]{1,2})\-?([a-zA-Z_]*)?(?=\.)'
|
_OHLCV_REGEX = r'^([a-zA-Z_-]+)\-(\d+[a-zA-Z]{1,2})\-?([a-zA-Z_]*)?(?=\.)'
|
||||||
|
|
||||||
def __init__(self, datadir: Path) -> None:
|
def __init__(self, datadir: Path) -> None:
|
||||||
self._datadir = datadir
|
self._datadir = datadir
|
||||||
@@ -61,6 +61,7 @@ class IDataHandler(ABC):
|
|||||||
) for match in _tmp if match and len(match.groups()) > 1]
|
) for match in _tmp if match and len(match.groups()) > 1]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
@abstractmethod
|
||||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Returns a list of all pairs with ohlcv data available in this datadir
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
@@ -70,15 +71,6 @@ class IDataHandler(ABC):
|
|||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: List of Pairs
|
:return: List of Pairs
|
||||||
"""
|
"""
|
||||||
candle = ""
|
|
||||||
if candle_type != CandleType.SPOT:
|
|
||||||
datadir = datadir.joinpath('futures')
|
|
||||||
candle = f"-{candle_type}"
|
|
||||||
ext = cls._get_file_extension()
|
|
||||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + f'.{ext})', p.name)
|
|
||||||
for p in datadir.glob(f"*{timeframe}{candle}.{ext}")]
|
|
||||||
# Check if regex found something and only return these results
|
|
||||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def ohlcv_store(
|
def ohlcv_store(
|
||||||
@@ -92,23 +84,6 @@ class IDataHandler(ABC):
|
|||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def ohlcv_data_min_max(self, pair: str, timeframe: str,
|
|
||||||
candle_type: CandleType) -> Tuple[datetime, datetime]:
|
|
||||||
"""
|
|
||||||
Returns the min and max timestamp for the given pair and timeframe.
|
|
||||||
:param pair: Pair to get min/max for
|
|
||||||
:param timeframe: Timeframe to get min/max for
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
:return: (min, max)
|
|
||||||
"""
|
|
||||||
data = self._ohlcv_load(pair, timeframe, None, candle_type)
|
|
||||||
if data.empty:
|
|
||||||
return (
|
|
||||||
datetime.fromtimestamp(0, tz=timezone.utc),
|
|
||||||
datetime.fromtimestamp(0, tz=timezone.utc)
|
|
||||||
)
|
|
||||||
return data.iloc[0]['date'].to_pydatetime(), data.iloc[-1]['date'].to_pydatetime()
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange],
|
def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange],
|
||||||
candle_type: CandleType
|
candle_type: CandleType
|
||||||
@@ -157,17 +132,13 @@ class IDataHandler(ABC):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
@abstractmethod
|
||||||
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Returns a list of all pairs for which trade data is available in this
|
Returns a list of all pairs for which trade data is available in this
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
:return: List of Pairs
|
:return: List of Pairs
|
||||||
"""
|
"""
|
||||||
_ext = cls._get_file_extension()
|
|
||||||
_tmp = [re.search(r'^(\S+)(?=\-trades.' + _ext + ')', p.name)
|
|
||||||
for p in datadir.glob(f"*trades.{_ext}")]
|
|
||||||
# Check if regex found something and only return these results to avoid exceptions.
|
|
||||||
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||||
@@ -272,15 +243,15 @@ class IDataHandler(ABC):
|
|||||||
Rebuild pair name from filename
|
Rebuild pair name from filename
|
||||||
Assumes a asset name of max. 7 length to also support BTC-PERP and BTC-PERP:USD names.
|
Assumes a asset name of max. 7 length to also support BTC-PERP and BTC-PERP:USD names.
|
||||||
"""
|
"""
|
||||||
res = re.sub(r'^(([A-Za-z\d]{1,10})|^([A-Za-z\-]{1,6}))(_)', r'\g<1>/', pair, 1)
|
res = re.sub(r'^(([A-Za-z]{1,10})|^([A-Za-z\-]{1,6}))(_)', r'\g<1>/', pair, 1)
|
||||||
res = re.sub('_', ':', res, 1)
|
res = re.sub('_', ':', res, 1)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def ohlcv_load(self, pair, timeframe: str,
|
def ohlcv_load(self, pair, timeframe: str,
|
||||||
candle_type: CandleType, *,
|
candle_type: CandleType,
|
||||||
timerange: Optional[TimeRange] = None,
|
timerange: Optional[TimeRange] = None,
|
||||||
fill_missing: bool = True,
|
fill_missing: bool = True,
|
||||||
drop_incomplete: bool = False,
|
drop_incomplete: bool = True,
|
||||||
startup_candles: int = 0,
|
startup_candles: int = 0,
|
||||||
warn_no_data: bool = True,
|
warn_no_data: bool = True,
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
@@ -308,7 +279,7 @@ class IDataHandler(ABC):
|
|||||||
timerange=timerange_startup,
|
timerange=timerange_startup,
|
||||||
candle_type=candle_type
|
candle_type=candle_type
|
||||||
)
|
)
|
||||||
if self._check_empty_df(pairdf, pair, timeframe, candle_type, warn_no_data, True):
|
if self._check_empty_df(pairdf, pair, timeframe, candle_type, warn_no_data):
|
||||||
return pairdf
|
return pairdf
|
||||||
else:
|
else:
|
||||||
enddate = pairdf.iloc[-1]['date']
|
enddate = pairdf.iloc[-1]['date']
|
||||||
@@ -328,9 +299,8 @@ class IDataHandler(ABC):
|
|||||||
self._check_empty_df(pairdf, pair, timeframe, candle_type, warn_no_data)
|
self._check_empty_df(pairdf, pair, timeframe, candle_type, warn_no_data)
|
||||||
return pairdf
|
return pairdf
|
||||||
|
|
||||||
def _check_empty_df(
|
def _check_empty_df(self, pairdf: DataFrame, pair: str, timeframe: str,
|
||||||
self, pairdf: DataFrame, pair: str, timeframe: str, candle_type: CandleType,
|
candle_type: CandleType, warn_no_data: bool):
|
||||||
warn_no_data: bool, warn_price: bool = False) -> bool:
|
|
||||||
"""
|
"""
|
||||||
Warn on empty dataframe
|
Warn on empty dataframe
|
||||||
"""
|
"""
|
||||||
@@ -341,20 +311,6 @@ class IDataHandler(ABC):
|
|||||||
"Use `freqtrade download-data` to download the data"
|
"Use `freqtrade download-data` to download the data"
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
elif warn_price:
|
|
||||||
candle_price_gap = 0
|
|
||||||
if (candle_type in (CandleType.SPOT, CandleType.FUTURES) and
|
|
||||||
not pairdf.empty
|
|
||||||
and 'close' in pairdf.columns and 'open' in pairdf.columns):
|
|
||||||
# Detect gaps between prior close and open
|
|
||||||
gaps = ((pairdf['open'] - pairdf['close'].shift(1)) / pairdf['close'].shift(1))
|
|
||||||
gaps = gaps.dropna()
|
|
||||||
if len(gaps):
|
|
||||||
candle_price_gap = max(abs(gaps))
|
|
||||||
if candle_price_gap > 0.1:
|
|
||||||
logger.info(f"Price jump in {pair}, {timeframe}, {candle_type} between two candles "
|
|
||||||
f"of {candle_price_gap:.2%} detected.")
|
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _validate_pairdata(self, pair, pairdata: DataFrame, timeframe: str,
|
def _validate_pairdata(self, pair, pairdata: DataFrame, timeframe: str,
|
||||||
@@ -366,11 +322,13 @@ class IDataHandler(ABC):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
if pairdata.iloc[0]['date'] > timerange.startdt:
|
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||||
|
if pairdata.iloc[0]['date'] > start:
|
||||||
logger.warning(f"{pair}, {candle_type}, {timeframe}, "
|
logger.warning(f"{pair}, {candle_type}, {timeframe}, "
|
||||||
f"data starts at {pairdata.iloc[0]['date']:%Y-%m-%d %H:%M:%S}")
|
f"data starts at {pairdata.iloc[0]['date']:%Y-%m-%d %H:%M:%S}")
|
||||||
if timerange.stoptype == 'date':
|
if timerange.stoptype == 'date':
|
||||||
if pairdata.iloc[-1]['date'] < timerange.stopdt:
|
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||||
|
if pairdata.iloc[-1]['date'] < stop:
|
||||||
logger.warning(f"{pair}, {candle_type}, {timeframe}, "
|
logger.warning(f"{pair}, {candle_type}, {timeframe}, "
|
||||||
f"data ends at {pairdata.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}")
|
f"data ends at {pairdata.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}")
|
||||||
|
|
||||||
@@ -393,12 +351,6 @@ def get_datahandlerclass(datatype: str) -> Type[IDataHandler]:
|
|||||||
elif datatype == 'hdf5':
|
elif datatype == 'hdf5':
|
||||||
from .hdf5datahandler import HDF5DataHandler
|
from .hdf5datahandler import HDF5DataHandler
|
||||||
return HDF5DataHandler
|
return HDF5DataHandler
|
||||||
elif datatype == 'feather':
|
|
||||||
from .featherdatahandler import FeatherDataHandler
|
|
||||||
return FeatherDataHandler
|
|
||||||
elif datatype == 'parquet':
|
|
||||||
from .parquetdatahandler import ParquetDataHandler
|
|
||||||
return ParquetDataHandler
|
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"No datahandler for datatype {datatype} available.")
|
raise ValueError(f"No datahandler for datatype {datatype} available.")
|
||||||
|
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Optional
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from pandas import DataFrame, read_json, to_datetime
|
from pandas import DataFrame, read_json, to_datetime
|
||||||
@@ -21,6 +23,26 @@ class JsonDataHandler(IDataHandler):
|
|||||||
_use_zip = False
|
_use_zip = False
|
||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
|
for the specified timeframe
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:param timeframe: Timeframe to search pairs for
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
|
:return: List of Pairs
|
||||||
|
"""
|
||||||
|
candle = ""
|
||||||
|
if candle_type != CandleType.SPOT:
|
||||||
|
datadir = datadir.joinpath('futures')
|
||||||
|
candle = f"-{candle_type}"
|
||||||
|
|
||||||
|
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + '.json)', p.name)
|
||||||
|
for p in datadir.glob(f"*{timeframe}{candle}.{cls._get_file_extension()}")]
|
||||||
|
# Check if regex found something and only return these results
|
||||||
|
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||||
|
|
||||||
def ohlcv_store(
|
def ohlcv_store(
|
||||||
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -97,6 +119,18 @@ class JsonDataHandler(IDataHandler):
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs for which trade data is available in this
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:return: List of Pairs
|
||||||
|
"""
|
||||||
|
_tmp = [re.search(r'^(\S+)(?=\-trades.json)', p.name)
|
||||||
|
for p in datadir.glob(f"*trades.{cls._get_file_extension()}")]
|
||||||
|
# Check if regex found something and only return these results to avoid exceptions.
|
||||||
|
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||||
|
|
||||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||||
"""
|
"""
|
||||||
Store trades data (list of Dicts) to file
|
Store trades data (list of Dicts) to file
|
||||||
|
@@ -1,129 +0,0 @@
|
|||||||
import logging
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from pandas import DataFrame, read_parquet, to_datetime
|
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
|
||||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, TradeList
|
|
||||||
from freqtrade.enums import CandleType
|
|
||||||
|
|
||||||
from .idatahandler import IDataHandler
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class ParquetDataHandler(IDataHandler):
|
|
||||||
|
|
||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
|
||||||
|
|
||||||
def ohlcv_store(
|
|
||||||
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
|
||||||
"""
|
|
||||||
Store data in json format "values".
|
|
||||||
format looks as follows:
|
|
||||||
[[<date>,<open>,<high>,<low>,<close>]]
|
|
||||||
:param pair: Pair - used to generate filename
|
|
||||||
:param timeframe: Timeframe - used to generate filename
|
|
||||||
:param data: Dataframe containing OHLCV data
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
|
||||||
self.create_dir_if_needed(filename)
|
|
||||||
|
|
||||||
data.reset_index(drop=True).loc[:, self._columns].to_parquet(filename)
|
|
||||||
|
|
||||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
|
||||||
timerange: Optional[TimeRange], candle_type: CandleType
|
|
||||||
) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Internal method used to load data for one pair from disk.
|
|
||||||
Implements the loading and conversion to a Pandas dataframe.
|
|
||||||
Timerange trimming and dataframe validation happens outside of this method.
|
|
||||||
:param pair: Pair to load data
|
|
||||||
:param timeframe: Timeframe (e.g. "5m")
|
|
||||||
:param timerange: Limit data to be loaded to this timerange.
|
|
||||||
Optionally implemented by subclasses to avoid loading
|
|
||||||
all data where possible.
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
|
||||||
"""
|
|
||||||
filename = self._pair_data_filename(
|
|
||||||
self._datadir, pair, timeframe, candle_type=candle_type)
|
|
||||||
if not filename.exists():
|
|
||||||
# Fallback mode for 1M files
|
|
||||||
filename = self._pair_data_filename(
|
|
||||||
self._datadir, pair, timeframe, candle_type=candle_type, no_timeframe_modify=True)
|
|
||||||
if not filename.exists():
|
|
||||||
return DataFrame(columns=self._columns)
|
|
||||||
|
|
||||||
pairdata = read_parquet(filename)
|
|
||||||
pairdata.columns = self._columns
|
|
||||||
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
|
||||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
|
||||||
pairdata['date'] = to_datetime(pairdata['date'],
|
|
||||||
unit='ms',
|
|
||||||
utc=True,
|
|
||||||
infer_datetime_format=True)
|
|
||||||
return pairdata
|
|
||||||
|
|
||||||
def ohlcv_append(
|
|
||||||
self,
|
|
||||||
pair: str,
|
|
||||||
timeframe: str,
|
|
||||||
data: DataFrame,
|
|
||||||
candle_type: CandleType
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Append data to existing data structures
|
|
||||||
:param pair: Pair
|
|
||||||
:param timeframe: Timeframe this ohlcv data is for
|
|
||||||
:param data: Data to append.
|
|
||||||
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
|
||||||
"""
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
def trades_store(self, pair: str, data: TradeList) -> None:
|
|
||||||
"""
|
|
||||||
Store trades data (list of Dicts) to file
|
|
||||||
:param pair: Pair - used for filename
|
|
||||||
:param data: List of Lists containing trade data,
|
|
||||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
|
||||||
"""
|
|
||||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
|
||||||
|
|
||||||
raise NotImplementedError()
|
|
||||||
# array = pa.array(data)
|
|
||||||
# array
|
|
||||||
# feather.write_feather(data, filename)
|
|
||||||
|
|
||||||
def trades_append(self, pair: str, data: TradeList):
|
|
||||||
"""
|
|
||||||
Append data to existing files
|
|
||||||
:param pair: Pair - used for filename
|
|
||||||
:param data: List of Lists containing trade data,
|
|
||||||
column sequence as in DEFAULT_TRADES_COLUMNS
|
|
||||||
"""
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
def _trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> TradeList:
|
|
||||||
"""
|
|
||||||
Load a pair from file, either .json.gz or .json
|
|
||||||
# TODO: respect timerange ...
|
|
||||||
:param pair: Load trades for this pair
|
|
||||||
:param timerange: Timerange to load trades for - currently not implemented
|
|
||||||
:return: List of trades
|
|
||||||
"""
|
|
||||||
raise NotImplementedError()
|
|
||||||
# filename = self._pair_trades_filename(self._datadir, pair)
|
|
||||||
# tradesdata = misc.file_load_json(filename)
|
|
||||||
|
|
||||||
# if not tradesdata:
|
|
||||||
# return []
|
|
||||||
|
|
||||||
# return tradesdata
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _get_file_extension(cls):
|
|
||||||
return "parquet"
|
|
@@ -11,11 +11,11 @@ import utils_find_1st as utf1st
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT, Config
|
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.enums import CandleType, ExitType, RunMode
|
from freqtrade.enums import CandleType, ExitType, RunMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import timeframe_to_seconds
|
from freqtrade.exchange.exchange import timeframe_to_seconds
|
||||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||||
from freqtrade.strategy.interface import IStrategy
|
from freqtrade.strategy.interface import IStrategy
|
||||||
|
|
||||||
@@ -42,9 +42,10 @@ class Edge:
|
|||||||
Author: https://github.com/mishaker
|
Author: https://github.com/mishaker
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
config: Dict = {}
|
||||||
_cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
_cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||||
|
|
||||||
def __init__(self, config: Config, exchange, strategy) -> None:
|
def __init__(self, config: Dict[str, Any], exchange, strategy) -> None:
|
||||||
|
|
||||||
self.config = config
|
self.config = config
|
||||||
self.exchange = exchange
|
self.exchange = exchange
|
||||||
@@ -392,7 +393,7 @@ class Edge:
|
|||||||
# Returning a list of pairs in order of "expectancy"
|
# Returning a list of pairs in order of "expectancy"
|
||||||
return final
|
return final
|
||||||
|
|
||||||
def _find_trades_for_stoploss_range(self, df, pair: str, stoploss_range) -> list:
|
def _find_trades_for_stoploss_range(self, df, pair, stoploss_range):
|
||||||
buy_column = df['enter_long'].values
|
buy_column = df['enter_long'].values
|
||||||
sell_column = df['exit_long'].values
|
sell_column = df['exit_long'].values
|
||||||
date_column = df['date'].values
|
date_column = df['date'].values
|
||||||
@@ -407,7 +408,7 @@ class Edge:
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
||||||
ohlc_columns, stoploss, pair: str):
|
ohlc_columns, stoploss, pair):
|
||||||
"""
|
"""
|
||||||
Iterate through ohlc_columns in order to find the next trade
|
Iterate through ohlc_columns in order to find the next trade
|
||||||
Next trade opens from the first buy signal noticed to
|
Next trade opens from the first buy signal noticed to
|
||||||
|
@@ -3,10 +3,9 @@ from freqtrade.enums.backteststate import BacktestState
|
|||||||
from freqtrade.enums.candletype import CandleType
|
from freqtrade.enums.candletype import CandleType
|
||||||
from freqtrade.enums.exitchecktuple import ExitCheckTuple
|
from freqtrade.enums.exitchecktuple import ExitCheckTuple
|
||||||
from freqtrade.enums.exittype import ExitType
|
from freqtrade.enums.exittype import ExitType
|
||||||
from freqtrade.enums.hyperoptstate import HyperoptState
|
|
||||||
from freqtrade.enums.marginmode import MarginMode
|
from freqtrade.enums.marginmode import MarginMode
|
||||||
from freqtrade.enums.ordertypevalue import OrderTypeValues
|
from freqtrade.enums.ordertypevalue import OrderTypeValues
|
||||||
from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType
|
from freqtrade.enums.rpcmessagetype import RPCMessageType
|
||||||
from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode
|
from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode
|
||||||
from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType
|
from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType
|
||||||
from freqtrade.enums.state import State
|
from freqtrade.enums.state import State
|
||||||
|
@@ -1,12 +0,0 @@
|
|||||||
from enum import Enum
|
|
||||||
|
|
||||||
|
|
||||||
class HyperoptState(Enum):
|
|
||||||
""" Hyperopt states """
|
|
||||||
STARTUP = 1
|
|
||||||
DATALOAD = 2
|
|
||||||
INDICATORS = 3
|
|
||||||
OPTIMIZE = 4
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return f"{self.name.lower()}"
|
|
@@ -1,7 +1,7 @@
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
class RPCMessageType(str, Enum):
|
class RPCMessageType(Enum):
|
||||||
STATUS = 'status'
|
STATUS = 'status'
|
||||||
WARNING = 'warning'
|
WARNING = 'warning'
|
||||||
STARTUP = 'startup'
|
STARTUP = 'startup'
|
||||||
@@ -19,19 +19,8 @@ class RPCMessageType(str, Enum):
|
|||||||
|
|
||||||
STRATEGY_MSG = 'strategy_msg'
|
STRATEGY_MSG = 'strategy_msg'
|
||||||
|
|
||||||
WHITELIST = 'whitelist'
|
|
||||||
ANALYZED_DF = 'analyzed_df'
|
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return self.value
|
return self.value
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.value
|
return self.value
|
||||||
|
|
||||||
|
|
||||||
# Enum for parsing requests from ws consumers
|
|
||||||
class RPCRequestType(str, Enum):
|
|
||||||
SUBSCRIBE = 'subscribe'
|
|
||||||
|
|
||||||
WHITELIST = 'whitelist'
|
|
||||||
ANALYZED_DF = 'analyzed_df'
|
|
||||||
|
@@ -9,15 +9,14 @@ from freqtrade.exchange.bitpanda import Bitpanda
|
|||||||
from freqtrade.exchange.bittrex import Bittrex
|
from freqtrade.exchange.bittrex import Bittrex
|
||||||
from freqtrade.exchange.bybit import Bybit
|
from freqtrade.exchange.bybit import Bybit
|
||||||
from freqtrade.exchange.coinbasepro import Coinbasepro
|
from freqtrade.exchange.coinbasepro import Coinbasepro
|
||||||
from freqtrade.exchange.exchange_utils import (amount_to_contract_precision, amount_to_contracts,
|
from freqtrade.exchange.exchange import (amount_to_precision, available_exchanges, ccxt_exchanges,
|
||||||
amount_to_precision, available_exchanges,
|
date_minus_candles, is_exchange_known_ccxt,
|
||||||
ccxt_exchanges, contracts_to_amount,
|
is_exchange_officially_supported, market_is_active,
|
||||||
date_minus_candles, is_exchange_known_ccxt,
|
price_to_precision, timeframe_to_minutes,
|
||||||
market_is_active, price_to_precision,
|
timeframe_to_msecs, timeframe_to_next_date,
|
||||||
timeframe_to_minutes, timeframe_to_msecs,
|
timeframe_to_prev_date, timeframe_to_seconds,
|
||||||
timeframe_to_next_date, timeframe_to_prev_date,
|
validate_exchange, validate_exchanges)
|
||||||
timeframe_to_seconds, validate_exchange,
|
from freqtrade.exchange.ftx import Ftx
|
||||||
validate_exchanges)
|
|
||||||
from freqtrade.exchange.gateio import Gateio
|
from freqtrade.exchange.gateio import Gateio
|
||||||
from freqtrade.exchange.hitbtc import Hitbtc
|
from freqtrade.exchange.hitbtc import Hitbtc
|
||||||
from freqtrade.exchange.huobi import Huobi
|
from freqtrade.exchange.huobi import Huobi
|
||||||
|
@@ -1,4 +1,5 @@
|
|||||||
""" Binance exchange subclass """
|
""" Binance exchange subclass """
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -11,8 +12,7 @@ from freqtrade.enums import CandleType, MarginMode, TradingMode
|
|||||||
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.exchange.common import retrier
|
from freqtrade.exchange.common import retrier
|
||||||
from freqtrade.exchange.types import Tickers
|
from freqtrade.misc import deep_merge_dicts
|
||||||
from freqtrade.misc import deep_merge_dicts, json_load
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -23,7 +23,8 @@ class Binance(Exchange):
|
|||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
"stoploss_order_types": {"limit": "stop_loss_limit"},
|
"stoploss_order_types": {"limit": "stop_loss_limit"},
|
||||||
"order_time_in_force": ['GTC', 'FOK', 'IOC'],
|
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||||
|
"time_in_force_parameter": "timeInForce",
|
||||||
"ohlcv_candle_limit": 1000,
|
"ohlcv_candle_limit": 1000,
|
||||||
"trades_pagination": "id",
|
"trades_pagination": "id",
|
||||||
"trades_pagination_arg": "fromId",
|
"trades_pagination_arg": "fromId",
|
||||||
@@ -31,7 +32,7 @@ class Binance(Exchange):
|
|||||||
"ccxt_futures_name": "future"
|
"ccxt_futures_name": "future"
|
||||||
}
|
}
|
||||||
_ft_has_futures: Dict = {
|
_ft_has_futures: Dict = {
|
||||||
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
"stoploss_order_types": {"limit": "stop"},
|
||||||
"tickers_have_price": False,
|
"tickers_have_price": False,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +43,26 @@ class Binance(Exchange):
|
|||||||
(TradingMode.FUTURES, MarginMode.ISOLATED)
|
(TradingMode.FUTURES, MarginMode.ISOLATED)
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Tickers:
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
|
"""
|
||||||
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
|
Returns True if adjustment is necessary.
|
||||||
|
:param side: "buy" or "sell"
|
||||||
|
"""
|
||||||
|
|
||||||
|
ordertype = 'stop' if self.trading_mode == TradingMode.FUTURES else 'stop_loss_limit'
|
||||||
|
|
||||||
|
return (
|
||||||
|
order.get('stopPrice', None) is None
|
||||||
|
or (
|
||||||
|
order['type'] == ordertype
|
||||||
|
and (
|
||||||
|
(side == "sell" and stop_loss > float(order['stopPrice'])) or
|
||||||
|
(side == "buy" and stop_loss < float(order['stopPrice']))
|
||||||
|
)
|
||||||
|
))
|
||||||
|
|
||||||
|
def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Dict:
|
||||||
tickers = super().get_tickers(symbols=symbols, cached=cached)
|
tickers = super().get_tickers(symbols=symbols, cached=cached)
|
||||||
if self.trading_mode == TradingMode.FUTURES:
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
# Binance's future result has no bid/ask values.
|
# Binance's future result has no bid/ask values.
|
||||||
@@ -51,37 +71,6 @@ class Binance(Exchange):
|
|||||||
tickers = deep_merge_dicts(bidsasks, tickers, allow_null_overrides=False)
|
tickers = deep_merge_dicts(bidsasks, tickers, allow_null_overrides=False)
|
||||||
return tickers
|
return tickers
|
||||||
|
|
||||||
@retrier
|
|
||||||
def additional_exchange_init(self) -> None:
|
|
||||||
"""
|
|
||||||
Additional exchange initialization logic.
|
|
||||||
.api will be available at this point.
|
|
||||||
Must be overridden in child methods if required.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
if self.trading_mode == TradingMode.FUTURES and not self._config['dry_run']:
|
|
||||||
position_side = self._api.fapiPrivateGetPositionsideDual()
|
|
||||||
self._log_exchange_response('position_side_setting', position_side)
|
|
||||||
assets_margin = self._api.fapiPrivateGetMultiAssetsMargin()
|
|
||||||
self._log_exchange_response('multi_asset_margin', assets_margin)
|
|
||||||
msg = ""
|
|
||||||
if position_side.get('dualSidePosition') is True:
|
|
||||||
msg += (
|
|
||||||
"\nHedge Mode is not supported by freqtrade. "
|
|
||||||
"Please change 'Position Mode' on your binance futures account.")
|
|
||||||
if assets_margin.get('multiAssetsMargin') is True:
|
|
||||||
msg += ("\nMulti-Asset Mode is not supported by freqtrade. "
|
|
||||||
"Please change 'Asset Mode' on your binance futures account.")
|
|
||||||
if msg:
|
|
||||||
raise OperationalException(msg)
|
|
||||||
except ccxt.DDoSProtection as e:
|
|
||||||
raise DDosProtection(e) from e
|
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
||||||
raise TemporaryError(
|
|
||||||
f'Could not set leverage due to {e.__class__.__name__}. Message: {e}') from e
|
|
||||||
except ccxt.BaseError as e:
|
|
||||||
raise OperationalException(e) from e
|
|
||||||
|
|
||||||
@retrier
|
@retrier
|
||||||
def _set_leverage(
|
def _set_leverage(
|
||||||
self,
|
self,
|
||||||
@@ -148,27 +137,23 @@ class Binance(Exchange):
|
|||||||
pair: str,
|
pair: str,
|
||||||
open_rate: float, # Entry price of position
|
open_rate: float, # Entry price of position
|
||||||
is_short: bool,
|
is_short: bool,
|
||||||
amount: float,
|
position: float, # Absolute value of position size
|
||||||
stake_amount: float,
|
|
||||||
wallet_balance: float, # Or margin balance
|
wallet_balance: float, # Or margin balance
|
||||||
mm_ex_1: float = 0.0, # (Binance) Cross only
|
mm_ex_1: float = 0.0, # (Binance) Cross only
|
||||||
upnl_ex_1: float = 0.0, # (Binance) Cross only
|
upnl_ex_1: float = 0.0, # (Binance) Cross only
|
||||||
) -> Optional[float]:
|
) -> Optional[float]:
|
||||||
"""
|
"""
|
||||||
Important: Must be fetching data from cached values as this is used by backtesting!
|
|
||||||
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
|
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
|
||||||
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
|
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
|
||||||
|
|
||||||
:param exchange_name:
|
:param exchange_name:
|
||||||
:param open_rate: Entry price of position
|
:param open_rate: (EP1) Entry price of position
|
||||||
:param is_short: True if the trade is a short, false otherwise
|
:param is_short: True if the trade is a short, false otherwise
|
||||||
:param amount: Absolute value of position size incl. leverage (in base currency)
|
:param position: Absolute value of position size (in base currency)
|
||||||
:param stake_amount: Stake amount - Collateral in settle currency.
|
:param wallet_balance: (WB)
|
||||||
:param trading_mode: SPOT, MARGIN, FUTURES, etc.
|
|
||||||
:param margin_mode: Either ISOLATED or CROSS
|
|
||||||
:param wallet_balance: Amount of margin_mode in the wallet being used to trade
|
|
||||||
Cross-Margin Mode: crossWalletBalance
|
Cross-Margin Mode: crossWalletBalance
|
||||||
Isolated-Margin Mode: isolatedWalletBalance
|
Isolated-Margin Mode: isolatedWalletBalance
|
||||||
|
:param maintenance_amt:
|
||||||
|
|
||||||
# * Only required for Cross
|
# * Only required for Cross
|
||||||
:param mm_ex_1: (TMM)
|
:param mm_ex_1: (TMM)
|
||||||
@@ -180,11 +165,12 @@ class Binance(Exchange):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
side_1 = -1 if is_short else 1
|
side_1 = -1 if is_short else 1
|
||||||
|
position = abs(position)
|
||||||
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
|
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
|
||||||
|
|
||||||
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
|
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
|
||||||
# maintenance_amt: (CUM) Maintenance Amount of position
|
# maintenance_amt: (CUM) Maintenance Amount of position
|
||||||
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, stake_amount)
|
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, position)
|
||||||
|
|
||||||
if (maintenance_amt is None):
|
if (maintenance_amt is None):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
@@ -196,9 +182,9 @@ class Binance(Exchange):
|
|||||||
return (
|
return (
|
||||||
(
|
(
|
||||||
(wallet_balance + cross_vars + maintenance_amt) -
|
(wallet_balance + cross_vars + maintenance_amt) -
|
||||||
(side_1 * amount * open_rate)
|
(side_1 * position * open_rate)
|
||||||
) / (
|
) / (
|
||||||
(amount * mm_ratio) - (side_1 * amount)
|
(position * mm_ratio) - (side_1 * position)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -213,7 +199,7 @@ class Binance(Exchange):
|
|||||||
Path(__file__).parent / 'binance_leverage_tiers.json'
|
Path(__file__).parent / 'binance_leverage_tiers.json'
|
||||||
)
|
)
|
||||||
with open(leverage_tiers_path) as json_file:
|
with open(leverage_tiers_path) as json_file:
|
||||||
return json_load(json_file)
|
return json.load(json_file)
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
return self._api.fetch_leverage_tiers()
|
return self._api.fetch_leverage_tiers()
|
||||||
|