commit
dfbd1c34c4
1
.github/ISSUE_TEMPLATE/feature_request.md
vendored
1
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -24,4 +24,3 @@ Have you search for this feature before requesting it? It's highly likely that a
|
|||||||
## Describe the enhancement
|
## Describe the enhancement
|
||||||
|
|
||||||
*Explain the enhancement you would like*
|
*Explain the enhancement you would like*
|
||||||
|
|
||||||
|
8
.github/PULL_REQUEST_TEMPLATE.md
vendored
8
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -1,9 +1,9 @@
|
|||||||
Thank you for sending your pull request. But first, have you included
|
<!-- Thank you for sending your pull request. But first, have you included
|
||||||
unit tests, and is your code PEP8 conformant? [More details](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
unit tests, and is your code PEP8 conformant? [More details](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||||
|
-->
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
Explain in one sentence the goal of this PR
|
<!-- Explain in one sentence the goal of this PR -->
|
||||||
|
|
||||||
Solve the issue: #___
|
Solve the issue: #___
|
||||||
|
|
||||||
@ -14,4 +14,4 @@ Solve the issue: #___
|
|||||||
|
|
||||||
## What's new?
|
## What's new?
|
||||||
|
|
||||||
*Explain in details what this PR solve or improve. You can include visuals.*
|
<!-- Explain in details what this PR solve or improve. You can include visuals. -->
|
||||||
|
50
.github/workflows/ci.yml
vendored
50
.github/workflows/ci.yml
vendored
@ -31,14 +31,14 @@ jobs:
|
|||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
- name: Cache_dependencies
|
- name: Cache_dependencies
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
id: cache
|
id: cache
|
||||||
with:
|
with:
|
||||||
path: ~/dependencies/
|
path: ~/dependencies/
|
||||||
key: ${{ runner.os }}-dependencies
|
key: ${{ runner.os }}-dependencies
|
||||||
|
|
||||||
- name: pip cache (linux)
|
- name: pip cache (linux)
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
if: runner.os == 'Linux'
|
if: runner.os == 'Linux'
|
||||||
with:
|
with:
|
||||||
path: ~/.cache/pip
|
path: ~/.cache/pip
|
||||||
@ -100,7 +100,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Mypy
|
- name: Mypy
|
||||||
run: |
|
run: |
|
||||||
mypy freqtrade scripts
|
mypy freqtrade scripts tests
|
||||||
|
|
||||||
- name: Discord notification
|
- name: Discord notification
|
||||||
uses: rjstone/discord-webhook-notify@v1
|
uses: rjstone/discord-webhook-notify@v1
|
||||||
@ -126,14 +126,14 @@ jobs:
|
|||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
- name: Cache_dependencies
|
- name: Cache_dependencies
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
id: cache
|
id: cache
|
||||||
with:
|
with:
|
||||||
path: ~/dependencies/
|
path: ~/dependencies/
|
||||||
key: ${{ runner.os }}-dependencies
|
key: ${{ runner.os }}-dependencies
|
||||||
|
|
||||||
- name: pip cache (macOS)
|
- name: pip cache (macOS)
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
if: runner.os == 'macOS'
|
if: runner.os == 'macOS'
|
||||||
with:
|
with:
|
||||||
path: ~/Library/Caches/pip
|
path: ~/Library/Caches/pip
|
||||||
@ -157,6 +157,12 @@ jobs:
|
|||||||
pip install -e .
|
pip install -e .
|
||||||
|
|
||||||
- name: Tests
|
- name: Tests
|
||||||
|
if: (runner.os != 'Linux' || matrix.python-version != '3.8')
|
||||||
|
run: |
|
||||||
|
pytest --random-order
|
||||||
|
|
||||||
|
- name: Tests (with cov)
|
||||||
|
if: (runner.os == 'Linux' && matrix.python-version == '3.8')
|
||||||
run: |
|
run: |
|
||||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
|
||||||
@ -218,7 +224,7 @@ jobs:
|
|||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
- name: Pip cache (Windows)
|
- name: Pip cache (Windows)
|
||||||
uses: actions/cache@preview
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~\AppData\Local\pip\Cache
|
path: ~\AppData\Local\pip\Cache
|
||||||
key: ${{ matrix.os }}-${{ matrix.python-version }}-pip
|
key: ${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
@ -229,7 +235,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: |
|
run: |
|
||||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
pytest --random-order
|
||||||
|
|
||||||
- name: Backtesting
|
- name: Backtesting
|
||||||
run: |
|
run: |
|
||||||
@ -249,7 +255,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Mypy
|
- name: Mypy
|
||||||
run: |
|
run: |
|
||||||
mypy freqtrade scripts
|
mypy freqtrade scripts tests
|
||||||
|
|
||||||
- name: Discord notification
|
- name: Discord notification
|
||||||
uses: rjstone/discord-webhook-notify@v1
|
uses: rjstone/discord-webhook-notify@v1
|
||||||
@ -259,6 +265,21 @@ jobs:
|
|||||||
details: Test Failed
|
details: Test Failed
|
||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
|
mypy_version_check:
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v3
|
||||||
|
with:
|
||||||
|
python-version: 3.9
|
||||||
|
|
||||||
|
- name: pre-commit dependencies
|
||||||
|
run: |
|
||||||
|
pip install pyaml
|
||||||
|
python build_helpers/pre_commit_update.py
|
||||||
|
|
||||||
docs_check:
|
docs_check:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
@ -271,7 +292,7 @@ jobs:
|
|||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v3
|
uses: actions/setup-python@v3
|
||||||
with:
|
with:
|
||||||
python-version: 3.8
|
python-version: 3.9
|
||||||
|
|
||||||
- name: Documentation build
|
- name: Documentation build
|
||||||
run: |
|
run: |
|
||||||
@ -288,6 +309,9 @@ jobs:
|
|||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
cleanup-prior-runs:
|
cleanup-prior-runs:
|
||||||
|
permissions:
|
||||||
|
actions: write # for rokroskar/workflow-run-cleanup-action to obtain workflow name & cancel it
|
||||||
|
contents: read # for rokroskar/workflow-run-cleanup-action to obtain branch
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Cleanup previous runs on this branch
|
- name: Cleanup previous runs on this branch
|
||||||
@ -298,8 +322,12 @@ 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 ]
|
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check ]
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
|
# Discord notification can't handle schedule events
|
||||||
|
if: (github.event_name != 'schedule')
|
||||||
|
permissions:
|
||||||
|
repository-projects: read
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
- name: Check user permission
|
- name: Check user permission
|
||||||
@ -319,7 +347,7 @@ jobs:
|
|||||||
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
|
|
||||||
deploy:
|
deploy:
|
||||||
needs: [ build_linux, build_macos, build_windows, docs_check ]
|
needs: [ build_linux, build_macos, build_windows, docs_check, mypy_version_check ]
|
||||||
runs-on: ubuntu-20.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'
|
||||||
|
3
.github/workflows/docker_update_readme.yml
vendored
3
.github/workflows/docker_update_readme.yml
vendored
@ -10,9 +10,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Docker Hub Description
|
- name: Docker Hub Description
|
||||||
uses: peter-evans/dockerhub-description@v2.4.3
|
uses: peter-evans/dockerhub-description@v3
|
||||||
env:
|
env:
|
||||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
DOCKERHUB_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
DOCKERHUB_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
DOCKERHUB_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
DOCKERHUB_REPOSITORY: freqtradeorg/freqtrade
|
DOCKERHUB_REPOSITORY: freqtradeorg/freqtrade
|
||||||
|
|
||||||
|
46
.pre-commit-config.yaml
Normal file
46
.pre-commit-config.yaml
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
# See https://pre-commit.com for more information
|
||||||
|
# See https://pre-commit.com/hooks.html for more hooks
|
||||||
|
repos:
|
||||||
|
- repo: https://github.com/pycqa/flake8
|
||||||
|
rev: "4.0.1"
|
||||||
|
hooks:
|
||||||
|
- id: flake8
|
||||||
|
# stages: [push]
|
||||||
|
|
||||||
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
|
rev: "v0.942"
|
||||||
|
hooks:
|
||||||
|
- id: mypy
|
||||||
|
exclude: build_helpers
|
||||||
|
additional_dependencies:
|
||||||
|
- types-cachetools==5.0.1
|
||||||
|
- types-filelock==3.2.5
|
||||||
|
- types-requests==2.27.20
|
||||||
|
- types-tabulate==0.8.7
|
||||||
|
- types-python-dateutil==2.8.12
|
||||||
|
# stages: [push]
|
||||||
|
|
||||||
|
- repo: https://github.com/pycqa/isort
|
||||||
|
rev: "5.10.1"
|
||||||
|
hooks:
|
||||||
|
- id: isort
|
||||||
|
name: isort (python)
|
||||||
|
# stages: [push]
|
||||||
|
|
||||||
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
rev: v2.4.0
|
||||||
|
hooks:
|
||||||
|
- id: end-of-file-fixer
|
||||||
|
exclude: |
|
||||||
|
(?x)^(
|
||||||
|
tests/.*|
|
||||||
|
.*\.svg
|
||||||
|
)$
|
||||||
|
- id: mixed-line-ending
|
||||||
|
- id: debug-statements
|
||||||
|
- id: check-ast
|
||||||
|
- id: trailing-whitespace
|
||||||
|
exclude: |
|
||||||
|
(?x)^(
|
||||||
|
.*\.md
|
||||||
|
)$
|
@ -7,4 +7,3 @@ ignore=vendor
|
|||||||
|
|
||||||
[TYPECHECK]
|
[TYPECHECK]
|
||||||
ignored-modules=numpy,talib,talib.abstract
|
ignored-modules=numpy,talib,talib.abstract
|
||||||
|
|
||||||
|
@ -2,5 +2,6 @@ include LICENSE
|
|||||||
include README.md
|
include README.md
|
||||||
recursive-include freqtrade *.py
|
recursive-include freqtrade *.py
|
||||||
recursive-include freqtrade/templates/ *.j2 *.ipynb
|
recursive-include freqtrade/templates/ *.j2 *.ipynb
|
||||||
|
include freqtrade/exchange/binance_leverage_tiers.json
|
||||||
include freqtrade/rpc/api_server/ui/fallback_file.html
|
include freqtrade/rpc/api_server/ui/fallback_file.html
|
||||||
include freqtrade/rpc/api_server/ui/favicon.ico
|
include freqtrade/rpc/api_server/ui/favicon.ico
|
||||||
|
11
README.md
11
README.md
@ -39,6 +39,14 @@ Please read the [exchange specific notes](docs/exchanges.md) to learn about even
|
|||||||
- [X] [OKX](https://okx.com/) (Former OKEX)
|
- [X] [OKX](https://okx.com/) (Former OKEX)
|
||||||
- [ ] [potentially many others](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
|
- [ ] [potentially many others](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
|
||||||
|
|
||||||
|
### Experimentally, freqtrade also supports futures on the following exchanges
|
||||||
|
|
||||||
|
- [X] [Binance](https://www.binance.com/)
|
||||||
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
|
- [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.
|
||||||
|
|
||||||
### Community tested
|
### Community tested
|
||||||
|
|
||||||
Exchanges confirmed working by the community:
|
Exchanges confirmed working by the community:
|
||||||
@ -128,7 +136,8 @@ Telegram is not mandatory. However, this is a great way to control your bot. Mor
|
|||||||
- `/stopbuy`: 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.
|
||||||
- `/forcesell <trade_id>|all`: Instantly sells the given trade (Ignoring `minimum_roi`).
|
- `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`).
|
||||||
|
- `/fx <trade_id>|all`: Alias to `/forceexit`
|
||||||
- `/performance`: Show performance of each finished trade grouped by pair
|
- `/performance`: Show performance of each finished trade grouped by pair
|
||||||
- `/balance`: Show account balance per currency.
|
- `/balance`: Show account balance per currency.
|
||||||
- `/daily <n>`: Shows profit or loss per day, over the last n days.
|
- `/daily <n>`: Shows profit or loss per day, over the last n days.
|
||||||
|
42
build_helpers/pre_commit_update.py
Normal file
42
build_helpers/pre_commit_update.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
# File used in CI to ensure pre-commit dependencies are kept uptodate.
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
|
||||||
|
pre_commit_file = Path('.pre-commit-config.yaml')
|
||||||
|
require_dev = Path('requirements-dev.txt')
|
||||||
|
|
||||||
|
with require_dev.open('r') as rfile:
|
||||||
|
requirements = rfile.readlines()
|
||||||
|
|
||||||
|
# Extract types only
|
||||||
|
type_reqs = [r.strip('\n') for r in requirements if r.startswith('types-')]
|
||||||
|
|
||||||
|
with pre_commit_file.open('r') as file:
|
||||||
|
f = yaml.load(file, Loader=yaml.FullLoader)
|
||||||
|
|
||||||
|
|
||||||
|
mypy_repo = [repo for repo in f['repos'] if repo['repo']
|
||||||
|
== 'https://github.com/pre-commit/mirrors-mypy']
|
||||||
|
|
||||||
|
hooks = mypy_repo[0]['hooks'][0]['additional_dependencies']
|
||||||
|
|
||||||
|
errors = []
|
||||||
|
for hook in hooks:
|
||||||
|
if hook not in type_reqs:
|
||||||
|
errors.append(f"{hook} is missing in requirements-dev.txt.")
|
||||||
|
|
||||||
|
for req in type_reqs:
|
||||||
|
if req not in hooks:
|
||||||
|
errors.append(f"{req} is missing in pre-config file.")
|
||||||
|
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
for e in errors:
|
||||||
|
print(e)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
sys.exit(0)
|
@ -42,7 +42,7 @@ docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_I
|
|||||||
docker tag freqtrade:$TAG_PLOT_ARM ${CACHE_IMAGE}:$TAG_PLOT_ARM
|
docker tag freqtrade:$TAG_PLOT_ARM ${CACHE_IMAGE}:$TAG_PLOT_ARM
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV2
|
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
|
@ -53,7 +53,7 @@ docker build --cache-from freqtrade:${TAG} --build-arg sourceimage=${CACHE_IMAGE
|
|||||||
docker tag freqtrade:$TAG_PLOT ${CACHE_IMAGE}:$TAG_PLOT
|
docker tag freqtrade:$TAG_PLOT ${CACHE_IMAGE}:$TAG_PLOT
|
||||||
|
|
||||||
# Run backtest
|
# Run backtest
|
||||||
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV2
|
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed running backtest"
|
echo "failed running backtest"
|
||||||
|
@ -8,21 +8,23 @@
|
|||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"entry": 10,
|
||||||
"sell": 10,
|
"exit": 10,
|
||||||
"exit_timeout_count": 0,
|
"exit_timeout_count": 0,
|
||||||
"unit": "minutes"
|
"unit": "minutes"
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
"ask_last_balance": 0.0,
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"bids_to_ask_delta": 1
|
"bids_to_ask_delta": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ask_strategy": {
|
"exit_pricing": {
|
||||||
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1
|
"order_book_top": 1
|
||||||
},
|
},
|
||||||
@ -88,7 +90,7 @@
|
|||||||
},
|
},
|
||||||
"bot_name": "freqtrade",
|
"bot_name": "freqtrade",
|
||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"force_entry_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5
|
||||||
}
|
}
|
||||||
|
@ -8,21 +8,23 @@
|
|||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"entry": 10,
|
||||||
"sell": 10,
|
"exit": 10,
|
||||||
"exit_timeout_count": 0,
|
"exit_timeout_count": 0,
|
||||||
"unit": "minutes"
|
"unit": "minutes"
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"ask_last_balance": 0.0,
|
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"bids_to_ask_delta": 1
|
"bids_to_ask_delta": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ask_strategy":{
|
"exit_pricing":{
|
||||||
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1
|
"order_book_top": 1
|
||||||
},
|
},
|
||||||
@ -85,7 +87,7 @@
|
|||||||
},
|
},
|
||||||
"bot_name": "freqtrade",
|
"bot_name": "freqtrade",
|
||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"force_entry_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5
|
||||||
}
|
}
|
||||||
|
@ -8,21 +8,23 @@
|
|||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"entry": 10,
|
||||||
"sell": 10,
|
"exit": 10,
|
||||||
"exit_timeout_count": 0,
|
"exit_timeout_count": 0,
|
||||||
"unit": "minutes"
|
"unit": "minutes"
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
"ask_last_balance": 0.0,
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"bids_to_ask_delta": 1
|
"bids_to_ask_delta": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ask_strategy": {
|
"exit_pricing": {
|
||||||
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1
|
"order_book_top": 1
|
||||||
},
|
},
|
||||||
@ -87,7 +89,7 @@
|
|||||||
},
|
},
|
||||||
"bot_name": "freqtrade",
|
"bot_name": "freqtrade",
|
||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"force_entry_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,13 @@
|
|||||||
"trailing_stop_positive": 0.005,
|
"trailing_stop_positive": 0.005,
|
||||||
"trailing_stop_positive_offset": 0.0051,
|
"trailing_stop_positive_offset": 0.0051,
|
||||||
"trailing_only_offset_is_reached": false,
|
"trailing_only_offset_is_reached": false,
|
||||||
"use_sell_signal": true,
|
"use_exit_signal": true,
|
||||||
"sell_profit_only": false,
|
"exit_profit_only": false,
|
||||||
"sell_profit_offset": 0.0,
|
"exit_profit_offset": 0.0,
|
||||||
"ignore_roi_if_buy_signal": false,
|
"ignore_roi_if_entry_signal": false,
|
||||||
"ignore_buying_expired_candle_after": 300,
|
"ignore_buying_expired_candle_after": 300,
|
||||||
|
"trading_mode": "spot",
|
||||||
|
"margin_mode": "",
|
||||||
"minimal_roi": {
|
"minimal_roi": {
|
||||||
"40": 0.0,
|
"40": 0.0,
|
||||||
"30": 0.01,
|
"30": 0.01,
|
||||||
@ -28,40 +30,41 @@
|
|||||||
},
|
},
|
||||||
"stoploss": -0.10,
|
"stoploss": -0.10,
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"entry": 10,
|
||||||
"sell": 10,
|
"exit": 10,
|
||||||
"exit_timeout_count": 0,
|
"exit_timeout_count": 0,
|
||||||
"unit": "minutes"
|
"unit": "minutes"
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
"price_side": "bid",
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"ask_last_balance": 0.0,
|
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"bids_to_ask_delta": 1
|
"bids_to_ask_delta": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ask_strategy":{
|
"exit_pricing":{
|
||||||
"price_side": "ask",
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0
|
||||||
},
|
},
|
||||||
"order_types": {
|
"order_types": {
|
||||||
"buy": "limit",
|
"entry": "limit",
|
||||||
"sell": "limit",
|
"exit": "limit",
|
||||||
"emergencysell": "market",
|
"emergency_exit": "market",
|
||||||
"forcesell": "market",
|
"force_exit": "market",
|
||||||
"forcebuy": "market",
|
"force_entry": "market",
|
||||||
"stoploss": "market",
|
"stoploss": "market",
|
||||||
"stoploss_on_exchange": false,
|
"stoploss_on_exchange": false,
|
||||||
"stoploss_on_exchange_interval": 60,
|
"stoploss_on_exchange_interval": 60,
|
||||||
"stoploss_on_exchange_limit_ratio": 0.99
|
"stoploss_on_exchange_limit_ratio": 0.99
|
||||||
},
|
},
|
||||||
"order_time_in_force": {
|
"order_time_in_force": {
|
||||||
"buy": "gtc",
|
"entry": "gtc",
|
||||||
"sell": "gtc"
|
"exit": "gtc"
|
||||||
},
|
},
|
||||||
"pairlists": [
|
"pairlists": [
|
||||||
{"method": "StaticPairList"},
|
{"method": "StaticPairList"},
|
||||||
@ -136,21 +139,21 @@
|
|||||||
"status": "on",
|
"status": "on",
|
||||||
"warning": "on",
|
"warning": "on",
|
||||||
"startup": "on",
|
"startup": "on",
|
||||||
"buy": "on",
|
"entry": "on",
|
||||||
"buy_fill": "on",
|
"entry_fill": "on",
|
||||||
"sell": {
|
"exit": {
|
||||||
"roi": "off",
|
"roi": "off",
|
||||||
"emergency_sell": "off",
|
"emergency_exit": "off",
|
||||||
"force_sell": "off",
|
"force_exit": "off",
|
||||||
"sell_signal": "off",
|
"exit_signal": "off",
|
||||||
"trailing_stop_loss": "off",
|
"trailing_stop_loss": "off",
|
||||||
"stop_loss": "off",
|
"stop_loss": "off",
|
||||||
"stoploss_on_exchange": "off",
|
"stoploss_on_exchange": "off",
|
||||||
"custom_sell": "off"
|
"custom_exit": "off"
|
||||||
},
|
},
|
||||||
"sell_fill": "on",
|
"exit_fill": "on",
|
||||||
"buy_cancel": "on",
|
"entry_cancel": "on",
|
||||||
"sell_cancel": "on",
|
"exit_cancel": "on",
|
||||||
"protection_trigger": "off",
|
"protection_trigger": "off",
|
||||||
"protection_trigger_global": "on"
|
"protection_trigger_global": "on"
|
||||||
},
|
},
|
||||||
@ -171,7 +174,7 @@
|
|||||||
"bot_name": "freqtrade",
|
"bot_name": "freqtrade",
|
||||||
"db_url": "sqlite:///tradesv3.sqlite",
|
"db_url": "sqlite:///tradesv3.sqlite",
|
||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"force_entry_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5,
|
"process_throttle_secs": 5,
|
||||||
"heartbeat_interval": 60
|
"heartbeat_interval": 60
|
||||||
@ -179,6 +182,8 @@
|
|||||||
"disable_dataframe_checks": false,
|
"disable_dataframe_checks": false,
|
||||||
"strategy": "SampleStrategy",
|
"strategy": "SampleStrategy",
|
||||||
"strategy_path": "user_data/strategies/",
|
"strategy_path": "user_data/strategies/",
|
||||||
|
"recursive_strategy_search": false,
|
||||||
|
"add_config_files": [],
|
||||||
"dataformat_ohlcv": "json",
|
"dataformat_ohlcv": "json",
|
||||||
"dataformat_trades": "jsongz"
|
"dataformat_trades": "jsongz"
|
||||||
}
|
}
|
||||||
|
@ -8,21 +8,23 @@
|
|||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"entry": 10,
|
||||||
"sell": 10,
|
"exit": 10,
|
||||||
"exit_timeout_count": 0,
|
"exit_timeout_count": 0,
|
||||||
"unit": "minutes"
|
"unit": "minutes"
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"ask_last_balance": 0.0,
|
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
|
"price_last_balance": 0.0,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"bids_to_ask_delta": 1
|
"bids_to_ask_delta": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ask_strategy":{
|
"exit_pricing":{
|
||||||
|
"price_side": "same",
|
||||||
"use_order_book": true,
|
"use_order_book": true,
|
||||||
"order_book_top": 1
|
"order_book_top": 1
|
||||||
},
|
},
|
||||||
@ -93,7 +95,7 @@
|
|||||||
},
|
},
|
||||||
"bot_name": "freqtrade",
|
"bot_name": "freqtrade",
|
||||||
"initial_state": "running",
|
"initial_state": "running",
|
||||||
"forcebuy_enable": false,
|
"force_entry_enable": false,
|
||||||
"internals": {
|
"internals": {
|
||||||
"process_throttle_secs": 5
|
"process_throttle_secs": 5
|
||||||
},
|
},
|
||||||
|
73
docs/advanced-backtesting.md
Normal file
73
docs/advanced-backtesting.md
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
# Advanced Backtesting Analysis
|
||||||
|
|
||||||
|
## Analyze the buy/entry and sell/exit tags
|
||||||
|
|
||||||
|
It can be helpful to understand how a strategy behaves according to the buy/entry tags used to
|
||||||
|
mark up different buy conditions. You might want to see more complex statistics about each buy and
|
||||||
|
sell condition above those provided by the default backtesting output. You may also want to
|
||||||
|
determine indicator values on the signal candle that resulted in a trade opening.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The following buy reason analysis is only available for backtesting, *not hyperopt*.
|
||||||
|
|
||||||
|
We need to run backtesting with the `--export` option set to `signals` to enable the exporting of
|
||||||
|
signals **and** trades:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade backtesting -c <config.json> --timeframe <tf> --strategy <strategy_name> --timerange=<timerange> --export=signals
|
||||||
|
```
|
||||||
|
|
||||||
|
This will tell freqtrade to output a pickled dictionary of strategy, pairs and corresponding
|
||||||
|
DataFrame of the candles that resulted in buy signals. Depending on how many buys your strategy
|
||||||
|
makes, this file may get quite large, so periodically check your `user_data/backtest_results`
|
||||||
|
folder to delete old exports.
|
||||||
|
|
||||||
|
To analyze the buy tags, we need to use the `buy_reasons.py` script from
|
||||||
|
[froggleston's repo](https://github.com/froggleston/freqtrade-buyreasons). Follow the instructions
|
||||||
|
in their README to copy the script into your `freqtrade/scripts/` folder.
|
||||||
|
|
||||||
|
Before running your next backtest, make sure you either delete your old backtest results or run
|
||||||
|
backtesting with the `--cache none` option to make sure no cached results are used.
|
||||||
|
|
||||||
|
If all goes well, you should now see a `backtest-result-{timestamp}_signals.pkl` file in the
|
||||||
|
`user_data/backtest_results` folder.
|
||||||
|
|
||||||
|
Now run the `buy_reasons.py` script, supplying a few options:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
python3 scripts/buy_reasons.py -c <config.json> -s <strategy_name> -t <timerange> -g0,1,2,3,4
|
||||||
|
```
|
||||||
|
|
||||||
|
The `-g` option is used to specify the various tabular outputs, ranging from the simplest (0)
|
||||||
|
to the most detailed per pair, per buy and per sell tag (4). More options are available by
|
||||||
|
running with the `-h` option.
|
||||||
|
|
||||||
|
### Tuning the buy tags and sell tags to display
|
||||||
|
|
||||||
|
To show only certain buy and sell tags in the displayed output, use the following two options:
|
||||||
|
|
||||||
|
```
|
||||||
|
--enter_reason_list : Comma separated list of enter signals to analyse. Default: "all"
|
||||||
|
--exit_reason_list : Comma separated list of exit signals to analyse. Default: "stop_loss,trailing_stop_loss"
|
||||||
|
```
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 scripts/buy_reasons.py -c <config.json> -s <strategy_name> -t <timerange> -g0,1,2,3,4 --enter_reason_list "enter_tag_a,enter_tag_b" --exit_reason_list "roi,custom_exit_tag_a,stop_loss"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Outputting signal candle indicators
|
||||||
|
|
||||||
|
The real power of the buy_reasons.py script comes from the ability to print out the indicator
|
||||||
|
values present on signal candles to allow fine-grained investigation and tuning of buy signal
|
||||||
|
indicators. To print out a column for a given set of indicators, use the `--indicator-list`
|
||||||
|
option:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 scripts/buy_reasons.py -c <config.json> -s <strategy_name> -t <timerange> -g0,1,2,3,4 --enter_reason_list "enter_tag_a,enter_tag_b" --exit_reason_list "roi,custom_exit_tag_a,stop_loss" --indicator_list "rsi,rsi_1h,bb_lowerband,ema_9,macd,macdsignal"
|
||||||
|
```
|
||||||
|
|
||||||
|
The indicators have to be present in your strategy's main DataFrame (either for your main
|
||||||
|
timeframe or for informative timeframes) otherwise they will simply be ignored in the script
|
||||||
|
output.
|
@ -56,7 +56,7 @@ Currently, the arguments are:
|
|||||||
|
|
||||||
* `results`: DataFrame containing the resulting trades.
|
* `results`: DataFrame containing the resulting trades.
|
||||||
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
||||||
`pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, sell_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs`
|
`pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, exit_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs`
|
||||||
* `trade_count`: Amount of trades (identical to `len(results)`)
|
* `trade_count`: Amount of trades (identical to `len(results)`)
|
||||||
* `min_date`: Start date of the timerange used
|
* `min_date`: Start date of the timerange used
|
||||||
* `min_date`: End date of the timerange used
|
* `min_date`: End date of the timerange used
|
||||||
|
@ -20,7 +20,8 @@ usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[--dry-run-wallet DRY_RUN_WALLET]
|
[--dry-run-wallet DRY_RUN_WALLET]
|
||||||
[--timeframe-detail TIMEFRAME_DETAIL]
|
[--timeframe-detail TIMEFRAME_DETAIL]
|
||||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||||
[--export {none,trades}] [--export-filename PATH]
|
[--export {none,trades,signals}]
|
||||||
|
[--export-filename PATH]
|
||||||
[--breakdown {day,week,month} [{day,week,month} ...]]
|
[--breakdown {day,week,month} [{day,week,month} ...]]
|
||||||
[--cache {none,day,week,month}]
|
[--cache {none,day,week,month}]
|
||||||
|
|
||||||
@ -63,18 +64,17 @@ optional arguments:
|
|||||||
`30m`, `1h`, `1d`).
|
`30m`, `1h`, `1d`).
|
||||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
||||||
Provide a space-separated list of strategies to
|
Provide a space-separated list of strategies to
|
||||||
backtest. Please note that timeframe needs to be
|
backtest. Please note that timeframe needs to be set
|
||||||
set either in config or via command line. When using
|
either in config or via command line. When using this
|
||||||
this together with `--export trades`, the strategy-
|
together with `--export trades`, the strategy-name is
|
||||||
name is injected into the filename (so `backtest-
|
injected into the filename (so `backtest-data.json`
|
||||||
data.json` becomes `backtest-data-SampleStrategy.json`
|
becomes `backtest-data-SampleStrategy.json`
|
||||||
--export {none,trades}
|
--export {none,trades,signals}
|
||||||
Export backtest results (default: trades).
|
Export backtest results (default: trades).
|
||||||
--export-filename PATH
|
--export-filename PATH, --backtest-filename PATH
|
||||||
Save backtest results to the file with this filename.
|
Use this filename for backtest results.Requires
|
||||||
Requires `--export` to be set as well. Example:
|
`--export` to be set as well. Example: `--export-filen
|
||||||
`--export-filename=user_data/backtest_results/backtest
|
ame=user_data/backtest_results/backtest_today.json`
|
||||||
_today.json`
|
|
||||||
--breakdown {day,week,month} [{day,week,month} ...]
|
--breakdown {day,week,month} [{day,week,month} ...]
|
||||||
Show backtesting breakdown per [day, week, month].
|
Show backtesting breakdown per [day, week, month].
|
||||||
--cache {none,day,week,month}
|
--cache {none,day,week,month}
|
||||||
@ -274,56 +274,57 @@ A backtesting result will look like that:
|
|||||||
| 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 |
|
||||||
========================================================= SELL REASON STATS ==========================================================
|
========================================================= EXIT REASON STATS ==========================================================
|
||||||
| Sell Reason | Sells | 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 |
|
||||||
| sell_signal | 56 | 36 | 0 | 20 |
|
| exit_signal | 56 | 36 | 0 | 20 |
|
||||||
| force_sell | 2 | 0 | 0 | 2 |
|
| force_exit | 2 | 0 | 0 | 2 |
|
||||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||||
| Pair | Buys | 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 |
|
||||||
|-----------------------+---------------------|
|
|------------------------+---------------------|
|
||||||
| Backtesting from | 2019-01-01 00:00:00 |
|
| Backtesting from | 2019-01-01 00:00:00 |
|
||||||
| Backtesting to | 2019-05-01 00:00:00 |
|
| Backtesting to | 2019-05-01 00:00:00 |
|
||||||
| Max open trades | 3 |
|
| Max open trades | 3 |
|
||||||
| | |
|
| | |
|
||||||
| Total/Daily Avg Trades| 429 / 3.575 |
|
| Total/Daily Avg Trades | 429 / 3.575 |
|
||||||
| Starting balance | 0.01000000 BTC |
|
| Starting balance | 0.01000000 BTC |
|
||||||
| Final balance | 0.01762792 BTC |
|
| Final balance | 0.01762792 BTC |
|
||||||
| Absolute profit | 0.00762792 BTC |
|
| Absolute profit | 0.00762792 BTC |
|
||||||
| Total profit % | 76.2% |
|
| Total profit % | 76.2% |
|
||||||
| Trades per day | 3.575 |
|
| CAGR % | 460.87% |
|
||||||
| Avg. stake amount | 0.001 BTC |
|
| Trades per day | 3.575 |
|
||||||
| Total trade volume | 0.429 BTC |
|
| Avg. stake amount | 0.001 BTC |
|
||||||
| | |
|
| Total trade volume | 0.429 BTC |
|
||||||
| Best Pair | LSK/BTC 26.26% |
|
| | |
|
||||||
| Worst Pair | ZEC/BTC -10.18% |
|
| Best Pair | LSK/BTC 26.26% |
|
||||||
| Best Trade | LSK/BTC 4.25% |
|
| Worst Pair | ZEC/BTC -10.18% |
|
||||||
| Worst Trade | ZEC/BTC -10.25% |
|
| Best Trade | LSK/BTC 4.25% |
|
||||||
| Best day | 0.00076 BTC |
|
| Worst Trade | ZEC/BTC -10.25% |
|
||||||
| Worst day | -0.00036 BTC |
|
| Best day | 0.00076 BTC |
|
||||||
| Days win/draw/lose | 12 / 82 / 25 |
|
| Worst day | -0.00036 BTC |
|
||||||
| Avg. Duration Winners | 4:23:00 |
|
| Days win/draw/lose | 12 / 82 / 25 |
|
||||||
| Avg. Duration Loser | 6:55:00 |
|
| Avg. Duration Winners | 4:23:00 |
|
||||||
| Rejected Buy signals | 3089 |
|
| Avg. Duration Loser | 6:55:00 |
|
||||||
| Entry/Exit Timeouts | 0 / 0 |
|
| Rejected Entry signals | 3089 |
|
||||||
| | |
|
| Entry/Exit Timeouts | 0 / 0 |
|
||||||
| Min balance | 0.00945123 BTC |
|
| | |
|
||||||
| Max balance | 0.01846651 BTC |
|
| Min balance | 0.00945123 BTC |
|
||||||
| Drawdown (Account) | 13.33% |
|
| Max balance | 0.01846651 BTC |
|
||||||
| Drawdown | 0.0015 BTC |
|
| Drawdown (Account) | 13.33% |
|
||||||
| Drawdown high | 0.0013 BTC |
|
| Drawdown | 0.0015 BTC |
|
||||||
| Drawdown low | -0.0002 BTC |
|
| Drawdown high | 0.0013 BTC |
|
||||||
| Drawdown Start | 2019-02-15 14:10:00 |
|
| Drawdown low | -0.0002 BTC |
|
||||||
| Drawdown End | 2019-04-11 18:15:00 |
|
| Drawdown Start | 2019-02-15 14:10:00 |
|
||||||
| Market change | -5.88% |
|
| Drawdown End | 2019-04-11 18:15:00 |
|
||||||
|
| Market change | -5.88% |
|
||||||
===============================================
|
===============================================
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -345,9 +346,9 @@ 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 buy strategy, your sell strategy, and also by the `minimal_roi` and `stop_loss` you have set.
|
Your strategy performance is influenced by your buy strategy, your 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 sell 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%).
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"minimal_roi": {
|
"minimal_roi": {
|
||||||
@ -359,14 +360,14 @@ On the other hand, if you set a too high `minimal_roi` like `"0": 0.55`
|
|||||||
(55%), there is almost no chance that the bot will ever reach this profit.
|
(55%), there is almost no chance that the bot will ever reach this profit.
|
||||||
Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up.
|
Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up.
|
||||||
|
|
||||||
### Sell reasons table
|
### Exit reasons table
|
||||||
|
|
||||||
The 2nd table contains a recap of sell reasons.
|
The 2nd table contains a recap of exit reasons.
|
||||||
This table can tell you which area needs some additional work (e.g. all or many of the `sell_signal` trades are losses, so you should work on improving the sell signal, or consider disabling it).
|
This table can tell you which area needs some additional work (e.g. all or many of the `exit_signal` trades are losses, so you should work on improving the exit signal, or consider disabling it).
|
||||||
|
|
||||||
### Left open trades table
|
### Left open trades table
|
||||||
|
|
||||||
The 3rd table contains all trades the bot had to `forcesell` at the end of the backtesting period to present you the full picture.
|
The 3rd table contains all trades the bot had to `force_exit` at the end of the backtesting period to present you the full picture.
|
||||||
This is necessary to simulate realistic behavior, since the backtest period has to end at some point, while realistically, you could leave the bot running forever.
|
This is necessary to simulate realistic behavior, since the backtest period has to end at some point, while realistically, you could leave the bot running forever.
|
||||||
These trades are also included in the first table, but are also shown separately in this table for clarity.
|
These trades are also included in the first table, but are also shown separately in this table for clarity.
|
||||||
|
|
||||||
@ -376,43 +377,50 @@ The last element of the backtest report is the summary metrics table.
|
|||||||
It contains some useful key metrics about performance of your strategy on backtesting data.
|
It contains some useful key metrics about performance of your strategy on backtesting data.
|
||||||
|
|
||||||
```
|
```
|
||||||
=============== SUMMARY METRICS ===============
|
================ SUMMARY METRICS ===============
|
||||||
| Metric | Value |
|
| Metric | Value |
|
||||||
|-----------------------+---------------------|
|
|------------------------+---------------------|
|
||||||
| Backtesting from | 2019-01-01 00:00:00 |
|
| Backtesting from | 2019-01-01 00:00:00 |
|
||||||
| Backtesting to | 2019-05-01 00:00:00 |
|
| Backtesting to | 2019-05-01 00:00:00 |
|
||||||
| Max open trades | 3 |
|
| Max open trades | 3 |
|
||||||
| | |
|
| | |
|
||||||
| Total/Daily Avg Trades| 429 / 3.575 |
|
| Total/Daily Avg Trades | 429 / 3.575 |
|
||||||
| Starting balance | 0.01000000 BTC |
|
| Starting balance | 0.01000000 BTC |
|
||||||
| Final balance | 0.01762792 BTC |
|
| Final balance | 0.01762792 BTC |
|
||||||
| Absolute profit | 0.00762792 BTC |
|
| Absolute profit | 0.00762792 BTC |
|
||||||
| Total profit % | 76.2% |
|
| Total profit % | 76.2% |
|
||||||
| Avg. stake amount | 0.001 BTC |
|
| CAGR % | 460.87% |
|
||||||
| Total trade volume | 0.429 BTC |
|
| Avg. stake amount | 0.001 BTC |
|
||||||
| | |
|
| Total trade volume | 0.429 BTC |
|
||||||
| Best Pair | LSK/BTC 26.26% |
|
| | |
|
||||||
| Worst Pair | ZEC/BTC -10.18% |
|
| Long / Short | 352 / 77 |
|
||||||
| Best Trade | LSK/BTC 4.25% |
|
| Total profit Long % | 1250.58% |
|
||||||
| Worst Trade | ZEC/BTC -10.25% |
|
| Total profit Short % | -15.02% |
|
||||||
| Best day | 0.00076 BTC |
|
| Absolute profit Long | 0.00838792 BTC |
|
||||||
| Worst day | -0.00036 BTC |
|
| Absolute profit Short | -0.00076 BTC |
|
||||||
| Days win/draw/lose | 12 / 82 / 25 |
|
| | |
|
||||||
| Avg. Duration Winners | 4:23:00 |
|
| Best Pair | LSK/BTC 26.26% |
|
||||||
| Avg. Duration Loser | 6:55:00 |
|
| Worst Pair | ZEC/BTC -10.18% |
|
||||||
| Rejected Buy signals | 3089 |
|
| Best Trade | LSK/BTC 4.25% |
|
||||||
| Entry/Exit Timeouts | 0 / 0 |
|
| Worst Trade | ZEC/BTC -10.25% |
|
||||||
| | |
|
| Best day | 0.00076 BTC |
|
||||||
| Min balance | 0.00945123 BTC |
|
| Worst day | -0.00036 BTC |
|
||||||
| Max balance | 0.01846651 BTC |
|
| Days win/draw/lose | 12 / 82 / 25 |
|
||||||
| Drawdown (Account) | 13.33% |
|
| Avg. Duration Winners | 4:23:00 |
|
||||||
| Drawdown | 0.0015 BTC |
|
| Avg. Duration Loser | 6:55:00 |
|
||||||
| Drawdown high | 0.0013 BTC |
|
| Rejected Entry signals | 3089 |
|
||||||
| Drawdown low | -0.0002 BTC |
|
| Entry/Exit Timeouts | 0 / 0 |
|
||||||
| Drawdown Start | 2019-02-15 14:10:00 |
|
| | |
|
||||||
| Drawdown End | 2019-04-11 18:15:00 |
|
| Min balance | 0.00945123 BTC |
|
||||||
| Market change | -5.88% |
|
| Max balance | 0.01846651 BTC |
|
||||||
===============================================
|
| Drawdown (Account) | 13.33% |
|
||||||
|
| Drawdown | 0.0015 BTC |
|
||||||
|
| Drawdown high | 0.0013 BTC |
|
||||||
|
| Drawdown low | -0.0002 BTC |
|
||||||
|
| Drawdown Start | 2019-02-15 14:10:00 |
|
||||||
|
| Drawdown End | 2019-04-11 18:15:00 |
|
||||||
|
| Market change | -5.88% |
|
||||||
|
================================================
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -430,7 +438,7 @@ It contains some useful key metrics about performance of your strategy on backte
|
|||||||
- `Best day` / `Worst day`: Best and worst day based on daily profit.
|
- `Best day` / `Worst day`: Best and worst day based on daily profit.
|
||||||
- `Days win/draw/lose`: Winning / Losing days (draws are usually days without closed trade).
|
- `Days win/draw/lose`: Winning / Losing days (draws are usually days without closed trade).
|
||||||
- `Avg. Duration Winners` / `Avg. Duration Loser`: Average durations for winning and losing trades.
|
- `Avg. Duration Winners` / `Avg. Duration Loser`: Average durations for winning and losing trades.
|
||||||
- `Rejected Buy signals`: Buy signals that could not be acted upon due to max_open_trades being reached.
|
- `Rejected Entry signals`: Trade entry signals that could not be acted upon due to `max_open_trades` being reached.
|
||||||
- `Entry/Exit Timeouts`: Entry/exit orders which did not fill (only applicable if custom pricing is used).
|
- `Entry/Exit Timeouts`: Entry/exit orders which did not fill (only applicable if custom pricing is used).
|
||||||
- `Min balance` / `Max balance`: Lowest and Highest Wallet balance during the backtest period.
|
- `Min balance` / `Max balance`: Lowest and Highest Wallet balance during the backtest period.
|
||||||
- `Drawdown (Account)`: Maximum Account Drawdown experienced. Calculated as $(Absolute Drawdown) / (DrawdownHigh + startingBalance)$.
|
- `Drawdown (Account)`: Maximum Account Drawdown experienced. Calculated as $(Absolute Drawdown) / (DrawdownHigh + startingBalance)$.
|
||||||
@ -438,6 +446,9 @@ It contains some useful key metrics about performance of your strategy on backte
|
|||||||
- `Drawdown high` / `Drawdown low`: Profit at the beginning and end of the largest drawdown period. A negative low value means initial capital lost.
|
- `Drawdown high` / `Drawdown low`: Profit at the beginning and end of the largest drawdown period. A negative low value means initial capital lost.
|
||||||
- `Drawdown Start` / `Drawdown End`: Start and end datetime for this largest drawdown (can also be visualized via the `plot-dataframe` sub-command).
|
- `Drawdown Start` / `Drawdown End`: Start and end datetime for this largest drawdown (can also be visualized via the `plot-dataframe` sub-command).
|
||||||
- `Market change`: Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the "close" column.
|
- `Market change`: Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the "close" column.
|
||||||
|
- `Long / Short`: Split long/short values (Only shown when short trades were made).
|
||||||
|
- `Total profit Long %` / `Absolute profit Long`: Profit long trades only (Only shown when short trades were made).
|
||||||
|
- `Total profit Short %` / `Absolute profit Short`: Profit short trades only (Only shown when short trades were made).
|
||||||
|
|
||||||
### Daily / Weekly / Monthly breakdown
|
### Daily / Weekly / Monthly breakdown
|
||||||
|
|
||||||
@ -483,24 +494,24 @@ Since backtesting lacks some detailed information about what happens within a ca
|
|||||||
|
|
||||||
- Buys 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)
|
||||||
- Sell-signal sells happen at open-price of the consecutive candle
|
- Exit-signal exits happen at open-price of the consecutive candle
|
||||||
- Sell-signal is favored over Stoploss, because sell-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
|
||||||
- sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell 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%)
|
||||||
- sells are never "below the candle", so a ROI of 2% may result in a sell 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
|
||||||
- Forcesells caused by `<N>=-1` ROI entries use low as sell 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 sells 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` sell 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
|
- 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 sells 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
|
||||||
- Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
|
- Exit-reason does not explain if a trade was positive or negative, just what triggered the exit (this can look odd if negative ROI values are used)
|
||||||
- Evaluation sequence (if multiple signals happen on the same candle)
|
- Evaluation sequence (if multiple signals happen on the same candle)
|
||||||
- Sell-signal
|
- Exit-signal
|
||||||
- ROI (if not stoploss)
|
- ROI (if not stoploss)
|
||||||
- Stoploss
|
- Stoploss
|
||||||
|
|
||||||
@ -524,7 +535,7 @@ freqtrade backtesting --strategy AwesomeStrategy --timeframe 1h --timeframe-deta
|
|||||||
```
|
```
|
||||||
|
|
||||||
This will load 1h data as well as 5m data for the timeframe. The strategy will be analyzed with the 1h timeframe - and for every "open trade candle" (candles where a trade is open) the 5m data will be used to simulate intra-candle movements.
|
This will load 1h data as well as 5m data for the timeframe. The strategy will be analyzed with the 1h timeframe - and for every "open trade candle" (candles where a trade is open) the 5m data will be used to simulate intra-candle movements.
|
||||||
All callback functions (`custom_sell()`, `custom_stoploss()`, ... ) will be running for each 5m candle once the trade is opened (so 12 times in the above example of 1h timeframe, and 5m detailed timeframe).
|
All callback functions (`custom_exit()`, `custom_stoploss()`, ... ) will be running for each 5m candle once the trade is opened (so 12 times in the above example of 1h timeframe, and 5m detailed timeframe).
|
||||||
|
|
||||||
`--timeframe-detail` must be smaller than the original timeframe, otherwise backtesting will fail to start.
|
`--timeframe-detail` must be smaller than the original timeframe, otherwise backtesting will fail to start.
|
||||||
|
|
||||||
|
@ -29,21 +29,22 @@ By default, loop runs every few seconds (`internals.process_throttle_secs`) and
|
|||||||
* Call `bot_loop_start()` strategy callback.
|
* Call `bot_loop_start()` strategy callback.
|
||||||
* Analyze strategy per pair.
|
* Analyze strategy per pair.
|
||||||
* Call `populate_indicators()`
|
* Call `populate_indicators()`
|
||||||
* Call `populate_buy_trend()`
|
* Call `populate_entry_trend()`
|
||||||
* Call `populate_sell_trend()`
|
* Call `populate_exit_trend()`
|
||||||
* Check timeouts for open orders.
|
* Check timeouts for open orders.
|
||||||
* Calls `check_buy_timeout()` strategy callback for open buy orders.
|
* Calls `check_entry_timeout()` strategy callback for open entry orders.
|
||||||
* Calls `check_sell_timeout()` strategy callback for open sell orders.
|
* Calls `check_exit_timeout()` strategy callback for open exit orders.
|
||||||
* Verifies existing positions and eventually places sell orders.
|
* Verifies existing positions and eventually places exit orders.
|
||||||
* Considers stoploss, ROI and sell-signal, `custom_sell()` and `custom_stoploss()`.
|
* Considers stoploss, ROI and exit-signal, `custom_exit()` and `custom_stoploss()`.
|
||||||
* Determine sell-price based on `ask_strategy` configuration setting or by using the `custom_exit_price()` callback.
|
* Determine exit-price based on `exit_pricing` configuration setting or by using the `custom_exit_price()` callback.
|
||||||
* Before a sell order is placed, `confirm_trade_exit()` strategy callback is called.
|
* Before a exit order is placed, `confirm_trade_exit()` strategy callback is called.
|
||||||
* Check position adjustments for open trades if enabled by calling `adjust_trade_position()` and place additional order if required.
|
* Check position adjustments for open trades if enabled by calling `adjust_trade_position()` and place additional order if required.
|
||||||
* Check if trade-slots are still available (if `max_open_trades` is reached).
|
* Check if trade-slots are still available (if `max_open_trades` is reached).
|
||||||
* Verifies buy signal trying to enter new positions.
|
* Verifies entry signal trying to enter new positions.
|
||||||
* Determine buy-price based on `bid_strategy` configuration setting, or by using the `custom_entry_price()` callback.
|
* Determine entry-price based on `entry_pricing` configuration setting, or by using the `custom_entry_price()` callback.
|
||||||
|
* In Margin and Futures mode, `leverage()` strategy callback is called to determine the desired leverage.
|
||||||
* Determine stake size by calling the `custom_stake_amount()` callback.
|
* Determine stake size by calling the `custom_stake_amount()` callback.
|
||||||
* Before a buy order is placed, `confirm_trade_entry()` strategy callback is called.
|
* Before an entry order is placed, `confirm_trade_entry()` strategy callback is called.
|
||||||
|
|
||||||
This loop will be repeated again and again until the bot is stopped.
|
This loop will be repeated again and again until the bot is stopped.
|
||||||
|
|
||||||
@ -54,15 +55,17 @@ This loop will be repeated again and again until the bot is stopped.
|
|||||||
* Load historic data for configured pairlist.
|
* Load historic data for configured pairlist.
|
||||||
* Calls `bot_loop_start()` once.
|
* Calls `bot_loop_start()` once.
|
||||||
* Calculate indicators (calls `populate_indicators()` once per pair).
|
* Calculate indicators (calls `populate_indicators()` once per pair).
|
||||||
* Calculate buy / sell signals (calls `populate_buy_trend()` and `populate_sell_trend()` once per pair).
|
* Calculate entry / exit signals (calls `populate_entry_trend()` and `populate_exit_trend()` once per pair).
|
||||||
* Loops per candle simulating entry and exit points.
|
* Loops per candle simulating entry and exit points.
|
||||||
* Confirm trade buy / sell (calls `confirm_trade_entry()` and `confirm_trade_exit()` if implemented in the strategy).
|
* Check for Order timeouts, either via the `unfilledtimeout` configuration, or via `check_entry_timeout()` / `check_exit_timeout()` strategy callbacks.
|
||||||
|
* Check for trade entry signals (`enter_long` / `enter_short` columns).
|
||||||
|
* Confirm trade entry / exits (calls `confirm_trade_entry()` and `confirm_trade_exit()` if implemented in the strategy).
|
||||||
* Call `custom_entry_price()` (if implemented in the strategy) to determine entry price (Prices are moved to be within the opening candle).
|
* Call `custom_entry_price()` (if implemented in the strategy) to determine entry price (Prices are moved to be within the opening candle).
|
||||||
|
* In Margin and Futures mode, `leverage()` strategy callback is called to determine the desired leverage.
|
||||||
* 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_sell()` to find custom exit points.
|
* Call `custom_stoploss()` and `custom_exit()` to find custom exit points.
|
||||||
* For sells based on sell-signal and custom-sell: 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).
|
||||||
* Check for Order timeouts, either via the `unfilledtimeout` configuration, or via `check_buy_timeout()` / `check_sell_timeout()` strategy callbacks.
|
|
||||||
* Generate backtest report output
|
* Generate backtest report output
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
|
@ -53,14 +53,63 @@ FREQTRADE__EXCHANGE__SECRET=<yourExchangeSecret>
|
|||||||
|
|
||||||
Multiple configuration files can be specified and used by the bot or the bot can read its configuration parameters from the process standard input stream.
|
Multiple configuration files can be specified and used by the bot or the bot can read its configuration parameters from the process standard input stream.
|
||||||
|
|
||||||
|
You can specify additional configuration files in `add_config_files`. Files specified in this parameter will be loaded and merged with the initial config file. The files are resolved relative to the initial configuration file.
|
||||||
|
This is similar to using multiple `--config` parameters, but simpler in usage as you don't have to specify all files for all commands.
|
||||||
|
|
||||||
!!! 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.
|
||||||
|
|
||||||
|
``` json title="user_data/config.json"
|
||||||
|
"add_config_files": [
|
||||||
|
"config-private.json"
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
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
|
``` bash
|
||||||
freqtrade trade --config user_data/config.json --config user_data/config-private.json <...>
|
freqtrade trade --config user_data/config.json --config user_data/config-private.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`).
|
This is equivalent to the example above - but `config-private.json` is specified as cli argument.
|
||||||
|
|
||||||
|
??? Note "config collision handling"
|
||||||
|
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.
|
||||||
|
|
||||||
|
``` json title="user_data/config.json"
|
||||||
|
{
|
||||||
|
"max_open_trades": 3,
|
||||||
|
"stake_currency": "USDT",
|
||||||
|
"add_config_files": [
|
||||||
|
"config-import.json"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
``` json title="user_data/config-import.json"
|
||||||
|
{
|
||||||
|
"max_open_trades": 10,
|
||||||
|
"stake_amount": "unlimited",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Resulting combined configuration:
|
||||||
|
|
||||||
|
``` json title="Result"
|
||||||
|
{
|
||||||
|
"max_open_trades": 10,
|
||||||
|
"stake_currency": "USDT",
|
||||||
|
"stake_amount": "unlimited"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Configuration parameters
|
## Configuration parameters
|
||||||
|
|
||||||
@ -92,35 +141,39 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
|
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
|
||||||
| `cancel_open_orders_on_exit` | Cancel open orders when the `/stop` RPC command is issued, `Ctrl+C` is pressed or the bot dies unexpectedly. When set to `true`, this allows you to use `/stop` to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `cancel_open_orders_on_exit` | Cancel open orders when the `/stop` RPC command is issued, `Ctrl+C` is pressed or the bot dies unexpectedly. When set to `true`, this allows you to use `/stop` to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to exit a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
||||||
| `stoploss` | **Required.** Value as ratio of the stoploss used by the bot. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float (as ratio)
|
| `stoploss` | **Required.** Value as ratio of the stoploss used by the bot. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float (as ratio)
|
||||||
| `trailing_stop` | Enables trailing stoploss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md#trailing-stop-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Boolean
|
| `trailing_stop` | Enables trailing stoploss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md#trailing-stop-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Boolean
|
||||||
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-custom-positive-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float
|
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-custom-positive-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float
|
||||||
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> **Datatype:** Float
|
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> **Datatype:** Float
|
||||||
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `fee` | Fee used during backtesting / dry-runs. Should normally not be configured, which has freqtrade fall back to the exchange default fee. Set as ratio (e.g. 0.001 = 0.1%). Fee is applied twice for each trade, once when buying, once when selling. <br> **Datatype:** Float (as ratio)
|
| `fee` | Fee used during backtesting / dry-runs. Should normally not be configured, which has freqtrade fall back to the exchange default fee. Set as ratio (e.g. 0.001 = 0.1%). Fee is applied twice for each trade, once when buying, once when selling. <br> **Datatype:** Float (as ratio)
|
||||||
| `unfilledtimeout.buy` | **Required.** How long (in minutes or seconds) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
| `trading_mode` | Specifies if you want to trade regularly, trade with leverage, or trade contracts whose prices are derived from matching cryptocurrency prices. [leverage documentation](leverage.md). <br>*Defaults to `"spot"`.* <br> **Datatype:** String
|
||||||
| `unfilledtimeout.sell` | **Required.** How long (in minutes or seconds) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
| `margin_mode` | When trading with leverage, this determines if the collateral owned by the trader will be shared or isolated to each trading pair [leverage documentation](leverage.md). <br> **Datatype:** String
|
||||||
|
| `liquidation_buffer` | A ratio specifying how large of a safety net to place between the liquidation price and the stoploss to prevent a position from reaching the liquidation price [leverage documentation](leverage.md). <br>*Defaults to `0.05`.* <br> **Datatype:** Float
|
||||||
|
| `unfilledtimeout.entry` | **Required.** How long (in minutes or seconds) the bot will wait for an unfilled entry order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||||
|
| `unfilledtimeout.exit` | **Required.** How long (in minutes or seconds) the bot will wait for an unfilled exit order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||||
| `unfilledtimeout.unit` | Unit to use in unfilledtimeout setting. Note: If you set unfilledtimeout.unit to "seconds", "internals.process_throttle_secs" must be inferior or equal to timeout [Strategy Override](#parameters-in-the-strategy). <br> *Defaults to `minutes`.* <br> **Datatype:** String
|
| `unfilledtimeout.unit` | Unit to use in unfilledtimeout setting. Note: If you set unfilledtimeout.unit to "seconds", "internals.process_throttle_secs" must be inferior or equal to timeout [Strategy Override](#parameters-in-the-strategy). <br> *Defaults to `minutes`.* <br> **Datatype:** String
|
||||||
| `unfilledtimeout.exit_timeout_count` | How many times can exit orders time out. Once this number of timeouts is reached, an emergency sell is triggered. 0 to disable and allow unlimited order cancels. [Strategy Override](#parameters-in-the-strategy).<br>*Defaults to `0`.* <br> **Datatype:** Integer
|
| `unfilledtimeout.exit_timeout_count` | How many times can exit orders time out. Once this number of timeouts is reached, an emergency exit is triggered. 0 to disable and allow unlimited order cancels. [Strategy Override](#parameters-in-the-strategy).<br>*Defaults to `0`.* <br> **Datatype:** Integer
|
||||||
| `bid_strategy.price_side` | Select the side of the spread the bot should look at to get the buy rate. [More information below](#buy-price-side).<br> *Defaults to `bid`.* <br> **Datatype:** String (either `ask` or `bid`).
|
| `entry_pricing.price_side` | Select the side of the spread the bot should look at to get the entry rate. [More information below](#buy-price-side).<br> *Defaults to `same`.* <br> **Datatype:** String (either `ask`, `bid`, `same` or `other`).
|
||||||
| `bid_strategy.ask_last_balance` | **Required.** Interpolate the bidding price. More information [below](#buy-price-without-orderbook-enabled).
|
| `entry_pricing.price_last_balance` | **Required.** Interpolate the bidding price. More information [below](#entry-price-without-orderbook-enabled).
|
||||||
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
| `entry_pricing.use_order_book` | Enable entering using the rates in [Order Book Entry](#entry-price-with-orderbook-enabled). <br> *Defaults to `True`.*<br> **Datatype:** Boolean
|
||||||
| `bid_strategy.order_book_top` | Bot will use the top N rate in Order Book "price_side" to buy. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in [Order Book Bids](#buy-price-with-orderbook-enabled). <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
| `entry_pricing.order_book_top` | Bot will use the top N rate in Order Book "price_side" to enter a trade. I.e. a value of 2 will allow the bot to pick the 2nd entry in [Order Book Entry](#entry-price-with-orderbook-enabled). <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||||
| `bid_strategy. check_depth_of_market.enabled` | Do not buy if the difference of buy orders and sell orders is met in Order Book. [Check market depth](#check-depth-of-market). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `entry_pricing. check_depth_of_market.enabled` | Do not enter if the difference of buy orders and sell orders is met in Order Book. [Check market depth](#check-depth-of-market). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. [Check market depth](#check-depth-of-market) <br> *Defaults to `0`.* <br> **Datatype:** Float (as ratio)
|
| `entry_pricing. check_depth_of_market.bids_to_ask_delta` | The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. [Check market depth](#check-depth-of-market) <br> *Defaults to `0`.* <br> **Datatype:** Float (as ratio)
|
||||||
| `ask_strategy.price_side` | Select the side of the spread the bot should look at to get the sell rate. [More information below](#sell-price-side).<br> *Defaults to `ask`.* <br> **Datatype:** String (either `ask` or `bid`).
|
| `exit_pricing.price_side` | Select the side of the spread the bot should look at to get the exit rate. [More information below](#exit-price-side).<br> *Defaults to `same`.* <br> **Datatype:** String (either `ask`, `bid`, `same` or `other`).
|
||||||
| `ask_strategy.bid_last_balance` | Interpolate the selling price. More information [below](#sell-price-without-orderbook-enabled).
|
| `exit_pricing.price_last_balance` | Interpolate the exiting price. More information [below](#exit-price-without-orderbook-enabled).
|
||||||
| `ask_strategy.use_order_book` | Enable selling of open trades using [Order Book Asks](#sell-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
| `exit_pricing.use_order_book` | Enable exiting of open trades using [Order Book Exit](#exit-price-with-orderbook-enabled). <br> *Defaults to `True`.*<br> **Datatype:** Boolean
|
||||||
| `ask_strategy.order_book_top` | Bot will use the top N rate in Order Book "price_side" to sell. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in [Order Book Asks](#sell-price-with-orderbook-enabled)<br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
| `exit_pricing.order_book_top` | Bot will use the top N rate in Order Book "price_side" to exit. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in [Order Book Exit](#exit-price-with-orderbook-enabled)<br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||||
| `use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
| `use_exit_signal` | Use exit signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||||
| `sell_profit_only` | Wait until the bot reaches `sell_profit_offset` before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `exit_profit_only` | Wait until the bot reaches `exit_profit_offset` before taking an exit decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `sell_profit_offset` | Sell-signal is only active above this value. Only active in combination with `sell_profit_only=True`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
|
| `exit_profit_offset` | Exit-signal is only active above this value. Only active in combination with `exit_profit_only=True`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
|
||||||
| `ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `ignore_roi_if_entry_signal` | Do not exit if the entry signal is still active. This setting takes preference over `minimal_roi` and `use_exit_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `ignore_buying_expired_candle_after` | Specifies the number of seconds until a buy signal is no longer used. <br> **Datatype:** Integer
|
| `ignore_buying_expired_candle_after` | Specifies the number of seconds until a buy signal is no longer used. <br> **Datatype:** Integer
|
||||||
| `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict
|
| `order_types` | Configure order-types depending on the action (`"entry"`, `"exit"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict
|
||||||
| `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
| `order_time_in_force` | Configure time in force for entry and exit orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
||||||
| `custom_price_max_distance_ratio` | Configure maximum distance ratio between current and custom entry or exit price. <br>*Defaults to `0.02` 2%).*<br> **Datatype:** Positive float
|
| `custom_price_max_distance_ratio` | Configure maximum distance ratio between current and custom entry or exit price. <br>*Defaults to `0.02` 2%).*<br> **Datatype:** Positive float
|
||||||
|
| `recursive_strategy_search` | Set to `true` to recursively search sub-directories inside `user_data/strategies` for a strategy. <br> **Datatype:** Boolean
|
||||||
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> **Datatype:** String
|
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> **Datatype:** String
|
||||||
| `exchange.sandbox` | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.<br> **Datatype:** Boolean
|
| `exchange.sandbox` | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.<br> **Datatype:** Boolean
|
||||||
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||||
@ -147,10 +200,12 @@ 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
|
||||||
| `webhook.enabled` | Enable usage of Webhook notifications <br> **Datatype:** Boolean
|
| `webhook.enabled` | Enable usage of Webhook notifications <br> **Datatype:** Boolean
|
||||||
| `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||||
| `webhook.webhookbuy` | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
| `webhook.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.webhookbuycancel` | Payload to send on buy 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.webhooksell` | Payload to send on sell. 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.webhooksellcancel` | Payload to send on sell order cancel. 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.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.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.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.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
|
||||||
| `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
|
||||||
@ -161,7 +216,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `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
|
||||||
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite:///tradesv3.dryrun.sqlite` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> **Datatype:** String, SQLAlchemy connect string
|
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite:///tradesv3.dryrun.sqlite` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> **Datatype:** String, SQLAlchemy connect string
|
||||||
| `initial_state` | Defines the initial application state. 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`
|
||||||
| `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> **Datatype:** Boolean
|
| `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below. <br> **Datatype:** Boolean
|
||||||
| `disable_dataframe_checks` | Disable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. [Strategy Override](#parameters-in-the-strategy).<br> *Defaults to `False`*. <br> **Datatype:** Boolean
|
| `disable_dataframe_checks` | Disable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. [Strategy Override](#parameters-in-the-strategy).<br> *Defaults to `False`*. <br> **Datatype:** Boolean
|
||||||
| `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> **Datatype:** ClassName
|
| `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> **Datatype:** ClassName
|
||||||
| `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> **Datatype:** String
|
| `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> **Datatype:** String
|
||||||
@ -170,6 +225,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> **Datatype:** Boolean
|
| `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> **Datatype:** Boolean
|
||||||
| `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> **Datatype:** String
|
| `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> **Datatype:** String
|
||||||
| `user_data_dir` | Directory containing user data. <br> *Defaults to `./user_data/`*. <br> **Datatype:** String
|
| `user_data_dir` | Directory containing user data. <br> *Defaults to `./user_data/`*. <br> **Datatype:** String
|
||||||
|
| `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
|
||||||
| `position_adjustment_enable` | Enables the strategy to use position adjustments (additional buys or sells). [More information here](strategy-callbacks.md#adjust-trade-position). <br> [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.*<br> **Datatype:** Boolean
|
| `position_adjustment_enable` | Enables the strategy to use position adjustments (additional buys or sells). [More information here](strategy-callbacks.md#adjust-trade-position). <br> [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.*<br> **Datatype:** Boolean
|
||||||
@ -193,10 +249,10 @@ Values set in the configuration file always overwrite values set in the strategy
|
|||||||
* `order_time_in_force`
|
* `order_time_in_force`
|
||||||
* `unfilledtimeout`
|
* `unfilledtimeout`
|
||||||
* `disable_dataframe_checks`
|
* `disable_dataframe_checks`
|
||||||
* `use_sell_signal`
|
- `use_exit_signal`
|
||||||
* `sell_profit_only`
|
* `exit_profit_only`
|
||||||
* `sell_profit_offset`
|
- `exit_profit_offset`
|
||||||
* `ignore_roi_if_buy_signal`
|
- `ignore_roi_if_entry_signal`
|
||||||
* `ignore_buying_expired_candle_after`
|
* `ignore_buying_expired_candle_after`
|
||||||
* `position_adjustment_enable`
|
* `position_adjustment_enable`
|
||||||
* `max_entry_position_adjustment`
|
* `max_entry_position_adjustment`
|
||||||
@ -325,10 +381,10 @@ See the example below:
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
"minimal_roi": {
|
"minimal_roi": {
|
||||||
"40": 0.0, # Sell after 40 minutes if the profit is not negative
|
"40": 0.0, # Exit after 40 minutes if the profit is not negative
|
||||||
"30": 0.01, # Sell after 30 minutes if there is at least 1% profit
|
"30": 0.01, # Exit after 30 minutes if there is at least 1% profit
|
||||||
"20": 0.02, # Sell after 20 minutes if there is at least 2% profit
|
"20": 0.02, # Exit after 20 minutes if there is at least 2% profit
|
||||||
"0": 0.04 # Sell immediately if there is at least 4% profit
|
"0": 0.04 # Exit immediately if there is at least 4% profit
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -337,14 +393,14 @@ This parameter can be set in either Strategy or Configuration file. If you use i
|
|||||||
`minimal_roi` value from the strategy file.
|
`minimal_roi` value from the strategy file.
|
||||||
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal ROI is disabled unless your trade generates 1000% profit.
|
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal ROI is disabled unless your trade generates 1000% profit.
|
||||||
|
|
||||||
!!! Note "Special case to forcesell after a specific time"
|
!!! Note "Special case to forceexit after a specific time"
|
||||||
A special case presents using `"<N>": -1` as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.
|
A special case presents using `"<N>": -1` as ROI. This forces the bot to exit a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-exit.
|
||||||
|
|
||||||
### Understand forcebuy_enable
|
### Understand force_entry_enable
|
||||||
|
|
||||||
The `forcebuy_enable` configuration parameter enables the usage of forcebuy commands via Telegram and REST API.
|
The `force_entry_enable` configuration parameter enables the usage of force-enter (`/forcelong`, `/forceshort`) commands via Telegram and REST API.
|
||||||
For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled.
|
For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled.
|
||||||
For example, you can send `/forcebuy ETH/BTC` to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
|
For example, you can send `/forceenter ETH/BTC` to the bot, which will result in freqtrade buying the pair and holds it until a regular exit-signal (ROI, stoploss, /forceexit) appears.
|
||||||
|
|
||||||
This can be dangerous with some strategies, so use with care.
|
This can be dangerous with some strategies, so use with care.
|
||||||
|
|
||||||
@ -371,29 +427,27 @@ For example, if your strategy is using a 1h timeframe, and you only want to buy
|
|||||||
|
|
||||||
### Understand order_types
|
### Understand order_types
|
||||||
|
|
||||||
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`, `emergencysell`, `forcesell`, `forcebuy`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
The `order_types` configuration parameter maps actions (`entry`, `exit`, `stoploss`, `emergency_exit`, `force_exit`, `force_entry`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
||||||
|
|
||||||
This allows to buy using limit orders, sell using
|
This allows to enter using limit orders, exit using limit-orders, and create stoplosses using market orders.
|
||||||
limit-orders, and create stoplosses using market orders. It also allows to set the
|
It also allows to set the
|
||||||
stoploss "on exchange" which means stoploss order would be placed immediately once
|
stoploss "on exchange" which means stoploss order would be placed immediately once the buy order is fulfilled.
|
||||||
the buy order is fulfilled.
|
|
||||||
|
|
||||||
`order_types` set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole `order_types` dictionary in one place.
|
`order_types` set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole `order_types` dictionary in one place.
|
||||||
|
|
||||||
If this is configured, the following 4 values (`buy`, `sell`, `stoploss` and
|
If this is configured, the following 4 values (`entry`, `exit`, `stoploss` and `stoploss_on_exchange`) need to be present, otherwise, the bot will fail to start.
|
||||||
`stoploss_on_exchange`) need to be present, otherwise, the bot will fail to start.
|
|
||||||
|
|
||||||
For information on (`emergencysell`,`forcesell`, `forcebuy`, `stoploss_on_exchange`,`stoploss_on_exchange_interval`,`stoploss_on_exchange_limit_ratio`) please see stop loss documentation [stop loss on exchange](stoploss.md)
|
For information on (`emergency_exit`,`force_exit`, `force_entry`, `stoploss_on_exchange`,`stoploss_on_exchange_interval`,`stoploss_on_exchange_limit_ratio`) please see stop loss documentation [stop loss on exchange](stoploss.md)
|
||||||
|
|
||||||
Syntax for Strategy:
|
Syntax for Strategy:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
order_types = {
|
order_types = {
|
||||||
"buy": "limit",
|
"entry": "limit",
|
||||||
"sell": "limit",
|
"exit": "limit",
|
||||||
"emergencysell": "market",
|
"emergency_exit": "market",
|
||||||
"forcebuy": "market",
|
"force_entry": "market",
|
||||||
"forcesell": "market",
|
"force_exit": "market",
|
||||||
"stoploss": "market",
|
"stoploss": "market",
|
||||||
"stoploss_on_exchange": False,
|
"stoploss_on_exchange": False,
|
||||||
"stoploss_on_exchange_interval": 60,
|
"stoploss_on_exchange_interval": 60,
|
||||||
@ -405,11 +459,11 @@ Configuration:
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
"order_types": {
|
"order_types": {
|
||||||
"buy": "limit",
|
"entry": "limit",
|
||||||
"sell": "limit",
|
"exit": "limit",
|
||||||
"emergencysell": "market",
|
"emergency_exit": "market",
|
||||||
"forcebuy": "market",
|
"force_entry": "market",
|
||||||
"forcesell": "market",
|
"force_exit": "market",
|
||||||
"stoploss": "market",
|
"stoploss": "market",
|
||||||
"stoploss_on_exchange": false,
|
"stoploss_on_exchange": false,
|
||||||
"stoploss_on_exchange_interval": 60
|
"stoploss_on_exchange_interval": 60
|
||||||
@ -432,7 +486,7 @@ Configuration:
|
|||||||
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.
|
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.
|
||||||
|
|
||||||
!!! Warning "Warning: stoploss_on_exchange failures"
|
!!! Warning "Warning: stoploss_on_exchange failures"
|
||||||
If stoploss on exchange creation fails for some reason, then an "emergency sell" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the `emergencysell` value in the `order_types` dictionary - however, this is not advised.
|
If stoploss on exchange creation fails for some reason, then an "emergency exit" is initiated. By default, this will exit the trade using a market order. The order-type for the emergency-exit can be changed by setting the `emergency_exit` value in the `order_types` dictionary - however, this is not advised.
|
||||||
|
|
||||||
### Understand order_time_in_force
|
### Understand order_time_in_force
|
||||||
|
|
||||||
@ -462,8 +516,8 @@ The possible values are: `gtc` (default), `fok` or `ioc`.
|
|||||||
|
|
||||||
``` python
|
``` python
|
||||||
"order_time_in_force": {
|
"order_time_in_force": {
|
||||||
"buy": "gtc",
|
"entry": "gtc",
|
||||||
"sell": "gtc"
|
"exit": "gtc"
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -509,10 +563,10 @@ creating trades on the exchange.
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
"key": "key",
|
"key": "key",
|
||||||
"secret": "secret",
|
"secret": "secret",
|
||||||
...
|
...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -122,5 +122,6 @@ Best avoid relative paths, since this starts at the storage location of the jupy
|
|||||||
|
|
||||||
* [Strategy debugging](strategy_analysis_example.md) - also available as Jupyter notebook (`user_data/notebooks/strategy_analysis_example.ipynb`)
|
* [Strategy debugging](strategy_analysis_example.md) - also available as Jupyter notebook (`user_data/notebooks/strategy_analysis_example.ipynb`)
|
||||||
* [Plotting](plotting.md)
|
* [Plotting](plotting.md)
|
||||||
|
* [Tag Analysis](advanced-backtesting.md)
|
||||||
|
|
||||||
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
|
||||||
|
@ -29,6 +29,7 @@ usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[--erase]
|
[--erase]
|
||||||
[--data-format-ohlcv {json,jsongz,hdf5}]
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[--data-format-trades {json,jsongz,hdf5}]
|
[--data-format-trades {json,jsongz,hdf5}]
|
||||||
|
[--trading-mode {spot,margin,futures}]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@ -59,6 +60,8 @@ optional arguments:
|
|||||||
--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}
|
||||||
|
Select Trading mode
|
||||||
|
|
||||||
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).
|
||||||
@ -193,11 +196,14 @@ usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
{json,jsongz,hdf5} --format-to
|
{json,jsongz,hdf5} --format-to
|
||||||
{json,jsongz,hdf5} [--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} ...]]
|
[-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]
|
||||||
|
[--trading-mode {spot,margin,futures}]
|
||||||
|
[--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 ...]
|
||||||
Show profits for only these pairs. Pairs are space-
|
Limit command to these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--format-from {json,jsongz,hdf5}
|
--format-from {json,jsongz,hdf5}
|
||||||
Source format for data conversion.
|
Source format for data conversion.
|
||||||
@ -208,6 +214,12 @@ optional arguments:
|
|||||||
-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} ...]
|
-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
|
||||||
|
config is provided.
|
||||||
|
--trading-mode {spot,margin,futures}
|
||||||
|
Select Trading mode
|
||||||
|
--candle-types {spot,,futures,mark,index,premiumIndex,funding_rate} [{spot,,futures,mark,index,premiumIndex,funding_rate} ...]
|
||||||
|
Select candle type to use
|
||||||
|
|
||||||
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).
|
||||||
@ -224,6 +236,7 @@ Common arguments:
|
|||||||
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.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
##### Example converting data
|
##### Example converting data
|
||||||
@ -347,6 +360,7 @@ 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}]
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[-p PAIRS [PAIRS ...]]
|
[-p PAIRS [PAIRS ...]]
|
||||||
|
[--trading-mode {spot,margin,futures}]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@ -356,8 +370,10 @@ optional arguments:
|
|||||||
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 ...]
|
||||||
Show profits for only these pairs. Pairs are space-
|
Limit command to these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
|
--trading-mode {spot,margin,futures}
|
||||||
|
Select Trading mode
|
||||||
|
|
||||||
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).
|
||||||
|
@ -38,7 +38,7 @@ The old section of configuration parameters (`"pairlist"`) has been deprecated i
|
|||||||
|
|
||||||
Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4, and have been removed in 2020.9.
|
Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4, and have been removed in 2020.9.
|
||||||
|
|
||||||
### Using order book steps for sell price
|
### Using order book steps for exit price
|
||||||
|
|
||||||
Using `order_book_min` and `order_book_max` used to allow stepping the orderbook and trying to find the next ROI slot - trying to place sell-orders early.
|
Using `order_book_min` and `order_book_max` used to allow stepping the orderbook and trying to find the next ROI slot - trying to place sell-orders early.
|
||||||
As this does however increase risk and provides no benefit, it's been removed for maintainability purposes in 2021.7.
|
As this does however increase risk and provides no benefit, it's been removed for maintainability purposes in 2021.7.
|
||||||
@ -47,3 +47,30 @@ As this does however increase risk and provides no benefit, it's been removed fo
|
|||||||
|
|
||||||
Using separate hyperopt files was deprecated in 2021.4 and was removed in 2021.9.
|
Using separate hyperopt files was deprecated in 2021.4 and was removed in 2021.9.
|
||||||
Please switch to the new [Parametrized Strategies](hyperopt.md) to benefit from the new hyperopt interface.
|
Please switch to the new [Parametrized Strategies](hyperopt.md) to benefit from the new hyperopt interface.
|
||||||
|
|
||||||
|
## Strategy changes between V2 and V3
|
||||||
|
|
||||||
|
Isolated Futures / short trading was introduced in 2022.4. This required major changes to configuration settings, strategy interfaces, ...
|
||||||
|
|
||||||
|
We have put a great effort into keeping compatibility with existing strategies, so if you just want to continue using freqtrade in spot markets, there are no changes necessary.
|
||||||
|
While we may drop support for the current interface sometime in the future, we will announce this separately and have an appropriate transition period.
|
||||||
|
|
||||||
|
Please follow the [Strategy migration](strategy_migration.md) guide to migrate your strategy to the new format to start using the new functionalities.
|
||||||
|
|
||||||
|
### webhooks - changes with 2022.4
|
||||||
|
|
||||||
|
#### `buy_tag` has been renamed to `enter_tag`
|
||||||
|
|
||||||
|
This should apply only to your strategy and potentially to webhooks.
|
||||||
|
We will keep a compatibility layer for 1-2 versions (so both `buy_tag` and `enter_tag` will still work), but support for this in webhooks will disappear after that.
|
||||||
|
|
||||||
|
#### Naming changes
|
||||||
|
|
||||||
|
Webhook terminology changed from "sell" to "exit", and from "buy" to "entry".
|
||||||
|
|
||||||
|
* `webhookbuy` -> `webhookentry`
|
||||||
|
* `webhookbuyfill` -> `webhookentryfill`
|
||||||
|
* `webhookbuycancel` -> `webhookentrycancel`
|
||||||
|
* `webhooksell` -> `webhookexit`
|
||||||
|
* `webhooksellfill` -> `webhookexitfill`
|
||||||
|
* `webhooksellcancel` -> `webhookexitcancel`
|
||||||
|
@ -26,6 +26,9 @@ Alternatively (e.g. if your system is not supported by the setup.sh script), fol
|
|||||||
|
|
||||||
This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
|
This will install all required tools for development, including `pytest`, `flake8`, `mypy`, and `coveralls`.
|
||||||
|
|
||||||
|
Then install the git hook scripts by running `pre-commit install`, so your changes will be verified locally before committing.
|
||||||
|
This avoids a lot of waiting for CI already, as some basic formatting checks are done locally on your machine.
|
||||||
|
|
||||||
Before opening a pull request, please familiarize yourself with our [Contributing Guidelines](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md).
|
Before opening a pull request, please familiarize yourself with our [Contributing Guidelines](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md).
|
||||||
|
|
||||||
### Devcontainer setup
|
### Devcontainer setup
|
||||||
@ -220,13 +223,13 @@ Protections can have 2 different ways to stop trading for a limited :
|
|||||||
##### Protections - per pair
|
##### Protections - per pair
|
||||||
|
|
||||||
Protections that implement the per pair approach must set `has_local_stop=True`.
|
Protections that implement the per pair approach must set `has_local_stop=True`.
|
||||||
The method `stop_per_pair()` will be called whenever a trade closed (sell order completed).
|
The method `stop_per_pair()` will be called whenever a trade closed (exit order completed).
|
||||||
|
|
||||||
##### Protections - global protection
|
##### Protections - global protection
|
||||||
|
|
||||||
These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock).
|
These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock).
|
||||||
Global protection must set `has_global_stop=True` to be evaluated for global stops.
|
Global protection must set `has_global_stop=True` to be evaluated for global stops.
|
||||||
The method `global_stop()` will be called whenever a trade closed (sell order completed).
|
The method `global_stop()` will be called whenever a trade closed (exit order completed).
|
||||||
|
|
||||||
##### Protections - calculating lock end time
|
##### Protections - calculating lock end time
|
||||||
|
|
||||||
@ -264,7 +267,7 @@ Additional tests / steps to complete:
|
|||||||
* Check if balance shows correctly (*)
|
* Check if balance shows correctly (*)
|
||||||
* Create market order (*)
|
* Create market order (*)
|
||||||
* Create limit order (*)
|
* Create limit order (*)
|
||||||
* Complete trade (buy + sell) (*)
|
* Complete trade (enter + exit) (*)
|
||||||
* Compare result calculation between exchange and bot
|
* Compare result calculation between exchange and bot
|
||||||
* Ensure fees are applied correctly (check the database against the exchange)
|
* Ensure fees are applied correctly (check the database against the exchange)
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
# Exchange-specific Notes
|
# Exchange-specific Notes
|
||||||
|
|
||||||
This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.
|
This page combines common gotchas and Information which are exchange-specific and most likely don't apply to other exchanges.
|
||||||
|
|
||||||
## Exchange configuration
|
## Exchange configuration
|
||||||
|
|
||||||
@ -64,6 +64,28 @@ Binance supports [time_in_force](configuration.md#understand-order_time_in_force
|
|||||||
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues.
|
||||||
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.
|
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 Futures
|
||||||
|
|
||||||
|
Binance has specific (unfortunately complex) [Futures Trading Quantitative Rules](https://www.binance.com/en/support/faq/4f462ebe6ff445d4a170be7d9e897272) which need to be followed, and which prohibit a too low stake-amount (among others) for too many orders.
|
||||||
|
Violating these rules will result in a trading restriction.
|
||||||
|
|
||||||
|
When trading on Binance Futures market, orderbook must be used because there is no price ticker data for futures.
|
||||||
|
|
||||||
|
``` jsonc
|
||||||
|
"entry_pricing": {
|
||||||
|
"use_order_book": true,
|
||||||
|
"order_book_top": 1,
|
||||||
|
"check_depth_of_market": {
|
||||||
|
"enabled": false,
|
||||||
|
"bids_to_ask_delta": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"exit_pricing": {
|
||||||
|
"use_order_book": true,
|
||||||
|
"order_book_top": 1
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
### Binance sites
|
### 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 has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
|
||||||
|
14
docs/faq.md
14
docs/faq.md
@ -6,13 +6,15 @@ Freqtrade supports spot trading only.
|
|||||||
|
|
||||||
### Can I open short positions?
|
### Can I open short positions?
|
||||||
|
|
||||||
No, Freqtrade does not support trading with margin / leverage, and cannot open short positions.
|
Freqtrade can open short positions in futures markets.
|
||||||
|
This requires the strategy to be made for this - and `"trading_mode": "futures"` in the configuration.
|
||||||
|
Please make sure to read the [relevant documentation page](leverage.md) first.
|
||||||
|
|
||||||
In some cases, your exchange may provide leveraged spot tokens which can be traded with Freqtrade eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD, etc...
|
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 I trade options or futures?
|
### Can I trade options or futures?
|
||||||
|
|
||||||
No, options and futures trading are not supported.
|
Futures trading is supported for selected exchanges.
|
||||||
|
|
||||||
## Beginner Tips & Tricks
|
## Beginner Tips & Tricks
|
||||||
|
|
||||||
@ -77,7 +79,7 @@ You can use "current" market data by using the [dataprovider](strategy-customiza
|
|||||||
|
|
||||||
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
### Is there a setting to only SELL the coins being held and not perform anymore BUYS?
|
||||||
|
|
||||||
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forcesell 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
|
||||||
|
|
||||||
@ -117,10 +119,10 @@ As the message says, your exchange does not support market orders and you have o
|
|||||||
|
|
||||||
To fix this, redefine order types in the strategy to use "limit" instead of "market":
|
To fix this, redefine order types in the strategy to use "limit" instead of "market":
|
||||||
|
|
||||||
```
|
``` python
|
||||||
order_types = {
|
order_types = {
|
||||||
...
|
...
|
||||||
'stoploss': 'limit',
|
"stoploss": "limit",
|
||||||
...
|
...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -153,8 +153,8 @@ Checklist on all tasks / possibilities in hyperopt
|
|||||||
|
|
||||||
Depending on the space you want to optimize, only some of the below are required:
|
Depending on the space you want to optimize, only some of the below are required:
|
||||||
|
|
||||||
* define parameters with `space='buy'` - for buy signal optimization
|
* define parameters with `space='buy'` - for entry signal optimization
|
||||||
* define parameters with `space='sell'` - for sell signal optimization
|
* define parameters with `space='sell'` - for exit signal optimization
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
`populate_indicators` needs to create all indicators any of the spaces may use, otherwise hyperopt will not work.
|
`populate_indicators` needs to create all indicators any of the spaces may use, otherwise hyperopt will not work.
|
||||||
@ -180,7 +180,7 @@ Hyperopt will first load your data into memory and will then run `populate_indic
|
|||||||
|
|
||||||
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.
|
||||||
|
|
||||||
For every new set of parameters, freqtrade will run first `populate_buy_trend()` followed by `populate_sell_trend()`, and then run the regular backtesting process to simulate trades.
|
For every new set of parameters, freqtrade will run first `populate_entry_trend()` followed by `populate_exit_trend()`, and then run the regular backtesting process to simulate trades.
|
||||||
|
|
||||||
After backtesting, the results are passed into the [loss function](#loss-functions), which will evaluate if this result was better or worse than previous results.
|
After backtesting, the results are passed into the [loss function](#loss-functions), which will evaluate if this result was better or worse than previous results.
|
||||||
Based on the loss function result, hyperopt will determine the next set of parameters to try in the next round of backtesting.
|
Based on the loss function result, hyperopt will determine the next set of parameters to try in the next round of backtesting.
|
||||||
@ -190,7 +190,7 @@ Based on the loss function result, hyperopt will determine the next set of param
|
|||||||
There are two places you need to change in your strategy file to add a new buy hyperopt for testing:
|
There are two places you need to change in your strategy file to add a new buy hyperopt for testing:
|
||||||
|
|
||||||
* Define the parameters at the class level hyperopt shall be optimizing.
|
* Define the parameters at the class level hyperopt shall be optimizing.
|
||||||
* Within `populate_buy_trend()` - use defined parameter values instead of raw constants.
|
* Within `populate_entry_trend()` - use defined parameter values instead of raw constants.
|
||||||
|
|
||||||
There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
||||||
|
|
||||||
@ -200,24 +200,24 @@ There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
|||||||
!!! Hint "Guards and Triggers"
|
!!! Hint "Guards and Triggers"
|
||||||
Technically, there is no difference between Guards and Triggers.
|
Technically, there is no difference between Guards and Triggers.
|
||||||
However, this guide will make this distinction to make it clear that signals should not be "sticking".
|
However, this guide will make this distinction to make it clear that signals should not be "sticking".
|
||||||
Sticking signals are signals that are active for multiple candles. This can lead into buying a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning).
|
Sticking signals are signals that are active for multiple candles. This can lead into entering a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning).
|
||||||
|
|
||||||
Hyper-optimization will, for each epoch round, pick one trigger and possibly multiple guards.
|
Hyper-optimization will, for each epoch round, pick one trigger and possibly multiple guards.
|
||||||
|
|
||||||
#### Sell optimization
|
#### Exit signal optimization
|
||||||
|
|
||||||
Similar to the buy-signal above, sell-signals can also be optimized.
|
Similar to the entry-signal above, exit-signals can also be optimized.
|
||||||
Place the corresponding settings into the following methods
|
Place the corresponding settings into the following methods
|
||||||
|
|
||||||
* Define the parameters at the class level hyperopt shall be optimizing, either naming them `sell_*`, or by explicitly defining `space='sell'`.
|
* Define the parameters at the class level hyperopt shall be optimizing, either naming them `sell_*`, or by explicitly defining `space='sell'`.
|
||||||
* Within `populate_sell_trend()` - use defined parameter values instead of raw constants.
|
* Within `populate_exit_trend()` - use defined parameter values instead of raw constants.
|
||||||
|
|
||||||
The configuration and rules are the same than for buy signals.
|
The configuration and rules are the same than for buy signals.
|
||||||
|
|
||||||
## Solving a Mystery
|
## Solving a Mystery
|
||||||
|
|
||||||
Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys.
|
Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your long entries.
|
||||||
And you also wonder should you use RSI or ADX to help with those buy decisions.
|
And you also wonder should you use RSI or ADX to help with those decisions.
|
||||||
If you decide to use RSI or ADX, which values should I use for them?
|
If you decide to use RSI or ADX, which values should I use for them?
|
||||||
|
|
||||||
So let's use hyperparameter optimization to solve this mystery.
|
So let's use hyperparameter optimization to solve this mystery.
|
||||||
@ -274,7 +274,7 @@ The last one we call `trigger` and use it to decide which buy trigger we want to
|
|||||||
So let's write the buy strategy using these values:
|
So let's write the buy strategy using these values:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
conditions = []
|
conditions = []
|
||||||
# GUARDS AND TRENDS
|
# GUARDS AND TRENDS
|
||||||
if self.buy_adx_enabled.value:
|
if self.buy_adx_enabled.value:
|
||||||
@ -296,12 +296,12 @@ So let's write the buy strategy using these values:
|
|||||||
if conditions:
|
if conditions:
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
reduce(lambda x, y: x & y, conditions),
|
reduce(lambda x, y: x & y, conditions),
|
||||||
'buy'] = 1
|
'enter_long'] = 1
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
Hyperopt will now call `populate_buy_trend()` many times (`epochs`) with different value combinations.
|
Hyperopt will now call `populate_entry_trend()` many times (`epochs`) with different value combinations.
|
||||||
It will use the given historical data and simulate buys based on the buy signals generated with the above function.
|
It will use the given historical data and simulate buys based on the buy signals generated with the above function.
|
||||||
Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured [loss function](#loss-functions)).
|
Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured [loss function](#loss-functions)).
|
||||||
|
|
||||||
@ -364,7 +364,7 @@ class MyAwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
conditions = []
|
conditions = []
|
||||||
conditions.append(qtpylib.crossed_above(
|
conditions.append(qtpylib.crossed_above(
|
||||||
dataframe[f'ema_short_{self.buy_ema_short.value}'], dataframe[f'ema_long_{self.buy_ema_long.value}']
|
dataframe[f'ema_short_{self.buy_ema_short.value}'], dataframe[f'ema_long_{self.buy_ema_long.value}']
|
||||||
@ -376,10 +376,10 @@ class MyAwesomeStrategy(IStrategy):
|
|||||||
if conditions:
|
if conditions:
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
reduce(lambda x, y: x & y, conditions),
|
reduce(lambda x, y: x & y, conditions),
|
||||||
'buy'] = 1
|
'enter_long'] = 1
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
conditions = []
|
conditions = []
|
||||||
conditions.append(qtpylib.crossed_above(
|
conditions.append(qtpylib.crossed_above(
|
||||||
dataframe[f'ema_long_{self.buy_ema_long.value}'], dataframe[f'ema_short_{self.buy_ema_short.value}']
|
dataframe[f'ema_long_{self.buy_ema_long.value}'], dataframe[f'ema_short_{self.buy_ema_short.value}']
|
||||||
@ -391,7 +391,7 @@ class MyAwesomeStrategy(IStrategy):
|
|||||||
if conditions:
|
if conditions:
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
reduce(lambda x, y: x & y, conditions),
|
reduce(lambda x, y: x & y, conditions),
|
||||||
'sell'] = 1
|
'exit_long'] = 1
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
## Prices used for orders
|
## Prices used for orders
|
||||||
|
|
||||||
Prices for regular orders can be controlled via the parameter structures `bid_strategy` for buying and `ask_strategy` for selling.
|
Prices for regular orders can be controlled via the parameter structures `entry_pricing` for trade entries and `exit_pricing` for trade exits.
|
||||||
Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.
|
Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
@ -9,20 +9,11 @@ Prices are always retrieved right before an order is placed, either by querying
|
|||||||
!!! Warning "Using market orders"
|
!!! Warning "Using market orders"
|
||||||
Please read the section [Market order pricing](#market-order-pricing) section when using market orders.
|
Please read the section [Market order pricing](#market-order-pricing) section when using market orders.
|
||||||
|
|
||||||
### Buy price
|
### Entry price
|
||||||
|
|
||||||
#### Check depth of market
|
#### Enter price side
|
||||||
|
|
||||||
When check depth of market is enabled (`bid_strategy.check_depth_of_market.enabled=True`), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.
|
The configuration setting `entry_pricing.price_side` defines the side of the orderbook the bot looks for when buying.
|
||||||
|
|
||||||
Orderbook `bid` (buy) side depth is then divided by the orderbook `ask` (sell) side depth and the resulting delta is compared to the value of the `bid_strategy.check_depth_of_market.bids_to_ask_delta` parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
A delta value below 1 means that `ask` (sell) orderbook side depth is greater than the depth of the `bid` (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).
|
|
||||||
|
|
||||||
#### Buy price side
|
|
||||||
|
|
||||||
The configuration setting `bid_strategy.price_side` defines the side of the spread the bot looks for when buying.
|
|
||||||
|
|
||||||
The following displays an orderbook.
|
The following displays an orderbook.
|
||||||
|
|
||||||
@ -38,30 +29,53 @@ The following displays an orderbook.
|
|||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
If `bid_strategy.price_side` is set to `"bid"`, then the bot will use 99 as buying price.
|
If `entry_pricing.price_side` is set to `"bid"`, then the bot will use 99 as entry price.
|
||||||
In line with that, if `bid_strategy.price_side` is set to `"ask"`, then the bot will use 101 as buying price.
|
In line with that, if `entry_pricing.price_side` is set to `"ask"`, then the bot will use 101 as entry price.
|
||||||
|
|
||||||
Using `ask` price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary.
|
Depending on the order direction (_long_/_short_), this will lead to different results. Therefore we recommend to use `"same"` or `"other"` for this configuration instead.
|
||||||
|
This would result in the following pricing matrix:
|
||||||
|
|
||||||
|
| direction | Order | setting | price | crosses spread |
|
||||||
|
|------ |--------|-----|-----|-----|
|
||||||
|
| long | buy | ask | 101 | yes |
|
||||||
|
| long | buy | bid | 99 | no |
|
||||||
|
| long | buy | same | 99 | no |
|
||||||
|
| long | buy | other | 101 | yes |
|
||||||
|
| short | sell | ask | 101 | no |
|
||||||
|
| short | sell | bid | 99 | yes |
|
||||||
|
| short | sell | same | 101 | no |
|
||||||
|
| short | sell | other | 99 | yes |
|
||||||
|
|
||||||
|
Using the other side of the orderbook often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary.
|
||||||
Taker fees instead of maker fees will most likely apply even when using limit buy orders.
|
Taker fees instead of maker fees will most likely apply even when using limit buy orders.
|
||||||
Also, prices at the "ask" side of the spread are higher than prices at the "bid" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).
|
Also, prices at the "other" side of the spread are higher than prices at the "bid" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).
|
||||||
|
|
||||||
#### Buy price with Orderbook enabled
|
#### Entry price with Orderbook enabled
|
||||||
|
|
||||||
When buying with the orderbook enabled (`bid_strategy.use_order_book=True`), Freqtrade fetches the `bid_strategy.order_book_top` entries from the orderbook and uses the entry specified as `bid_strategy.order_book_top` on the configured side (`bid_strategy.price_side`) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
|
When entering a trade with the orderbook enabled (`entry_pricing.use_order_book=True`), Freqtrade fetches the `entry_pricing.order_book_top` entries from the orderbook and uses the entry specified as `entry_pricing.order_book_top` on the configured side (`entry_pricing.price_side`) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
|
||||||
|
|
||||||
#### Buy price without Orderbook enabled
|
#### Entry price without Orderbook enabled
|
||||||
|
|
||||||
The following section uses `side` as the configured `bid_strategy.price_side` (defaults to `"bid"`).
|
The following section uses `side` as the configured `entry_pricing.price_side` (defaults to `"same"`).
|
||||||
|
|
||||||
When not using orderbook (`bid_strategy.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's below the `last` traded price from the ticker. Otherwise (when the `side` price is above the `last` price), it calculates a rate between `side` and `last` price based on `bid_strategy.ask_last_balance`..
|
When not using orderbook (`entry_pricing.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's below the `last` traded price from the ticker. Otherwise (when the `side` price is above the `last` price), it calculates a rate between `side` and `last` price based on `entry_pricing.price_last_balance`.
|
||||||
|
|
||||||
The `bid_strategy.ask_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the `last` price and values between those interpolate between ask and last price.
|
The `entry_pricing.price_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the `last` price and values between those interpolate between ask and last price.
|
||||||
|
|
||||||
### Sell price
|
#### Check depth of market
|
||||||
|
|
||||||
#### Sell price side
|
When check depth of market is enabled (`entry_pricing.check_depth_of_market.enabled=True`), the entry signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.
|
||||||
|
|
||||||
The configuration setting `ask_strategy.price_side` defines the side of the spread the bot looks for when selling.
|
Orderbook `bid` (buy) side depth is then divided by the orderbook `ask` (sell) side depth and the resulting delta is compared to the value of the `entry_pricing.check_depth_of_market.bids_to_ask_delta` parameter. The entry order is only executed if the orderbook delta is greater than or equal to the configured delta value.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
A delta value below 1 means that `ask` (sell) orderbook side depth is greater than the depth of the `bid` (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).
|
||||||
|
|
||||||
|
### Exit price
|
||||||
|
|
||||||
|
#### Exit price side
|
||||||
|
|
||||||
|
The configuration setting `exit_pricing.price_side` defines the side of the spread the bot looks for when exiting a trade.
|
||||||
|
|
||||||
The following displays an orderbook:
|
The following displays an orderbook:
|
||||||
|
|
||||||
@ -77,40 +91,54 @@ The following displays an orderbook:
|
|||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
If `ask_strategy.price_side` is set to `"ask"`, then the bot will use 101 as selling price.
|
If `exit_pricing.price_side` is set to `"ask"`, then the bot will use 101 as exiting price.
|
||||||
In line with that, if `ask_strategy.price_side` is set to `"bid"`, then the bot will use 99 as selling price.
|
In line with that, if `exit_pricing.price_side` is set to `"bid"`, then the bot will use 99 as exiting price.
|
||||||
|
|
||||||
#### Sell price with Orderbook enabled
|
Depending on the order direction (_long_/_short_), this will lead to different results. Therefore we recommend to use `"same"` or `"other"` for this configuration instead.
|
||||||
|
This would result in the following pricing matrix:
|
||||||
|
|
||||||
When selling with the orderbook enabled (`ask_strategy.use_order_book=True`), Freqtrade fetches the `ask_strategy.order_book_top` entries in the orderbook and uses the entry specified as `ask_strategy.order_book_top` from the configured side (`ask_strategy.price_side`) as selling price.
|
| Direction | Order | setting | price | crosses spread |
|
||||||
|
|------ |--------|-----|-----|-----|
|
||||||
|
| long | sell | ask | 101 | no |
|
||||||
|
| long | sell | bid | 99 | yes |
|
||||||
|
| long | sell | same | 101 | no |
|
||||||
|
| long | sell | other | 99 | yes |
|
||||||
|
| short | buy | ask | 101 | yes |
|
||||||
|
| short | buy | bid | 99 | no |
|
||||||
|
| short | buy | same | 99 | no |
|
||||||
|
| short | buy | other | 101 | yes |
|
||||||
|
|
||||||
|
#### Exit price with Orderbook enabled
|
||||||
|
|
||||||
|
When exiting with the orderbook enabled (`exit_pricing.use_order_book=True`), Freqtrade fetches the `exit_pricing.order_book_top` entries in the orderbook and uses the entry specified as `exit_pricing.order_book_top` from the configured side (`exit_pricing.price_side`) as trade exit price.
|
||||||
|
|
||||||
1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
|
1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
|
||||||
|
|
||||||
#### Sell price without Orderbook enabled
|
#### Exit price without Orderbook enabled
|
||||||
|
|
||||||
The following section uses `side` as the configured `ask_strategy.price_side` (defaults to `"ask"`).
|
The following section uses `side` as the configured `exit_pricing.price_side` (defaults to `"ask"`).
|
||||||
|
|
||||||
When not using orderbook (`ask_strategy.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's above the `last` traded price from the ticker. Otherwise (when the `side` price is below the `last` price), it calculates a rate between `side` and `last` price based on `ask_strategy.bid_last_balance`.
|
When not using orderbook (`exit_pricing.use_order_book=False`), Freqtrade uses the best `side` price from the ticker if it's above the `last` traded price from the ticker. Otherwise (when the `side` price is below the `last` price), it calculates a rate between `side` and `last` price based on `exit_pricing.price_last_balance`.
|
||||||
|
|
||||||
The `ask_strategy.bid_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the last price and values between those interpolate between `side` and last price.
|
The `exit_pricing.price_last_balance` configuration parameter controls this. A value of `0.0` will use `side` price, while `1.0` will use the last price and values between those interpolate between `side` and last price.
|
||||||
|
|
||||||
### Market order pricing
|
### Market order pricing
|
||||||
|
|
||||||
When using market orders, prices should be configured to use the "correct" side of the orderbook to allow realistic pricing detection.
|
When using market orders, prices should be configured to use the "correct" side of the orderbook to allow realistic pricing detection.
|
||||||
Assuming both buy and sell are using market orders, a configuration similar to the following might be used
|
Assuming both entry and exits are using market orders, a configuration similar to the following must be used
|
||||||
|
|
||||||
``` jsonc
|
``` jsonc
|
||||||
"order_types": {
|
"order_types": {
|
||||||
"buy": "market",
|
"entry": "market",
|
||||||
"sell": "market"
|
"exit": "market"
|
||||||
// ...
|
// ...
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
"price_side": "ask",
|
"price_side": "other",
|
||||||
// ...
|
// ...
|
||||||
},
|
},
|
||||||
"ask_strategy":{
|
"exit_pricing":{
|
||||||
"price_side": "bid",
|
"price_side": "other",
|
||||||
// ...
|
// ...
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
@ -51,6 +51,14 @@ Please read the [exchange specific notes](exchanges.md) to learn about eventual,
|
|||||||
- [X] [OKX](https://okx.com/) (Former OKEX)
|
- [X] [OKX](https://okx.com/) (Former OKEX)
|
||||||
- [ ] [potentially many others through <img alt="ccxt" width="30px" src="assets/ccxt-logo.svg" />](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
|
- [ ] [potentially many others through <img alt="ccxt" width="30px" src="assets/ccxt-logo.svg" />](https://github.com/ccxt/ccxt/). _(We cannot guarantee they will work)_
|
||||||
|
|
||||||
|
### Experimentally, freqtrade also supports futures on the following exchanges:
|
||||||
|
|
||||||
|
- [X] [Binance](https://www.binance.com/)
|
||||||
|
- [X] [Gate.io](https://www.gate.io/ref/6266643)
|
||||||
|
- [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.
|
||||||
|
|
||||||
### Community tested
|
### Community tested
|
||||||
|
|
||||||
Exchanges confirmed working by the community:
|
Exchanges confirmed working by the community:
|
||||||
|
116
docs/leverage.md
Normal file
116
docs/leverage.md
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
# Trading with Leverage
|
||||||
|
|
||||||
|
!!! Warning "Beta feature"
|
||||||
|
This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue.
|
||||||
|
|
||||||
|
!!! Note "Multiple bots on one account"
|
||||||
|
You can't run 2 bots on the same account with leverage. For leveraged / margin trading, freqtrade assumes it's the only user of the account, and all liquidation levels are calculated based on this assumption.
|
||||||
|
|
||||||
|
!!! Danger "Trading with leverage is very risky"
|
||||||
|
Do not trade with a leverage > 1 using a strategy that hasn't shown positive results in a live run using the spot market. Check the stoploss of your strategy. With a leverage of 2, a stoploss of 0.5 (50%) would be too low, and these trades would be liquidated before reaching that stoploss.
|
||||||
|
We do not assume any responsibility for eventual losses that occur from using this software or this mode.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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 is not possible when trading with [`trading_mode`](#understand-tradingmode) set to `spot`. To short trade, `trading_mode` must be set to `margin`(currently unavailable) or [`futures`](#futures), with [`margin_mode`](#margin-mode) set to `cross`(currently unavailable) or [`isolated`](#isolated-margin-mode)
|
||||||
|
|
||||||
|
For a strategy to short, the strategy class must set the class variable `can_short = True`
|
||||||
|
|
||||||
|
Please read [strategy customization](strategy-customization.md#entry-signal-rules) for instructions on how to set signals to enter and exit short trades.
|
||||||
|
|
||||||
|
## Understand `trading_mode`
|
||||||
|
|
||||||
|
The possible values are: `spot` (default), `margin`(*Currently unavailable*) or `futures`.
|
||||||
|
|
||||||
|
### Spot
|
||||||
|
|
||||||
|
Regular trading mode (low risk)
|
||||||
|
|
||||||
|
- Long trades only (No short trades).
|
||||||
|
- No leverage.
|
||||||
|
- No Liquidation.
|
||||||
|
- Profits gained/lost are equal to the change in value of the assets (minus trading fees).
|
||||||
|
|
||||||
|
### Leverage trading modes
|
||||||
|
|
||||||
|
With leverage, a trader borrows capital from the exchange. The capital must be re-payed fully to the exchange (potentially with interest), and the trader keeps any profits, or pays any losses, from any trades made using the borrowed capital.
|
||||||
|
|
||||||
|
Because the capital must always be re-payed, exchanges will **liquidate** (forcefully sell the traders assets) a trade made using borrowed capital when the total value of assets in the leverage account drops to a certain point (a point where the total value of losses is less than the value of the collateral that the trader actually owns in the leverage account), in order to ensure that the trader has enough capital to pay the borrowed assets back to the exchange. The exchange will also charge a **liquidation fee**, adding to the traders losses.
|
||||||
|
|
||||||
|
For this reason, **DO NOT TRADE WITH LEVERAGE IF YOU DON'T KNOW EXACTLY WHAT YOUR DOING. LEVERAGE TRADING IS HIGH RISK, AND CAN RESULT IN THE VALUE OF YOUR ASSETS DROPPING TO 0 VERY QUICKLY, WITH NO CHANCE OF INCREASING IN VALUE AGAIN.**
|
||||||
|
|
||||||
|
#### Margin (currently unavailable)
|
||||||
|
|
||||||
|
Trading occurs on the spot market, but the exchange lends currency to you in an amount equal to the chosen leverage. You pay the amount lent to you back to the exchange with interest, and your profits/losses are multiplied by the leverage specified.
|
||||||
|
|
||||||
|
#### Futures
|
||||||
|
|
||||||
|
Perpetual swaps (also known as Perpetual Futures) are contracts traded at a price that is closely tied to the underlying asset they are based off of (ex.). You are not trading the actual asset but instead are trading a derivative contract. Perpetual swap contracts can last indefinitely, in contrast to futures or option contracts.
|
||||||
|
|
||||||
|
In addition to the gains/losses from the change in price of the futures contract, traders also exchange _funding fees_, which are gains/losses worth an amount that is derived from the difference in price between the futures contract and the underlying asset. The difference in price between a futures contract and the underlying asset varies between exchanges.
|
||||||
|
|
||||||
|
To trade in futures markets, you'll have to set `trading_mode` to "futures".
|
||||||
|
You will also have to pick a "margin mode" (explanation below) - with freqtrade currently only supporting isolated margin.
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"trading_mode": "futures",
|
||||||
|
"margin_mode": "isolated"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Margin mode
|
||||||
|
|
||||||
|
The possible values are: `isolated`, or `cross`(*currently unavailable*)
|
||||||
|
|
||||||
|
#### Isolated margin mode
|
||||||
|
|
||||||
|
Each market(trading pair), keeps collateral in a separate account
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"margin_mode": "isolated"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Cross margin mode (currently unavailable)
|
||||||
|
|
||||||
|
One account is used to share collateral between markets (trading pairs). Margin is taken from total account balance to avoid liquidation when needed.
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"margin_mode": "cross"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Understand `liquidation_buffer`
|
||||||
|
|
||||||
|
*Defaults to `0.05`*
|
||||||
|
|
||||||
|
A ratio specifying how large of a safety net to place between the liquidation price and the stoploss to prevent a position from reaching the liquidation price.
|
||||||
|
This artificial liquidation price is calculated as:
|
||||||
|
|
||||||
|
`freqtrade_liquidation_price = liquidation_price ± (abs(open_rate - liquidation_price) * liquidation_buffer)`
|
||||||
|
|
||||||
|
- `±` = `+` for long trades
|
||||||
|
- `±` = `-` for short trades
|
||||||
|
|
||||||
|
Possible values are any floats between 0.0 and 0.99
|
||||||
|
|
||||||
|
**ex:** If a trade is entered at a price of 10 coin/USDT, and the liquidation price of this trade is 8 coin/USDT, then with `liquidation_buffer` set to `0.05` the minimum stoploss for this trade would be $8 + ((10 - 8) * 0.05) = 8 + 0.1 = 8.1$
|
||||||
|
|
||||||
|
!!! Danger "A `liquidation_buffer` of 0.0, or a low `liquidation_buffer` is likely to result in liquidations, and liquidation fees"
|
||||||
|
Currently Freqtrade is able to calculate liquidation prices, but does not calculate liquidation fees. Setting your `liquidation_buffer` to 0.0, or using a low `liquidation_buffer` could result in your positions being liquidated. Freqtrade does not track liquidation fees, so liquidations will result in inaccurate profit/loss results for your bot. If you use a low `liquidation_buffer`, it is recommended to use `stoploss_on_exchange` if your exchange supports this.
|
||||||
|
|
||||||
|
### Developer
|
||||||
|
|
||||||
|
#### Margin mode
|
||||||
|
|
||||||
|
For shorts, the currency which pays the interest fee for the `borrowed` currency is purchased at the same time of the closing trade (This means that the amount purchased in short closing trades is greater than the amount sold in short opening trades).
|
||||||
|
|
||||||
|
For longs, the currency which pays the interest fee for the `borrowed` will already be owned by the user and does not need to be purchased. The interest is subtracted from the `close_value` of the trade.
|
||||||
|
|
||||||
|
All Fees are included in `current_profit` calculations during the trade.
|
||||||
|
|
||||||
|
#### Futures mode
|
||||||
|
|
||||||
|
Funding fees are either added or subtracted from the total amount of a trade
|
@ -14,7 +14,7 @@ pip install -U -r requirements-plot.txt
|
|||||||
|
|
||||||
The `freqtrade plot-dataframe` subcommand shows an interactive graph with three subplots:
|
The `freqtrade plot-dataframe` subcommand shows an interactive graph with three subplots:
|
||||||
|
|
||||||
* Main plot with candlestics and indicators following price (sma/ema)
|
* Main plot with candlesticks and indicators following price (sma/ema)
|
||||||
* Volume bars
|
* Volume bars
|
||||||
* Additional indicators as specified by `--indicators2`
|
* Additional indicators as specified by `--indicators2`
|
||||||
|
|
||||||
@ -96,7 +96,7 @@ Strategy arguments:
|
|||||||
Example:
|
Example:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade plot-dataframe -p BTC/ETH
|
freqtrade plot-dataframe -p BTC/ETH --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
The `-p/--pairs` argument can be used to specify pairs you would like to plot.
|
The `-p/--pairs` argument can be used to specify pairs you would like to plot.
|
||||||
@ -107,9 +107,6 @@ The `-p/--pairs` argument can be used to specify pairs you would like to plot.
|
|||||||
Specify custom indicators.
|
Specify custom indicators.
|
||||||
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
Use `--indicators1` for the main plot and `--indicators2` for the subplot below (if values are in a different range than prices).
|
||||||
|
|
||||||
!!! Tip
|
|
||||||
You will almost certainly want to specify a custom strategy! This can be done by adding `-s Classname` / `--strategy ClassName` to the command.
|
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd
|
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd
|
||||||
```
|
```
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
mkdocs==1.2.3
|
mkdocs==1.3.0
|
||||||
mkdocs-material==8.2.5
|
mkdocs-material==8.2.10
|
||||||
mdx_truly_sane_lists==1.2
|
mdx_truly_sane_lists==1.2
|
||||||
pymdown-extensions==9.3
|
pymdown-extensions==9.4
|
||||||
jinja2==3.0.3
|
jinja2==3.1.1
|
||||||
|
@ -145,9 +145,10 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
|||||||
| `locks` | Displays currently locked pairs.
|
| `locks` | Displays currently locked pairs.
|
||||||
| `delete_lock <lock_id>` | Deletes (disables) the lock by id.
|
| `delete_lock <lock_id>` | Deletes (disables) the lock by id.
|
||||||
| `profit` | Display a summary of your profit/loss from close trades and some stats about your performance.
|
| `profit` | Display a summary of your profit/loss from close trades and some stats about your performance.
|
||||||
| `forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`).
|
| `forceexit <trade_id>` | Instantly exits the given trade (Ignoring `minimum_roi`).
|
||||||
| `forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`).
|
| `forceexit all` | Instantly exits all open trades (Ignoring `minimum_roi`).
|
||||||
| `forcebuy <pair> [rate]` | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
| `forceenter <pair> [rate]` | Instantly enters the given pair. Rate is optional. (`force_entry_enable` must be set to True)
|
||||||
|
| `forceenter <pair> <side> [rate]` | Instantly longs or shorts the given pair. Rate is optional. (`force_entry_enable` must be set to True)
|
||||||
| `performance` | Show performance of each finished trade grouped by pair.
|
| `performance` | Show performance of each finished trade grouped by pair.
|
||||||
| `balance` | Show account balance per currency.
|
| `balance` | Show account balance per currency.
|
||||||
| `daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7).
|
| `daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7).
|
||||||
@ -215,8 +216,15 @@ forcebuy
|
|||||||
:param pair: Pair to buy (ETH/BTC)
|
:param pair: Pair to buy (ETH/BTC)
|
||||||
:param price: Optional - price to buy
|
:param price: Optional - price to buy
|
||||||
|
|
||||||
forcesell
|
forceenter
|
||||||
Force-sell a trade.
|
Force entering a trade
|
||||||
|
|
||||||
|
:param pair: Pair to buy (ETH/BTC)
|
||||||
|
:param side: 'long' or 'short'
|
||||||
|
:param price: Optional - price to buy
|
||||||
|
|
||||||
|
forceexit
|
||||||
|
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)
|
||||||
|
|
||||||
@ -285,6 +293,9 @@ strategy
|
|||||||
|
|
||||||
:param strategy: Strategy class name
|
:param strategy: Strategy class name
|
||||||
|
|
||||||
|
sysinfo
|
||||||
|
Provides system information (CPU, RAM usage)
|
||||||
|
|
||||||
trade
|
trade
|
||||||
Return specific trade
|
Return specific trade
|
||||||
|
|
||||||
|
@ -104,16 +104,16 @@ To mitigate this, you can try to match the first order on the opposite orderbook
|
|||||||
|
|
||||||
``` jsonc
|
``` jsonc
|
||||||
"order_types": {
|
"order_types": {
|
||||||
"buy": "limit",
|
"entry": "limit",
|
||||||
"sell": "limit"
|
"exit": "limit"
|
||||||
// ...
|
// ...
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"entry_pricing": {
|
||||||
"price_side": "ask",
|
"price_side": "other",
|
||||||
// ...
|
// ...
|
||||||
},
|
},
|
||||||
"ask_strategy":{
|
"exit_pricing":{
|
||||||
"price_side": "bid",
|
"price_side": "other",
|
||||||
// ...
|
// ...
|
||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
@ -49,14 +49,14 @@ sqlite3
|
|||||||
SELECT * FROM trades;
|
SELECT * FROM trades;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Fix trade still open after a manual sell on the exchange
|
## Fix trade still open after a manual exit on the exchange
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell <tradeid> should be used to accomplish the same thing.
|
Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, /forceexit <tradeid> should be used to accomplish the same thing.
|
||||||
It is strongly advised to backup your database file before making any manual changes.
|
It is strongly advised to backup your database file before making any manual changes.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
|
This should not be necessary after /forceexit, as force_exit orders are closed automatically by the bot on the next iteration.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
UPDATE trades
|
UPDATE trades
|
||||||
@ -65,7 +65,7 @@ SET is_open=0,
|
|||||||
close_rate=<close_rate>,
|
close_rate=<close_rate>,
|
||||||
close_profit = close_rate / open_rate - 1,
|
close_profit = close_rate / open_rate - 1,
|
||||||
close_profit_abs = (amount * <close_rate> * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))),
|
close_profit_abs = (amount * <close_rate> * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))),
|
||||||
sell_reason=<sell_reason>
|
exit_reason=<exit_reason>
|
||||||
WHERE id=<trade_ID_to_update>;
|
WHERE id=<trade_ID_to_update>;
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -78,7 +78,7 @@ SET is_open=0,
|
|||||||
close_rate=0.19638016,
|
close_rate=0.19638016,
|
||||||
close_profit=0.0496,
|
close_profit=0.0496,
|
||||||
close_profit_abs = (amount * 0.19638016 * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))),
|
close_profit_abs = (amount * 0.19638016 * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))),
|
||||||
sell_reason='force_sell'
|
exit_reason='force_exit'
|
||||||
WHERE id=31;
|
WHERE id=31;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@ Those stoploss modes can be *on exchange* or *off exchange*.
|
|||||||
These modes can be configured with these values:
|
These modes can be configured with these values:
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
'emergencysell': 'market',
|
'emergency_exit': 'market',
|
||||||
'stoploss_on_exchange': False
|
'stoploss_on_exchange': False
|
||||||
'stoploss_on_exchange_interval': 60,
|
'stoploss_on_exchange_interval': 60,
|
||||||
'stoploss_on_exchange_limit_ratio': 0.99
|
'stoploss_on_exchange_limit_ratio': 0.99
|
||||||
@ -52,30 +52,30 @@ The bot cannot do these every 5 seconds (at each iteration), otherwise it would
|
|||||||
So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute).
|
||||||
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
|
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
|
||||||
|
|
||||||
### forcesell
|
### force_exit
|
||||||
|
|
||||||
`forcesell` is an optional value, which defaults to the same value as `sell` and is used when sending a `/forcesell` command from Telegram or from the Rest API.
|
`force_exit` is an optional value, which defaults to the same value as `exit` and is used when sending a `/forceexit` command from Telegram or from the Rest API.
|
||||||
|
|
||||||
### forcebuy
|
### force_entry
|
||||||
|
|
||||||
`forcebuy` is an optional value, which defaults to the same value as `buy` and is used when sending a `/forcebuy` command from Telegram or from the Rest API.
|
`force_entry` is an optional value, which defaults to the same value as `entry` and is used when sending a `/forceentry` command from Telegram or from the Rest API.
|
||||||
|
|
||||||
### emergencysell
|
### emergency_exit
|
||||||
|
|
||||||
`emergencysell` is an optional value, which defaults to `market` and is used when creating stop loss on exchange orders fails.
|
`emergency_exit` is an optional value, which defaults to `market` and is used when creating stop loss on exchange orders fails.
|
||||||
The below is the default which is used if not changed in strategy or configuration file.
|
The below is the default which is used if not changed in strategy or configuration file.
|
||||||
|
|
||||||
Example from strategy file:
|
Example from strategy file:
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
order_types = {
|
order_types = {
|
||||||
'buy': 'limit',
|
"entry": "limit",
|
||||||
'sell': 'limit',
|
"exit": "limit",
|
||||||
'emergencysell': 'market',
|
"emergency_exit": "market",
|
||||||
'stoploss': 'market',
|
"stoploss": "market",
|
||||||
'stoploss_on_exchange': True,
|
"stoploss_on_exchange": True,
|
||||||
'stoploss_on_exchange_interval': 60,
|
"stoploss_on_exchange_interval": 60,
|
||||||
'stoploss_on_exchange_limit_ratio': 0.99
|
"stoploss_on_exchange_limit_ratio": 0.99
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -49,7 +49,7 @@ from freqtrade.exchange import timeframe_to_prev_date
|
|||||||
|
|
||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float,
|
def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float,
|
||||||
rate: float, time_in_force: str, sell_reason: str,
|
rate: float, time_in_force: str, exit_reason: str,
|
||||||
current_time: 'datetime', **kwargs) -> bool:
|
current_time: 'datetime', **kwargs) -> bool:
|
||||||
# Obtain pair dataframe.
|
# Obtain pair dataframe.
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
@ -77,47 +77,47 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
***
|
***
|
||||||
|
|
||||||
## Buy Tag
|
## Enter Tag
|
||||||
|
|
||||||
When your strategy has multiple buy signals, you can name the signal that triggered.
|
When your strategy has multiple buy signals, you can name the signal that triggered.
|
||||||
Then you can access you buy signal on `custom_sell`
|
Then you can access you buy signal on `custom_exit`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['rsi'] < 35) &
|
(dataframe['rsi'] < 35) &
|
||||||
(dataframe['volume'] > 0)
|
(dataframe['volume'] > 0)
|
||||||
),
|
),
|
||||||
['buy', 'buy_tag']] = (1, 'buy_signal_rsi')
|
['enter_long', 'enter_tag']] = (1, 'buy_signal_rsi')
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
def custom_sell(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
def custom_exit(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
||||||
current_profit: float, **kwargs):
|
current_profit: float, **kwargs):
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
last_candle = dataframe.iloc[-1].squeeze()
|
last_candle = dataframe.iloc[-1].squeeze()
|
||||||
if trade.buy_tag == 'buy_signal_rsi' and last_candle['rsi'] > 80:
|
if trade.enter_tag == 'buy_signal_rsi' and last_candle['rsi'] > 80:
|
||||||
return 'sell_signal_rsi'
|
return 'sell_signal_rsi'
|
||||||
return None
|
return None
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
`buy_tag` is limited to 100 characters, remaining data will be truncated.
|
`enter_tag` is limited to 100 characters, remaining data will be truncated.
|
||||||
|
|
||||||
## 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.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
(dataframe['rsi'] > 70) &
|
(dataframe['rsi'] > 70) &
|
||||||
(dataframe['volume'] > 0)
|
(dataframe['volume'] > 0)
|
||||||
),
|
),
|
||||||
['sell', 'exit_tag']] = (1, 'exit_rsi')
|
['exit_long', 'exit_tag']] = (1, 'exit_rsi')
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
@ -125,7 +125,7 @@ def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
The provided exit-tag is then used as sell-reason - and shown as such in backtest results.
|
The provided exit-tag is then used as sell-reason - and shown as such in backtest results.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
`sell_reason` is limited to 100 characters, remaining data will be truncated.
|
`exit_reason` is limited to 100 characters, remaining data will be truncated.
|
||||||
|
|
||||||
## Strategy version
|
## Strategy version
|
||||||
|
|
||||||
|
@ -1,25 +1,50 @@
|
|||||||
# Strategy Callbacks
|
# Strategy Callbacks
|
||||||
|
|
||||||
While the main strategy functions (`populate_indicators()`, `populate_buy_trend()`, `populate_sell_trend()`) should be used in a vectorized way, and are only called [once during backtesting](bot-basics.md#backtesting-hyperopt-execution-logic), callbacks are called "whenever needed".
|
While the main strategy functions (`populate_indicators()`, `populate_entry_trend()`, `populate_exit_trend()`) should be used in a vectorized way, and are only called [once during backtesting](bot-basics.md#backtesting-hyperopt-execution-logic), callbacks are called "whenever needed".
|
||||||
|
|
||||||
As such, you should avoid doing heavy calculations in callbacks to avoid delays during operations.
|
As such, you should avoid doing heavy calculations in callbacks to avoid delays during operations.
|
||||||
Depending on the callback used, they may be called when entering / exiting a trade, or throughout the duration of a trade.
|
Depending on the callback used, they may be called when entering / exiting a trade, or throughout the duration of a trade.
|
||||||
|
|
||||||
Currently available callbacks:
|
Currently available callbacks:
|
||||||
|
|
||||||
|
* [`bot_start()`](#bot-start)
|
||||||
* [`bot_loop_start()`](#bot-loop-start)
|
* [`bot_loop_start()`](#bot-loop-start)
|
||||||
* [`custom_stake_amount()`](#custom-stake-size)
|
* [`custom_stake_amount()`](#stake-size-management)
|
||||||
* [`custom_sell()`](#custom-sell-signal)
|
* [`custom_exit()`](#custom-exit-signal)
|
||||||
* [`custom_stoploss()`](#custom-stoploss)
|
* [`custom_stoploss()`](#custom-stoploss)
|
||||||
* [`custom_entry_price()` and `custom_exit_price()`](#custom-order-price-rules)
|
* [`custom_entry_price()` and `custom_exit_price()`](#custom-order-price-rules)
|
||||||
* [`check_buy_timeout()` and `check_sell_timeout()](#custom-order-timeout-rules)
|
* [`check_entry_timeout()` and `check_exit_timeout()`](#custom-order-timeout-rules)
|
||||||
* [`confirm_trade_entry()`](#trade-entry-buy-order-confirmation)
|
* [`confirm_trade_entry()`](#trade-entry-buy-order-confirmation)
|
||||||
* [`confirm_trade_exit()`](#trade-exit-sell-order-confirmation)
|
* [`confirm_trade_exit()`](#trade-exit-sell-order-confirmation)
|
||||||
* [`adjust_trade_position()`](#adjust-trade-position)
|
* [`adjust_trade_position()`](#adjust-trade-position)
|
||||||
|
* [`leverage()`](#leverage-callback)
|
||||||
|
|
||||||
!!! Tip "Callback calling sequence"
|
!!! Tip "Callback calling sequence"
|
||||||
You can find the callback calling sequence in [bot-basics](bot-basics.md#bot-execution-logic)
|
You can find the callback calling sequence in [bot-basics](bot-basics.md#bot-execution-logic)
|
||||||
|
|
||||||
|
## Bot start
|
||||||
|
|
||||||
|
A simple callback which is called once when the strategy is loaded.
|
||||||
|
This can be used to perform actions that must only be performed once and runs after dataprovider and wallet are set
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import requests
|
||||||
|
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
|
# ... populate_* methods
|
||||||
|
|
||||||
|
def bot_start(self, **kwargs) -> None:
|
||||||
|
"""
|
||||||
|
Called only once after bot instantiation.
|
||||||
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
|
"""
|
||||||
|
if self.config['runmode'].value in ('live', 'dry_run'):
|
||||||
|
# Assign this to the class by using self.*
|
||||||
|
# can then be used by populate_* methods
|
||||||
|
self.cust_remote_data = requests.get('https://some_remote_source.example.com')
|
||||||
|
|
||||||
|
```
|
||||||
## Bot loop start
|
## Bot loop start
|
||||||
|
|
||||||
A simple callback which is called once at the start of every bot throttling iteration (roughly every 5 seconds, unless configured differently).
|
A simple callback which is called once at the start of every bot throttling iteration (roughly every 5 seconds, unless configured differently).
|
||||||
@ -46,7 +71,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Custom Stake size
|
### 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.
|
||||||
|
|
||||||
@ -54,7 +79,7 @@ Called before entering a trade, makes it possible to manage your position size w
|
|||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||||
proposed_stake: float, min_stake: float, max_stake: float,
|
proposed_stake: float, min_stake: float, max_stake: float,
|
||||||
entry_tag: Optional[str], **kwargs) -> float:
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
|
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
|
||||||
current_candle = dataframe.iloc[-1].squeeze()
|
current_candle = dataframe.iloc[-1].squeeze()
|
||||||
@ -79,24 +104,25 @@ Freqtrade will fall back to the `proposed_stake` value should your code raise an
|
|||||||
!!! Tip
|
!!! Tip
|
||||||
Returning `0` or `None` will prevent trades from being placed.
|
Returning `0` or `None` will prevent trades from being placed.
|
||||||
|
|
||||||
## Custom sell signal
|
## Custom exit signal
|
||||||
|
|
||||||
Called for open trade every throttling iteration (roughly every 5 seconds) until a trade is closed.
|
Called for open trade every throttling iteration (roughly every 5 seconds) until a trade is closed.
|
||||||
|
|
||||||
Allows to define custom sell signals, indicating that specified position should be sold. This is very useful when we need to customize sell conditions for each individual trade, or if you need trade data to make an exit decision.
|
Allows to define custom exit signals, indicating that specified position should be sold. This is very useful when we need to customize exit conditions for each individual trade, or if you need trade data to make an exit decision.
|
||||||
|
|
||||||
For example you could implement a 1:2 risk-reward ROI with `custom_sell()`.
|
For example you could implement a 1:2 risk-reward ROI with `custom_exit()`.
|
||||||
|
|
||||||
Using custom_sell() signals in place of stoploss though *is not recommended*. It is a inferior method to using `custom_stoploss()` in this regard - which also allows you to keep the stoploss on exchange.
|
Using `custom_exit()` signals in place of stoploss though *is not recommended*. It is a inferior method to using `custom_stoploss()` in this regard - which also allows you to keep the stoploss on exchange.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Returning a (none-empty) `string` or `True` from this method is equal to setting sell signal on a candle at specified time. This method is not called when sell signal is set already, or if sell signals are disabled (`use_sell_signal=False` or `sell_profit_only=True` while profit is below `sell_profit_offset`). `string` max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters.
|
Returning a (none-empty) `string` or `True` from this method is equal to setting exit signal on a candle at specified time. This method is not called when exit signal is set already, or if exit signals are disabled (`use_exit_signal=False`). `string` max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters.
|
||||||
|
`custom_exit()` will ignore `exit_profit_only`, and will always be called unless `use_exit_signal=False`, even if there is a new enter signal.
|
||||||
|
|
||||||
An example of how we can use different indicators depending on the current profit and also sell trades that were open longer than one day:
|
An example of how we can use different indicators depending on the current profit and also exit trades that were open longer than one day:
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
def custom_exit(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
||||||
current_profit: float, **kwargs):
|
current_profit: float, **kwargs):
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
last_candle = dataframe.iloc[-1].squeeze()
|
last_candle = dataframe.iloc[-1].squeeze()
|
||||||
@ -120,10 +146,11 @@ See [Dataframe access](strategy-advanced.md#dataframe-access) for more informati
|
|||||||
|
|
||||||
## Custom stoploss
|
## Custom stoploss
|
||||||
|
|
||||||
Called for open trade every throttling iteration (roughly every 5 seconds) until a trade is closed.
|
Called for open trade every iteration (roughly every 5 seconds) until a trade is closed.
|
||||||
|
|
||||||
The usage of the custom stoploss method must be enabled by setting `use_custom_stoploss=True` on the strategy object.
|
The usage of the custom stoploss method must be enabled by setting `use_custom_stoploss=True` on the strategy object.
|
||||||
|
|
||||||
The stoploss price can only ever move upwards - if the stoploss value returned from `custom_stoploss` would result in a lower stoploss price than was previously set, it will be ignored. The traditional `stoploss` value serves as an absolute lower level and will be instated as the initial stoploss (before this method is called for the first time for a trade).
|
The stoploss price can only ever move upwards - if the stoploss value returned from `custom_stoploss` would result in a lower stoploss price than was previously set, it will be ignored. The traditional `stoploss` value serves as an absolute lower level and will be instated as the initial stoploss (before this method is called for the first time for a trade), and is still mandatory.
|
||||||
|
|
||||||
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.
|
||||||
@ -158,7 +185,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
:param pair: Pair that's currently analyzed
|
:param pair: Pair that's currently analyzed
|
||||||
:param trade: trade object.
|
:param trade: trade object.
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Rate, calculated based on pricing settings in ask_strategy.
|
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return float: New stoploss value, relative to the current rate
|
:return float: New stoploss value, relative to the current rate
|
||||||
@ -283,11 +310,11 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
# evaluate highest to lowest, so that highest possible stop is used
|
# evaluate highest to lowest, so that highest possible stop is used
|
||||||
if current_profit > 0.40:
|
if current_profit > 0.40:
|
||||||
return stoploss_from_open(0.25, current_profit)
|
return stoploss_from_open(0.25, current_profit, is_short=trade.is_short)
|
||||||
elif current_profit > 0.25:
|
elif current_profit > 0.25:
|
||||||
return stoploss_from_open(0.15, current_profit)
|
return stoploss_from_open(0.15, current_profit, is_short=trade.is_short)
|
||||||
elif current_profit > 0.20:
|
elif current_profit > 0.20:
|
||||||
return stoploss_from_open(0.07, current_profit)
|
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short)
|
||||||
|
|
||||||
# return maximum stoploss value, keeping current stoploss price unchanged
|
# return maximum stoploss value, keeping current stoploss price unchanged
|
||||||
return 1
|
return 1
|
||||||
@ -363,7 +390,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
# ... populate_* methods
|
# ... populate_* methods
|
||||||
|
|
||||||
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
||||||
entry_tag: Optional[str], **kwargs) -> float:
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
|
|
||||||
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
|
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
|
||||||
timeframe=self.timeframe)
|
timeframe=self.timeframe)
|
||||||
@ -373,7 +400,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
def custom_exit_price(self, pair: str, trade: Trade,
|
def custom_exit_price(self, pair: str, trade: Trade,
|
||||||
current_time: datetime, proposed_rate: float,
|
current_time: datetime, proposed_rate: float,
|
||||||
current_profit: float, **kwargs) -> float:
|
current_profit: float, exit_tag: Optional[str], **kwargs) -> float:
|
||||||
|
|
||||||
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
|
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
|
||||||
timeframe=self.timeframe)
|
timeframe=self.timeframe)
|
||||||
@ -391,7 +418,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 Sell_signal and Custom sell. All other sell-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
|
||||||
|
|
||||||
@ -406,7 +433,7 @@ However, freqtrade also offers a custom callback for both order types, which all
|
|||||||
### Custom order timeout example
|
### Custom order timeout example
|
||||||
|
|
||||||
Called for every open order until that order is either filled or cancelled.
|
Called for every open order until that order is either filled or cancelled.
|
||||||
`check_buy_timeout()` is called for trade entries, while `check_sell_timeout()` is called for trade exit orders.
|
`check_entry_timeout()` is called for trade entries, while `check_exit_timeout()` is called for trade exit orders.
|
||||||
|
|
||||||
A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below.
|
A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below.
|
||||||
It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins.
|
It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins.
|
||||||
@ -415,7 +442,7 @@ The function must return either `True` (cancel order) or `False` (keep order ali
|
|||||||
|
|
||||||
``` python
|
``` python
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from freqtrade.persistence import Trade
|
from freqtrade.persistence import Trade, Order
|
||||||
|
|
||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
@ -423,12 +450,12 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
# Set unfilledtimeout to 25 hours, since the maximum timeout from below is 24 hours.
|
# Set unfilledtimeout to 25 hours, since the maximum timeout from below is 24 hours.
|
||||||
unfilledtimeout = {
|
unfilledtimeout = {
|
||||||
'buy': 60 * 25,
|
'entry': 60 * 25,
|
||||||
'sell': 60 * 25
|
'exit': 60 * 25
|
||||||
}
|
}
|
||||||
|
|
||||||
def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict,
|
def check_entry_timeout(self, pair: str, trade: 'Trade', order: 'Order',
|
||||||
current_time: datetime, **kwargs) -> bool:
|
current_time: datetime, **kwargs) -> bool:
|
||||||
if trade.open_rate > 100 and trade.open_date_utc < current_time - timedelta(minutes=5):
|
if trade.open_rate > 100 and trade.open_date_utc < current_time - timedelta(minutes=5):
|
||||||
return True
|
return True
|
||||||
elif trade.open_rate > 10 and trade.open_date_utc < current_time - timedelta(minutes=3):
|
elif trade.open_rate > 10 and trade.open_date_utc < current_time - timedelta(minutes=3):
|
||||||
@ -438,7 +465,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def check_sell_timeout(self, pair: str, trade: Trade, order: dict,
|
def check_exit_timeout(self, pair: str, trade: Trade, order: 'Order',
|
||||||
current_time: datetime, **kwargs) -> bool:
|
current_time: datetime, **kwargs) -> bool:
|
||||||
if trade.open_rate > 100 and trade.open_date_utc < current_time - timedelta(minutes=5):
|
if trade.open_rate > 100 and trade.open_date_utc < current_time - timedelta(minutes=5):
|
||||||
return True
|
return True
|
||||||
@ -456,7 +483,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
``` python
|
``` python
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from freqtrade.persistence import Trade
|
from freqtrade.persistence import Trade, Order
|
||||||
|
|
||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
@ -464,26 +491,26 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
# Set unfilledtimeout to 25 hours, since the maximum timeout from below is 24 hours.
|
# Set unfilledtimeout to 25 hours, since the maximum timeout from below is 24 hours.
|
||||||
unfilledtimeout = {
|
unfilledtimeout = {
|
||||||
'buy': 60 * 25,
|
'entry': 60 * 25,
|
||||||
'sell': 60 * 25
|
'exit': 60 * 25
|
||||||
}
|
}
|
||||||
|
|
||||||
def check_buy_timeout(self, pair: str, trade: Trade, order: dict,
|
def check_entry_timeout(self, pair: str, trade: 'Trade', order: 'Order',
|
||||||
current_time: datetime, **kwargs) -> bool:
|
current_time: datetime, **kwargs) -> bool:
|
||||||
ob = self.dp.orderbook(pair, 1)
|
ob = self.dp.orderbook(pair, 1)
|
||||||
current_price = ob['bids'][0][0]
|
current_price = ob['bids'][0][0]
|
||||||
# Cancel buy order if price is more than 2% above the order.
|
# Cancel buy order if price is more than 2% above the order.
|
||||||
if current_price > order['price'] * 1.02:
|
if current_price > order.price * 1.02:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def check_sell_timeout(self, pair: str, trade: Trade, order: dict,
|
def check_exit_timeout(self, pair: str, trade: 'Trade', order: 'Order',
|
||||||
current_time: datetime, **kwargs) -> bool:
|
current_time: datetime, **kwargs) -> bool:
|
||||||
ob = self.dp.orderbook(pair, 1)
|
ob = self.dp.orderbook(pair, 1)
|
||||||
current_price = ob['asks'][0][0]
|
current_price = ob['asks'][0][0]
|
||||||
# Cancel sell order if price is more than 2% below the order.
|
# Cancel sell order if price is more than 2% below the order.
|
||||||
if current_price < order['price'] * 0.98:
|
if current_price < order.price * 0.98:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
```
|
```
|
||||||
@ -506,9 +533,9 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||||
time_in_force: str, current_time: datetime, entry_tag: Optional[str],
|
time_in_force: str, current_time: datetime, entry_tag: Optional[str],
|
||||||
**kwargs) -> bool:
|
side: str, **kwargs) -> bool:
|
||||||
"""
|
"""
|
||||||
Called right before placing a buy order.
|
Called right before placing a entry order.
|
||||||
Timing for this function is critical, so avoid doing heavy computations or
|
Timing for this function is critical, so avoid doing heavy computations or
|
||||||
network requests in this method.
|
network requests in this method.
|
||||||
|
|
||||||
@ -516,12 +543,13 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
When not implemented by a strategy, returns True (always confirming).
|
When not implemented by a strategy, returns True (always confirming).
|
||||||
|
|
||||||
:param pair: Pair that's about to be bought.
|
:param pair: Pair that's about to be bought/shorted.
|
||||||
:param order_type: Order type (as configured in order_types). usually limit or market.
|
:param order_type: Order type (as configured in order_types). usually limit or market.
|
||||||
:param amount: Amount in target (quote) currency that's going to be traded.
|
:param amount: Amount in target (quote) currency that's going to be traded.
|
||||||
:param rate: Rate that's going to be used when using limit orders
|
:param rate: Rate that's going to be used when using limit orders
|
||||||
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
|
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
|
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return bool: When True is returned, then the buy-order is placed on the exchange.
|
:return bool: When True is returned, then the buy-order is placed on the exchange.
|
||||||
False aborts the process
|
False aborts the process
|
||||||
@ -543,7 +571,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
# ... populate_* methods
|
# ... populate_* methods
|
||||||
|
|
||||||
def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
|
def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
|
||||||
rate: float, time_in_force: str, sell_reason: str,
|
rate: float, time_in_force: str, exit_reason: str,
|
||||||
current_time: datetime, **kwargs) -> bool:
|
current_time: datetime, **kwargs) -> bool:
|
||||||
"""
|
"""
|
||||||
Called right before placing a regular sell order.
|
Called right before placing a regular sell order.
|
||||||
@ -559,15 +587,15 @@ class AwesomeStrategy(IStrategy):
|
|||||||
:param amount: Amount in quote currency.
|
:param amount: Amount in quote currency.
|
||||||
:param rate: Rate that's going to be used when using limit orders
|
:param rate: Rate that's going to be used when using limit orders
|
||||||
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
|
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
|
||||||
:param sell_reason: Sell reason.
|
:param exit_reason: Exit reason.
|
||||||
Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
|
Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
|
||||||
'sell_signal', 'force_sell', 'emergency_sell']
|
'exit_signal', 'force_exit', 'emergency_exit']
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return bool: When True is returned, then the sell-order is placed on the exchange.
|
:return bool: When True is returned, then the exit-order is placed on the exchange.
|
||||||
False aborts the process
|
False aborts the process
|
||||||
"""
|
"""
|
||||||
if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0:
|
if exit_reason == 'force_exit' and trade.calc_profit_ratio(rate) < 0:
|
||||||
# Reject force-sells with negative profit
|
# Reject force-sells with negative profit
|
||||||
# This is just a sample, please adjust to your needs
|
# This is just a sample, please adjust to your needs
|
||||||
# (this does not necessarily make sense, assuming you know when you're force-selling)
|
# (this does not necessarily make sense, assuming you know when you're force-selling)
|
||||||
@ -591,6 +619,8 @@ Additional orders also result in additional fees and those orders don't count to
|
|||||||
This callback is **not** called when there is an open order (either buy or sell) waiting for execution, or when you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`.
|
This callback is **not** called when there is an open order (either buy or sell) waiting for execution, or when you have reached the maximum amount of extra buys that you have set on `max_entry_position_adjustment`.
|
||||||
`adjust_trade_position()` is called very frequently for the duration of a trade, so you must keep your implementation as performant as possible.
|
`adjust_trade_position()` is called very frequently for the duration of a trade, so you must keep your implementation as performant as possible.
|
||||||
|
|
||||||
|
Position adjustments will always be applied in the direction of the trade, so a positive value will always increase 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.
|
||||||
If you wish to buy additional orders with DCA, then make sure to leave enough funds in the wallet for that.
|
If you wish to buy additional orders with DCA, then make sure to leave enough funds in the wallet for that.
|
||||||
@ -626,7 +656,7 @@ class DigDeeperStrategy(IStrategy):
|
|||||||
# This is called when placing the initial order (opening trade)
|
# This is called when placing the initial order (opening trade)
|
||||||
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||||
proposed_stake: float, min_stake: float, max_stake: float,
|
proposed_stake: float, min_stake: float, max_stake: float,
|
||||||
entry_tag: Optional[str], **kwargs) -> float:
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
|
|
||||||
# We need to leave most of the funds for possible further DCA orders
|
# We need to leave most of the funds for possible further DCA orders
|
||||||
# This also applies to fixed stakes
|
# This also applies to fixed stakes
|
||||||
@ -660,8 +690,8 @@ class DigDeeperStrategy(IStrategy):
|
|||||||
if last_candle['close'] < previous_candle['close']:
|
if last_candle['close'] < previous_candle['close']:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
filled_buys = trade.select_filled_orders('buy')
|
filled_entries = trade.select_filled_orders(trade.entry_side)
|
||||||
count_of_buys = trade.nr_of_successful_buys
|
count_of_entries = trade.nr_of_successful_entries
|
||||||
# Allow up to 3 additional increasingly larger buys (4 in total)
|
# Allow up to 3 additional increasingly larger buys (4 in total)
|
||||||
# Initial buy is 1x
|
# Initial buy is 1x
|
||||||
# If that falls to -5% profit, we buy 1.25x more, average profit should increase to roughly -2.2%
|
# If that falls to -5% profit, we buy 1.25x more, average profit should increase to roughly -2.2%
|
||||||
@ -672,9 +702,9 @@ class DigDeeperStrategy(IStrategy):
|
|||||||
# Hope you have a deep wallet!
|
# Hope you have a deep wallet!
|
||||||
try:
|
try:
|
||||||
# This returns first order stake size
|
# This returns first order stake size
|
||||||
stake_amount = filled_buys[0].cost
|
stake_amount = filled_entries[0].cost
|
||||||
# This then calculates current safety order size
|
# This then calculates current safety order size
|
||||||
stake_amount = stake_amount * (1 + (count_of_buys * 0.25))
|
stake_amount = stake_amount * (1 + (count_of_entries * 0.25))
|
||||||
return stake_amount
|
return stake_amount
|
||||||
except Exception as exception:
|
except Exception as exception:
|
||||||
return None
|
return None
|
||||||
@ -682,3 +712,31 @@ class DigDeeperStrategy(IStrategy):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Leverage Callback
|
||||||
|
|
||||||
|
When trading in markets that allow leverage, this method must return the desired Leverage (Defaults to 1 -> No leverage).
|
||||||
|
|
||||||
|
Assuming a capital of 500USDT, a trade with leverage=3 would result in a position with 500 x 3 = 1500 USDT.
|
||||||
|
|
||||||
|
Values that are above `max_leverage` will be adjusted to `max_leverage`.
|
||||||
|
For markets / exchanges that don't support leverage, this method is ignored.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def leverage(self, pair: str, current_time: 'datetime', current_rate: float,
|
||||||
|
proposed_leverage: float, max_leverage: float, side: str,
|
||||||
|
**kwargs) -> float:
|
||||||
|
"""
|
||||||
|
Customize leverage for each new trade.
|
||||||
|
|
||||||
|
:param pair: Pair that's currently analyzed
|
||||||
|
:param current_time: datetime object, containing the current datetime
|
||||||
|
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
|
:param proposed_leverage: A leverage proposed by the bot.
|
||||||
|
:param max_leverage: Max leverage allowed on this pair
|
||||||
|
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||||
|
:return: A leverage amount, which is between 1.0 and max_leverage.
|
||||||
|
"""
|
||||||
|
return 1.0
|
||||||
|
```
|
||||||
|
@ -26,8 +26,8 @@ This will create a new strategy file from a template, which will be located unde
|
|||||||
A strategy file contains all the information needed to build a good strategy:
|
A strategy file contains all the information needed to build a good strategy:
|
||||||
|
|
||||||
- Indicators
|
- Indicators
|
||||||
- Buy strategy rules
|
- Entry strategy rules
|
||||||
- Sell strategy rules
|
- Exit strategy rules
|
||||||
- Minimal ROI recommended
|
- Minimal ROI recommended
|
||||||
- Stoploss strongly recommended
|
- Stoploss strongly recommended
|
||||||
|
|
||||||
@ -35,7 +35,7 @@ The bot also include a sample strategy called `SampleStrategy` you can update: `
|
|||||||
You can test it with the parameter: `--strategy SampleStrategy`
|
You can test it with the parameter: `--strategy SampleStrategy`
|
||||||
|
|
||||||
Additionally, there is an attribute called `INTERFACE_VERSION`, which defines the version of the strategy interface the bot should use.
|
Additionally, there is an attribute called `INTERFACE_VERSION`, which defines the version of the strategy interface the bot should use.
|
||||||
The current version is 2 - which is also the default when it's not set explicitly in the strategy.
|
The current version is 3 - which is also the default when it's not set explicitly in the strategy.
|
||||||
|
|
||||||
Future versions will require this to be set.
|
Future versions will require this to be set.
|
||||||
|
|
||||||
@ -82,7 +82,7 @@ As a dataframe is a table, simple python comparisons like the following will not
|
|||||||
|
|
||||||
``` python
|
``` python
|
||||||
if dataframe['rsi'] > 30:
|
if dataframe['rsi'] > 30:
|
||||||
dataframe['buy'] = 1
|
dataframe['enter_long'] = 1
|
||||||
```
|
```
|
||||||
|
|
||||||
The above section will fail with `The truth value of a Series is ambiguous. [...]`.
|
The above section will fail with `The truth value of a Series is ambiguous. [...]`.
|
||||||
@ -92,16 +92,16 @@ This must instead be written in a pandas-compatible way, so the operation is per
|
|||||||
``` python
|
``` python
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(dataframe['rsi'] > 30)
|
(dataframe['rsi'] > 30)
|
||||||
, 'buy'] = 1
|
, 'enter_long'] = 1
|
||||||
```
|
```
|
||||||
|
|
||||||
With this section, you have a new column in your dataframe, which has `1` assigned whenever RSI is above 30.
|
With this section, you have a new column in your dataframe, which has `1` assigned whenever RSI is above 30.
|
||||||
|
|
||||||
### Customize Indicators
|
### Customize Indicators
|
||||||
|
|
||||||
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
|
Buy and sell signals need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
|
||||||
|
|
||||||
You should only add the indicators used in either `populate_buy_trend()`, `populate_sell_trend()`, or to populate another indicator, otherwise performance may suffer.
|
You should only add the indicators used in either `populate_entry_trend()`, `populate_exit_trend()`, or to populate another indicator, otherwise performance may suffer.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
@ -199,18 +199,18 @@ If this data is available, indicators will be calculated with this extended time
|
|||||||
!!! Note
|
!!! Note
|
||||||
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
|
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
|
||||||
|
|
||||||
### Buy signal rules
|
### Entry signal rules
|
||||||
|
|
||||||
Edit the method `populate_buy_trend()` in your strategy file to update your buy strategy.
|
Edit the method `populate_entry_trend()` in your strategy file to update your entry strategy.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
This method will also define a new column, `"buy"`, which needs to contain 1 for buys, and 0 for "no action".
|
This method will also define a new column, `"enter_long"` (`"enter_short"` for shorts), which needs to contain 1 for entries, and 0 for "no action". `enter_long` is a mandatory column that must be set even if the strategy is shorting only.
|
||||||
|
|
||||||
Sample from `user_data/strategies/sample_strategy.py`:
|
Sample from `user_data/strategies/sample_strategy.py`:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Based on TA indicators, populates the buy signal for the given dataframe
|
Based on TA indicators, populates the buy signal for the given dataframe
|
||||||
:param dataframe: DataFrame populated with indicators
|
:param dataframe: DataFrame populated with indicators
|
||||||
@ -224,29 +224,58 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'buy'] = 1
|
['enter_long', 'enter_tag']] = (1, 'rsi_cross')
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
??? Note "Enter short trades"
|
||||||
|
Short-entries can be created by setting `enter_short` (corresponds to `enter_long` for long trades).
|
||||||
|
The `enter_tag` column remains identical.
|
||||||
|
Short-trades need to be supported by your exchange and market configuration!
|
||||||
|
Please make sure to set [`can_short`]() appropriately on your strategy if you intend to short.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
|
(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['enter_long', 'enter_tag']] = (1, 'rsi_cross')
|
||||||
|
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_below(dataframe['rsi'], 70)) & # Signal: RSI crosses below 70
|
||||||
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['enter_short', 'enter_tag']] = (1, 'rsi_cross')
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Buying requires sellers to buy from - therefore volume needs to be > 0 (`dataframe['volume'] > 0`) to make sure that the bot does not buy/sell in no-activity periods.
|
Buying requires sellers to buy from - therefore volume needs to be > 0 (`dataframe['volume'] > 0`) to make sure that the bot does not buy/sell in no-activity periods.
|
||||||
|
|
||||||
### Sell signal rules
|
### Exit signal rules
|
||||||
|
|
||||||
Edit the method `populate_sell_trend()` into your strategy file to update your sell strategy.
|
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
|
||||||
Please note that the sell-signal is only used if `use_sell_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.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
This method will also define a new column, `"sell"`, which needs to contain 1 for sells, and 0 for "no action".
|
This method will also define a new column, `"exit_long"` (`"exit_short"` for shorts), which needs to contain 1 for exits, and 0 for "no action".
|
||||||
|
|
||||||
Sample from `user_data/strategies/sample_strategy.py`:
|
Sample from `user_data/strategies/sample_strategy.py`:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Based on TA indicators, populates the sell signal for the given dataframe
|
Based on TA indicators, populates the exit signal for the given dataframe
|
||||||
:param dataframe: DataFrame populated with indicators
|
:param dataframe: DataFrame populated with indicators
|
||||||
:param metadata: Additional information, like the currently traded pair
|
:param metadata: Additional information, like the currently traded pair
|
||||||
:return: DataFrame with buy column
|
:return: DataFrame with buy column
|
||||||
@ -258,13 +287,39 @@ def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame
|
|||||||
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
),
|
),
|
||||||
'sell'] = 1
|
['exit_long', 'exit_tag']] = (1, 'rsi_too_high')
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
??? Note "Exit short trades"
|
||||||
|
Short-exits can be created by setting `exit_short` (corresponds to `exit_long`).
|
||||||
|
The `exit_tag` column remains identical.
|
||||||
|
Short-trades need to be supported by your exchange and market configuration!
|
||||||
|
|
||||||
|
```python
|
||||||
|
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
|
||||||
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['exit_long', 'exit_tag']] = (1, 'rsi_too_high')
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_below(dataframe['rsi'], 30)) & # Signal: RSI crosses below 30
|
||||||
|
(dataframe['tema'] < dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['exit_short', 'exit_tag']] = (1, 'rsi_too_low')
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
### Minimal ROI
|
### Minimal ROI
|
||||||
|
|
||||||
This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.
|
This dict defines the minimal Return On Investment (ROI) a trade should reach before exiting, independent from the exit signal.
|
||||||
|
|
||||||
It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
|
It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
|
||||||
|
|
||||||
@ -279,10 +334,10 @@ minimal_roi = {
|
|||||||
|
|
||||||
The above configuration would therefore mean:
|
The above configuration would therefore mean:
|
||||||
|
|
||||||
- Sell whenever 4% profit was reached
|
- Exit whenever 4% profit was reached
|
||||||
- Sell when 2% profit was reached (in effect after 20 minutes)
|
- Exit when 2% profit was reached (in effect after 20 minutes)
|
||||||
- Sell when 1% profit was reached (in effect after 30 minutes)
|
- Exit when 1% profit was reached (in effect after 30 minutes)
|
||||||
- Sell when trade is non-loosing (in effect after 40 minutes)
|
- Exit when trade is non-loosing (in effect after 40 minutes)
|
||||||
|
|
||||||
The calculation does include fees.
|
The calculation does include fees.
|
||||||
|
|
||||||
@ -294,7 +349,7 @@ minimal_roi = {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
|
While technically not completely disabled, this would exit once the trade reaches 10000% Profit.
|
||||||
|
|
||||||
To use times based on candle duration (timeframe), the following snippet can be handy.
|
To use times based on candle duration (timeframe), the following snippet can be handy.
|
||||||
This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...)
|
This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...)
|
||||||
@ -330,13 +385,19 @@ For the full documentation on stoploss features, look at the dedicated [stoploss
|
|||||||
This is the set of candles the bot should download and use for the analysis.
|
This is the set of candles the bot should download and use for the analysis.
|
||||||
Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work.
|
Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work.
|
||||||
|
|
||||||
Please note that the same buy/sell signals may work well with one timeframe, but not with the others.
|
Please note that the same entry/exit signals may work well with one timeframe, but not with the others.
|
||||||
|
|
||||||
This setting is accessible within the strategy methods as the `self.timeframe` attribute.
|
This setting is accessible within the strategy methods as the `self.timeframe` attribute.
|
||||||
|
|
||||||
|
### Can short
|
||||||
|
|
||||||
|
To use short signals in futures markets, you will have to let us know to do so by setting `can_short=True`.
|
||||||
|
Strategies which enable this will fail to load on spot markets.
|
||||||
|
Disabling of this will have short signals ignored (also in futures markets).
|
||||||
|
|
||||||
### Metadata dict
|
### Metadata dict
|
||||||
|
|
||||||
The metadata-dict (available for `populate_buy_trend`, `populate_sell_trend`, `populate_indicators`) contains additional information.
|
The metadata-dict (available for `populate_entry_trend`, `populate_exit_trend`, `populate_indicators`) contains additional information.
|
||||||
Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`.
|
Currently this is `pair`, which can be accessed using `metadata['pair']` - and will return a pair in the format `XRP/BTC`.
|
||||||
|
|
||||||
The Metadata-dict should not be modified and does not persist information across multiple calls.
|
The Metadata-dict should not be modified and does not persist information across multiple calls.
|
||||||
@ -382,6 +443,19 @@ A full sample can be found [in the DataProvider section](#complete-data-provider
|
|||||||
It is however better to use resampling to longer timeframes whenever possible
|
It is however better to use resampling to longer timeframes whenever possible
|
||||||
to avoid hammering the exchange with too many requests and risk being blocked.
|
to avoid hammering the exchange with too many requests and risk being blocked.
|
||||||
|
|
||||||
|
??? Note "Alternative candle types"
|
||||||
|
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. Details about this can be found in the exchange documentation.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
def informative_pairs(self):
|
||||||
|
return [
|
||||||
|
("ETH/USDT", "5m", ""), # Uses default candletype, depends on trading_mode
|
||||||
|
("ETH/USDT", "5m", "spot"), # Forces usage of spot candles
|
||||||
|
("BTC/TUSD", "15m", "futures"), # Uses futures candles
|
||||||
|
("BTC/TUSD", "15m", "mark"), # Uses mark candles
|
||||||
|
]
|
||||||
|
```
|
||||||
***
|
***
|
||||||
|
|
||||||
### Informative pairs decorator (`@informative()`)
|
### Informative pairs decorator (`@informative()`)
|
||||||
@ -395,6 +469,8 @@ for more information.
|
|||||||
``` python
|
``` python
|
||||||
def informative(timeframe: str, asset: str = '',
|
def informative(timeframe: str, asset: str = '',
|
||||||
fmt: Optional[Union[str, Callable[[KwArg(str)], str]]] = None,
|
fmt: Optional[Union[str, Callable[[KwArg(str)], str]]] = None,
|
||||||
|
*,
|
||||||
|
candle_type: Optional[CandleType] = None,
|
||||||
ffill: bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]:
|
ffill: bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]:
|
||||||
"""
|
"""
|
||||||
A decorator for populate_indicators_Nn(self, dataframe, metadata), allowing these functions to
|
A decorator for populate_indicators_Nn(self, dataframe, metadata), allowing these functions to
|
||||||
@ -423,6 +499,7 @@ for more information.
|
|||||||
* {column} - name of dataframe column.
|
* {column} - name of dataframe column.
|
||||||
* {timeframe} - timeframe of informative dataframe.
|
* {timeframe} - timeframe of informative dataframe.
|
||||||
:param ffill: ffill dataframe after merging informative pair.
|
:param ffill: ffill dataframe after merging informative pair.
|
||||||
|
:param candle_type: '', mark, index, premiumIndex, or funding_rate
|
||||||
"""
|
"""
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -451,7 +528,7 @@ for more information.
|
|||||||
|
|
||||||
# Define BTC/STAKE informative pair. Available in populate_indicators and other methods as
|
# Define BTC/STAKE informative pair. Available in populate_indicators and other methods as
|
||||||
# 'btc_rsi_1h'. Current stake currency should be specified as {stake} format variable
|
# 'btc_rsi_1h'. Current stake currency should be specified as {stake} format variable
|
||||||
# instead of hardcoding actual stake currency. Available in populate_indicators and other
|
# instead of hard-coding actual stake currency. Available in populate_indicators and other
|
||||||
# methods as 'btc_usdt_rsi_1h' (when stake currency is USDT).
|
# methods as 'btc_usdt_rsi_1h' (when stake currency is USDT).
|
||||||
@informative('1h', 'BTC/{stake}')
|
@informative('1h', 'BTC/{stake}')
|
||||||
def populate_indicators_btc_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_indicators_btc_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
@ -490,7 +567,7 @@ for more information.
|
|||||||
Use string formatting when accessing informative dataframes of other pairs. This will allow easily changing stake currency in config without having to adjust strategy code.
|
Use string formatting when accessing informative dataframes of other pairs. This will allow easily changing stake currency in config without having to adjust strategy code.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
stake = self.config['stake_currency']
|
stake = self.config['stake_currency']
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
@ -498,7 +575,7 @@ for more information.
|
|||||||
&
|
&
|
||||||
(dataframe['volume'] > 0)
|
(dataframe['volume'] > 0)
|
||||||
),
|
),
|
||||||
['buy', 'buy_tag']] = (1, 'buy_signal_rsi')
|
['enter_long', 'enter_tag']] = (1, 'buy_signal_rsi')
|
||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
```
|
```
|
||||||
@ -510,7 +587,6 @@ for more information.
|
|||||||
will overwrite previously defined method and not produce any errors due to limitations of Python programming language. In such cases you will find that indicators
|
will overwrite previously defined method and not produce any errors due to limitations of Python programming language. In such cases you will find that indicators
|
||||||
created in earlier-defined methods are not available in the dataframe. Carefully review method names and make sure they are unique!
|
created in earlier-defined methods are not available in the dataframe. Carefully review method names and make sure they are unique!
|
||||||
|
|
||||||
|
|
||||||
## Additional data (DataProvider)
|
## Additional data (DataProvider)
|
||||||
|
|
||||||
The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
|
The strategy provides access to the `DataProvider`. This allows you to get additional data to use in your strategy.
|
||||||
@ -706,7 +782,7 @@ class SampleStrategy(IStrategy):
|
|||||||
|
|
||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
@ -714,7 +790,7 @@ class SampleStrategy(IStrategy):
|
|||||||
(dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30
|
(dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30
|
||||||
(dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting)
|
(dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting)
|
||||||
),
|
),
|
||||||
'buy'] = 1
|
['enter_long', 'enter_tag']] = (1, 'rsi_cross')
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -791,7 +867,7 @@ Stoploss values returned from `custom_stoploss` must specify a percentage relati
|
|||||||
|
|
||||||
Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21`).
|
Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21`).
|
||||||
|
|
||||||
If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100.
|
If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit, False)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100.
|
||||||
|
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
@ -811,7 +887,7 @@ Stoploss values returned from `custom_stoploss` must specify a percentage relati
|
|||||||
|
|
||||||
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
||||||
if current_profit > 0.10:
|
if current_profit > 0.10:
|
||||||
return stoploss_from_open(0.07, current_profit)
|
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short)
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
@ -822,7 +898,7 @@ Stoploss values returned from `custom_stoploss` must specify a percentage relati
|
|||||||
!!! Note
|
!!! Note
|
||||||
Providing invalid input to `stoploss_from_open()` may produce "CustomStoploss function did not return valid stoploss" warnings.
|
Providing invalid input to `stoploss_from_open()` may produce "CustomStoploss function did not return valid stoploss" warnings.
|
||||||
This may happen if `current_profit` parameter is below specified `open_relative_stop`. Such situations may arise when closing trade
|
This may happen if `current_profit` parameter is below specified `open_relative_stop`. Such situations may arise when closing trade
|
||||||
is blocked by `confirm_trade_exit()` method. Warnings can be solved by never blocking stop loss sells by checking `sell_reason` in
|
is blocked by `confirm_trade_exit()` method. Warnings can be solved by never blocking stop loss sells by checking `exit_reason` in
|
||||||
`confirm_trade_exit()`, or by using `return stoploss_from_open(...) or 1` idiom, which will request to not change stop loss when
|
`confirm_trade_exit()`, or by using `return stoploss_from_open(...) or 1` idiom, which will request to not change stop loss when
|
||||||
`current_profit < open_relative_stop`.
|
`current_profit < open_relative_stop`.
|
||||||
|
|
||||||
@ -832,7 +908,7 @@ In some situations it may be confusing to deal with stops relative to current ra
|
|||||||
|
|
||||||
??? Example "Returning a stoploss using absolute price from the custom stoploss function"
|
??? Example "Returning a stoploss using absolute price from the custom stoploss function"
|
||||||
|
|
||||||
If we want to trail a stop price at 2xATR below current proce we can call `stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate)`.
|
If we want to trail a stop price at 2xATR below current price we can call `stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short)`.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
|
|
||||||
@ -852,7 +928,7 @@ In some situations it may be confusing to deal with stops relative to current ra
|
|||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, **kwargs) -> float:
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
candle = dataframe.iloc[-1].squeeze()
|
candle = dataframe.iloc[-1].squeeze()
|
||||||
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate)
|
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -920,7 +996,7 @@ if self.config['runmode'].value in ('live', 'dry_run'):
|
|||||||
Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).
|
Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).
|
||||||
|
|
||||||
``` json
|
``` json
|
||||||
{'pair': "ETH/BTC", 'profit': 0.015, 'count': 5}
|
{"pair": "ETH/BTC", "profit": 0.015, "count": 5}
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
@ -974,16 +1050,16 @@ if self.config['runmode'].value in ('live', 'dry_run'):
|
|||||||
|
|
||||||
## Print created dataframe
|
## Print created dataframe
|
||||||
|
|
||||||
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
To inspect the created dataframe, you can issue a print-statement in either `populate_entry_trend()` or `populate_exit_trend()`.
|
||||||
You may also want to print the pair so it's clear what data is currently shown.
|
You may also want to print the pair so it's clear what data is currently shown.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
dataframe.loc[
|
dataframe.loc[
|
||||||
(
|
(
|
||||||
#>> whatever condition<<<
|
#>> whatever condition<<<
|
||||||
),
|
),
|
||||||
'buy'] = 1
|
['enter_long', 'enter_tag']] = (1, 'somestring')
|
||||||
|
|
||||||
# Print the Analyzed pair
|
# Print the Analyzed pair
|
||||||
print(f"result for {metadata['pair']}")
|
print(f"result for {metadata['pair']}")
|
||||||
@ -1012,7 +1088,12 @@ The following lists some common patterns which should be avoided to prevent frus
|
|||||||
|
|
||||||
### Colliding signals
|
### Colliding signals
|
||||||
|
|
||||||
When buy and sell signals collide (both `'buy'` and `'sell'` are 1), freqtrade will do nothing and ignore the entry (buy) signal. This will avoid trades that buy, and sell immediately. Obviously, this can potentially lead to missed entries.
|
When conflicting signals collide (e.g. both `'enter_long'` and `'exit_long'` are 1), freqtrade will do nothing and ignore the entry signal. This will avoid trades that enter, and exit immediately. Obviously, this can potentially lead to missed entries.
|
||||||
|
|
||||||
|
The following rules apply, and entry signals will be ignored if more than one of the 3 signals is set:
|
||||||
|
|
||||||
|
- `enter_long` -> `exit_long`, `enter_short`
|
||||||
|
- `enter_short` -> `exit_short`, `enter_long`
|
||||||
|
|
||||||
## Further strategy ideas
|
## Further strategy ideas
|
||||||
|
|
||||||
|
@ -73,7 +73,7 @@ df.tail()
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Report results
|
# Report results
|
||||||
print(f"Generated {df['buy'].sum()} buy signals")
|
print(f"Generated {df['enter_long'].sum()} entry signals")
|
||||||
data = df.set_index('date', drop=False)
|
data = df.set_index('date', drop=False)
|
||||||
data.tail()
|
data.tail()
|
||||||
```
|
```
|
||||||
@ -129,7 +129,7 @@ print(stats['strategy_comparison'])
|
|||||||
trades = load_backtest_data(backtest_dir)
|
trades = load_backtest_data(backtest_dir)
|
||||||
|
|
||||||
# Show value-counts per pair
|
# Show value-counts per pair
|
||||||
trades.groupby("pair")["sell_reason"].value_counts()
|
trades.groupby("pair")["exit_reason"].value_counts()
|
||||||
```
|
```
|
||||||
|
|
||||||
## Plotting daily profit / equity line
|
## Plotting daily profit / equity line
|
||||||
@ -182,7 +182,7 @@ from freqtrade.data.btanalysis import load_trades_from_db
|
|||||||
trades = load_trades_from_db("sqlite:///tradesv3.sqlite")
|
trades = load_trades_from_db("sqlite:///tradesv3.sqlite")
|
||||||
|
|
||||||
# Display results
|
# Display results
|
||||||
trades.groupby("pair")["sell_reason"].value_counts()
|
trades.groupby("pair")["exit_reason"].value_counts()
|
||||||
```
|
```
|
||||||
|
|
||||||
## Analyze the loaded trades for trade parallelism
|
## Analyze the loaded trades for trade parallelism
|
||||||
@ -244,7 +244,7 @@ import plotly.figure_factory as ff
|
|||||||
hist_data = [trades.profit_ratio]
|
hist_data = [trades.profit_ratio]
|
||||||
group_labels = ['profit_ratio'] # name of the dataset
|
group_labels = ['profit_ratio'] # name of the dataset
|
||||||
|
|
||||||
fig = ff.create_distplot(hist_data, group_labels,bin_size=0.01)
|
fig = ff.create_distplot(hist_data, group_labels, bin_size=0.01)
|
||||||
fig.show()
|
fig.show()
|
||||||
|
|
||||||
```
|
```
|
||||||
|
471
docs/strategy_migration.md
Normal file
471
docs/strategy_migration.md
Normal file
@ -0,0 +1,471 @@
|
|||||||
|
# Strategy Migration between V2 and V3
|
||||||
|
|
||||||
|
To support new markets and trade-types (namely short trades / trades with leverage), some things had to change in the interface.
|
||||||
|
If you intend on using markets other than spot markets, please migrate your strategy to the new format.
|
||||||
|
|
||||||
|
We have put a great effort into keeping compatibility with existing strategies, so if you just want to continue using freqtrade in __spot markets__, there should be no changes necessary for now.
|
||||||
|
|
||||||
|
You can use the quick summary as checklist. Please refer to the detailed sections below for full migration details.
|
||||||
|
|
||||||
|
## Quick summary / migration checklist
|
||||||
|
|
||||||
|
Note : `forcesell`, `forcebuy`, `emergencysell` are changed to `force_exit`, `force_enter`, `emergency_exit` respectively.
|
||||||
|
|
||||||
|
* Strategy methods:
|
||||||
|
* [`populate_buy_trend()` -> `populate_entry_trend()`](#populate_buy_trend)
|
||||||
|
* [`populate_sell_trend()` -> `populate_exit_trend()`](#populate_sell_trend)
|
||||||
|
* [`custom_sell()` -> `custom_exit()`](#custom_sell)
|
||||||
|
* [`check_buy_timeout()` -> `check_entry_timeout()`](#custom_entry_timeout)
|
||||||
|
* [`check_sell_timeout()` -> `check_exit_timeout()`](#custom_entry_timeout)
|
||||||
|
* New `side` argument to callbacks without trade object
|
||||||
|
* [`custom_stake_amount`](#custom-stake-amount)
|
||||||
|
* [`confirm_trade_entry`](#confirm_trade_entry)
|
||||||
|
* [`custom_entry_price`](#custom_entry_price)
|
||||||
|
* [Changed argument name in `confirm_trade_exit`](#confirm_trade_exit)
|
||||||
|
* Dataframe columns:
|
||||||
|
* [`buy` -> `enter_long`](#populate_buy_trend)
|
||||||
|
* [`sell` -> `exit_long`](#populate_sell_trend)
|
||||||
|
* [`buy_tag` -> `enter_tag` (used for both long and short trades)](#populate_buy_trend)
|
||||||
|
* [New column `enter_short` and corresponding new column `exit_short`](#populate_sell_trend)
|
||||||
|
* trade-object now has the following new properties:
|
||||||
|
* `is_short`
|
||||||
|
* `entry_side`
|
||||||
|
* `exit_side`
|
||||||
|
* `trade_direction`
|
||||||
|
* renamed: `sell_reason` -> `exit_reason`
|
||||||
|
* [Renamed `trade.nr_of_successful_buys` to `trade.nr_of_successful_entries` (mostly relevant for `adjust_trade_position()`)](#adjust-trade-position-changes)
|
||||||
|
* Introduced new [`leverage` callback](strategy-callbacks.md#leverage-callback).
|
||||||
|
* Informative pairs can now pass a 3rd element in the Tuple, defining the candle type.
|
||||||
|
* `@informative` decorator now takes an optional `candle_type` argument.
|
||||||
|
* [helper methods](#helper-methods) `stoploss_from_open` and `stoploss_from_absolute` now take `is_short` as additional argument.
|
||||||
|
* `INTERFACE_VERSION` should be set to 3.
|
||||||
|
* [Strategy/Configuration settings](#strategyconfiguration-settings).
|
||||||
|
* `order_time_in_force` buy -> entry, sell -> exit.
|
||||||
|
* `order_types` buy -> entry, sell -> exit.
|
||||||
|
* `unfilledtimeout` buy -> entry, sell -> exit.
|
||||||
|
* 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_signal` -> `exit_signal`
|
||||||
|
* `custom_sell` -> `custom_exit`
|
||||||
|
* `force_sell` -> `force_exit`
|
||||||
|
* `emergency_sell` -> `emergency_exit`
|
||||||
|
* Webhook terminology changed from "sell" to "exit", and from "buy" to entry
|
||||||
|
* `webhookbuy` -> `webhookentry`
|
||||||
|
* `webhookbuyfill` -> `webhookentryfill`
|
||||||
|
* `webhookbuycancel` -> `webhookentrycancel`
|
||||||
|
* `webhooksell` -> `webhookexit`
|
||||||
|
* `webhooksellfill` -> `webhookexitfill`
|
||||||
|
* `webhooksellcancel` -> `webhookexitcancel`
|
||||||
|
* Telegram notification settings
|
||||||
|
* `buy` -> `entry`
|
||||||
|
* `buy_fill` -> `entry_fill`
|
||||||
|
* `buy_cancel` -> `entry_cancel`
|
||||||
|
* `sell` -> `exit`
|
||||||
|
* `sell_fill` -> `exit_fill`
|
||||||
|
* `sell_cancel` -> `exit_cancel`
|
||||||
|
* Strategy/config settings:
|
||||||
|
* `use_sell_signal` -> `use_exit_signal`
|
||||||
|
* `sell_profit_only` -> `exit_profit_only`
|
||||||
|
* `sell_profit_offset` -> `exit_profit_offset`
|
||||||
|
* `ignore_roi_if_buy_signal` -> `ignore_roi_if_entry_signal`
|
||||||
|
* `forcebuy_enable` -> `force_entry_enable`
|
||||||
|
|
||||||
|
## Extensive explanation
|
||||||
|
|
||||||
|
### `populate_buy_trend`
|
||||||
|
|
||||||
|
In `populate_buy_trend()` - you will want to change the columns you assign from `'buy`' to `'enter_long'`, as well as the method name from `populate_buy_trend` to `populate_entry_trend`.
|
||||||
|
|
||||||
|
```python hl_lines="1 9"
|
||||||
|
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
|
(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['buy', 'buy_tag']] = (1, 'rsi_cross')
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
```python hl_lines="1 9"
|
||||||
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
|
(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['enter_long', 'enter_tag']] = (1, 'rsi_cross')
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
Please refer to the [Strategy documentation](strategy-customization.md#entry-signal-rules) on how to enter and exit short trades.
|
||||||
|
|
||||||
|
### `populate_sell_trend`
|
||||||
|
|
||||||
|
Similar to `populate_buy_trend`, `populate_sell_trend()` will be renamed to `populate_exit_trend()`.
|
||||||
|
We'll also change the column from `'sell'` to `'exit_long'`.
|
||||||
|
|
||||||
|
``` python hl_lines="1 9"
|
||||||
|
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
|
||||||
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['sell', 'exit_tag']] = (1, 'some_exit_tag')
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
After
|
||||||
|
|
||||||
|
``` python hl_lines="1 9"
|
||||||
|
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
|
||||||
|
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard
|
||||||
|
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
|
||||||
|
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||||
|
),
|
||||||
|
['exit_long', 'exit_tag']] = (1, 'some_exit_tag')
|
||||||
|
return dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
Please refer to the [Strategy documentation](strategy-customization.md#exit-signal-rules) on how to enter and exit short trades.
|
||||||
|
|
||||||
|
### `custom_sell`
|
||||||
|
|
||||||
|
`custom_sell` has been renamed to `custom_exit`.
|
||||||
|
It's now also being called for every iteration, independent of current profit and `exit_profit_only` settings.
|
||||||
|
|
||||||
|
``` python hl_lines="2"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
||||||
|
current_profit: float, **kwargs):
|
||||||
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
|
last_candle = dataframe.iloc[-1].squeeze()
|
||||||
|
# ...
|
||||||
|
```
|
||||||
|
|
||||||
|
``` python hl_lines="2"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def custom_exit(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
||||||
|
current_profit: float, **kwargs):
|
||||||
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
|
last_candle = dataframe.iloc[-1].squeeze()
|
||||||
|
# ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### `custom_entry_timeout`
|
||||||
|
|
||||||
|
`check_buy_timeout()` has been renamed to `check_entry_timeout()`, and `check_sell_timeout()` has been renamed to `check_exit_timeout()`.
|
||||||
|
|
||||||
|
``` python hl_lines="2 6"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict,
|
||||||
|
current_time: datetime, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict,
|
||||||
|
current_time: datetime, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
```
|
||||||
|
|
||||||
|
``` python hl_lines="2 6"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def check_entry_timeout(self, pair: str, trade: 'Trade', order: 'Order',
|
||||||
|
current_time: datetime, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def check_exit_timeout(self, pair: str, trade: 'Trade', order: 'Order',
|
||||||
|
current_time: datetime, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom-stake-amount
|
||||||
|
|
||||||
|
New string argument `side` - which can be either `"long"` or `"short"`.
|
||||||
|
|
||||||
|
``` python hl_lines="4"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||||
|
proposed_stake: float, min_stake: float, max_stake: float,
|
||||||
|
entry_tag: Optional[str], **kwargs) -> float:
|
||||||
|
# ...
|
||||||
|
return proposed_stake
|
||||||
|
```
|
||||||
|
|
||||||
|
``` python hl_lines="4"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||||
|
proposed_stake: float, min_stake: float, max_stake: float,
|
||||||
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
|
# ...
|
||||||
|
return proposed_stake
|
||||||
|
```
|
||||||
|
|
||||||
|
### `confirm_trade_entry`
|
||||||
|
|
||||||
|
New string argument `side` - which can be either `"long"` or `"short"`.
|
||||||
|
|
||||||
|
``` python hl_lines="4"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||||
|
time_in_force: str, current_time: datetime, entry_tag: Optional[str],
|
||||||
|
**kwargs) -> bool:
|
||||||
|
return True
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="4"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||||
|
time_in_force: str, current_time: datetime, entry_tag: Optional[str],
|
||||||
|
side: str, **kwargs) -> bool:
|
||||||
|
return True
|
||||||
|
```
|
||||||
|
|
||||||
|
### `confirm_trade_exit`
|
||||||
|
|
||||||
|
Changed argument `sell_reason` to `exit_reason`.
|
||||||
|
For compatibility, `sell_reason` will still be provided for a limited time.
|
||||||
|
|
||||||
|
``` python hl_lines="3"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
|
||||||
|
rate: float, time_in_force: str, sell_reason: str,
|
||||||
|
current_time: datetime, **kwargs) -> bool:
|
||||||
|
return True
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="3"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
|
||||||
|
rate: float, time_in_force: str, exit_reason: str,
|
||||||
|
current_time: datetime, **kwargs) -> bool:
|
||||||
|
return True
|
||||||
|
```
|
||||||
|
|
||||||
|
### `custom_entry_price`
|
||||||
|
|
||||||
|
New string argument `side` - which can be either `"long"` or `"short"`.
|
||||||
|
|
||||||
|
``` python hl_lines="3"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
||||||
|
entry_tag: Optional[str], **kwargs) -> float:
|
||||||
|
return proposed_rate
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="3"
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
||||||
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
|
return proposed_rate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Adjust trade position changes
|
||||||
|
|
||||||
|
While adjust-trade-position itself did not change, you should no longer use `trade.nr_of_successful_buys` - and instead use `trade.nr_of_successful_entries`, which will also include short entries.
|
||||||
|
|
||||||
|
### Helper methods
|
||||||
|
|
||||||
|
Added argument "is_short" to `stoploss_from_open` and `stoploss_from_absolute`.
|
||||||
|
This should be given the value of `trade.is_short`.
|
||||||
|
|
||||||
|
``` python hl_lines="5 7"
|
||||||
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
|
current_rate: float, current_profit: float, **kwargs) -> float:
|
||||||
|
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
||||||
|
if current_profit > 0.10:
|
||||||
|
return stoploss_from_open(0.07, current_profit)
|
||||||
|
|
||||||
|
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate)
|
||||||
|
|
||||||
|
return 1
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="5 7"
|
||||||
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
|
current_rate: float, current_profit: float, **kwargs) -> float:
|
||||||
|
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
||||||
|
if current_profit > 0.10:
|
||||||
|
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short)
|
||||||
|
|
||||||
|
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short)
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Strategy/Configuration settings
|
||||||
|
|
||||||
|
#### `order_time_in_force`
|
||||||
|
|
||||||
|
`order_time_in_force` attributes changed from `"buy"` to `"entry"` and `"sell"` to `"exit"`.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
order_time_in_force: Dict = {
|
||||||
|
"buy": "gtc",
|
||||||
|
"sell": "gtc",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="2 3"
|
||||||
|
order_time_in_force: Dict = {
|
||||||
|
"entry": "gtc",
|
||||||
|
"exit": "gtc",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `order_types`
|
||||||
|
|
||||||
|
`order_types` have changed all wordings from `buy` to `entry` - and `sell` to `exit`.
|
||||||
|
And two words are joined with `_`.
|
||||||
|
|
||||||
|
``` python hl_lines="2-6"
|
||||||
|
order_types = {
|
||||||
|
"buy": "limit",
|
||||||
|
"sell": "limit",
|
||||||
|
"emergencysell": "market",
|
||||||
|
"forcesell": "market",
|
||||||
|
"forcebuy": "market",
|
||||||
|
"stoploss": "market",
|
||||||
|
"stoploss_on_exchange": false,
|
||||||
|
"stoploss_on_exchange_interval": 60
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="2-6"
|
||||||
|
order_types = {
|
||||||
|
"entry": "limit",
|
||||||
|
"exit": "limit",
|
||||||
|
"emergency_exit": "market",
|
||||||
|
"force_exit": "market",
|
||||||
|
"force_entry": "market",
|
||||||
|
"stoploss": "market",
|
||||||
|
"stoploss_on_exchange": false,
|
||||||
|
"stoploss_on_exchange_interval": 60
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Strategy level settings
|
||||||
|
|
||||||
|
* `use_sell_signal` -> `use_exit_signal`
|
||||||
|
* `sell_profit_only` -> `exit_profit_only`
|
||||||
|
* `sell_profit_offset` -> `exit_profit_offset`
|
||||||
|
* `ignore_roi_if_buy_signal` -> `ignore_roi_if_entry_signal`
|
||||||
|
|
||||||
|
``` python hl_lines="2-5"
|
||||||
|
# These values can be overridden in the config.
|
||||||
|
use_sell_signal = True
|
||||||
|
sell_profit_only = True
|
||||||
|
sell_profit_offset: 0.01
|
||||||
|
ignore_roi_if_buy_signal = False
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="2-5"
|
||||||
|
# These values can be overridden in the config.
|
||||||
|
use_exit_signal = True
|
||||||
|
exit_profit_only = True
|
||||||
|
exit_profit_offset: 0.01
|
||||||
|
ignore_roi_if_entry_signal = False
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `unfilledtimeout`
|
||||||
|
|
||||||
|
`unfilledtimeout` have changed all wordings from `buy` to `entry` - and `sell` to `exit`.
|
||||||
|
|
||||||
|
``` python hl_lines="2-3"
|
||||||
|
unfilledtimeout = {
|
||||||
|
"buy": 10,
|
||||||
|
"sell": 10,
|
||||||
|
"exit_timeout_count": 0,
|
||||||
|
"unit": "minutes"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
After:
|
||||||
|
|
||||||
|
``` python hl_lines="2-3"
|
||||||
|
unfilledtimeout = {
|
||||||
|
"entry": 10,
|
||||||
|
"exit": 10,
|
||||||
|
"exit_timeout_count": 0,
|
||||||
|
"unit": "minutes"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `order pricing`
|
||||||
|
|
||||||
|
Order pricing changed in 2 ways. `bid_strategy` was renamed to `entry_pricing` and `ask_strategy` was renamed to `exit_pricing`.
|
||||||
|
The attributes `ask_last_balance` -> `price_last_balance` and `bid_last_balance` -> `price_last_balance` were renamed as well.
|
||||||
|
Also, price-side can now be defined as `ask`, `bid`, `same` or `other`.
|
||||||
|
Please refer to the [pricing documentation](configuration.md#prices-used-for-orders) for more information.
|
||||||
|
|
||||||
|
``` json hl_lines="2-3 6 12-13 16"
|
||||||
|
{
|
||||||
|
"bid_strategy": {
|
||||||
|
"price_side": "bid",
|
||||||
|
"use_order_book": true,
|
||||||
|
"order_book_top": 1,
|
||||||
|
"ask_last_balance": 0.0,
|
||||||
|
"check_depth_of_market": {
|
||||||
|
"enabled": false,
|
||||||
|
"bids_to_ask_delta": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ask_strategy":{
|
||||||
|
"price_side": "ask",
|
||||||
|
"use_order_book": true,
|
||||||
|
"order_book_top": 1,
|
||||||
|
"bid_last_balance": 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
after:
|
||||||
|
|
||||||
|
``` json hl_lines="2-3 6 12-13 16"
|
||||||
|
{
|
||||||
|
"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,
|
||||||
|
"price_last_balance": 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
@ -81,21 +81,21 @@ Example configuration showing the different settings:
|
|||||||
"status": "silent",
|
"status": "silent",
|
||||||
"warning": "on",
|
"warning": "on",
|
||||||
"startup": "off",
|
"startup": "off",
|
||||||
"buy": "silent",
|
"entry": "silent",
|
||||||
"sell": {
|
"exit": {
|
||||||
"roi": "silent",
|
"roi": "silent",
|
||||||
"emergency_sell": "on",
|
"emergency_exit": "on",
|
||||||
"force_sell": "on",
|
"force_exit": "on",
|
||||||
"sell_signal": "silent",
|
"exit_signal": "silent",
|
||||||
"trailing_stop_loss": "on",
|
"trailing_stop_loss": "on",
|
||||||
"stop_loss": "on",
|
"stop_loss": "on",
|
||||||
"stoploss_on_exchange": "on",
|
"stoploss_on_exchange": "on",
|
||||||
"custom_sell": "silent"
|
"custom_exit": "silent"
|
||||||
},
|
},
|
||||||
"buy_cancel": "silent",
|
"entry_cancel": "silent",
|
||||||
"sell_cancel": "on",
|
"exit_cancel": "on",
|
||||||
"buy_fill": "off",
|
"entry_fill": "off",
|
||||||
"sell_fill": "off",
|
"exit_fill": "off",
|
||||||
"protection_trigger": "off",
|
"protection_trigger": "off",
|
||||||
"protection_trigger_global": "on"
|
"protection_trigger_global": "on"
|
||||||
},
|
},
|
||||||
@ -104,8 +104,8 @@ Example configuration showing the different settings:
|
|||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
`buy` notifications are sent when the order is placed, while `buy_fill` notifications are sent when the order is filled on the exchange.
|
`entry` notifications are sent when the order is placed, while `entry_fill` notifications are sent when the order is filled on the exchange.
|
||||||
`sell` notifications are sent when the order is placed, while `sell_fill` notifications are sent when the order is filled on the exchange.
|
`exit` notifications are sent when the order is placed, while `exit_fill` notifications are sent when the order is filled on the exchange.
|
||||||
`*_fill` notifications are off by default and must be explicitly enabled.
|
`*_fill` notifications are off by default and must be explicitly enabled.
|
||||||
`protection_trigger` notifications are sent when a protection triggers and `protection_trigger_global` notifications trigger when global protections are triggered.
|
`protection_trigger` notifications are sent when a protection triggers and `protection_trigger_global` notifications trigger when global protections are triggered.
|
||||||
|
|
||||||
@ -171,15 +171,19 @@ official commands. You can ask at any moment for help with `/help`.
|
|||||||
| `/locks` | Show currently locked pairs.
|
| `/locks` | Show currently locked pairs.
|
||||||
| `/unlock <pair or lock_id>` | Remove the lock for this pair (or for this lock id).
|
| `/unlock <pair or lock_id>` | Remove the lock for this pair (or for this lock id).
|
||||||
| `/profit [<n>]` | Display a summary of your profit/loss from close trades and some stats about your performance, over the last n days (all trades by default)
|
| `/profit [<n>]` | Display a summary of your profit/loss from close trades and some stats about your performance, over the last n days (all trades by default)
|
||||||
| `/forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`).
|
| `/forceexit <trade_id>` | Instantly exits the given trade (Ignoring `minimum_roi`).
|
||||||
| `/forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`).
|
| `/forceexit all` | Instantly exits all open trades (Ignoring `minimum_roi`).
|
||||||
| `/forcebuy <pair> [rate]` | Instantly buys the given pair. Rate is optional and only applies to limit orders. (`forcebuy_enable` must be set to True)
|
| `/fx` | alias for `/forceexit`
|
||||||
|
| `/forcelong <pair> [rate]` | Instantly buys the given pair. Rate is optional and only applies to limit orders. (`force_entry_enable` must be set to True)
|
||||||
|
| `/forceshort <pair> [rate]` | Instantly shorts the given pair. Rate is optional and only applies to limit orders. This will only work on non-spot markets. (`force_entry_enable` must be set to True)
|
||||||
| `/performance` | Show performance of each finished trade grouped by pair
|
| `/performance` | Show performance of each finished trade grouped by pair
|
||||||
| `/balance` | Show account balance per currency
|
| `/balance` | Show account balance per currency
|
||||||
| `/daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7)
|
| `/daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7)
|
||||||
| `/weekly <n>` | Shows profit or loss per week, over the last n weeks (n defaults to 8)
|
| `/weekly <n>` | Shows profit or loss per week, over the last n weeks (n defaults to 8)
|
||||||
| `/monthly <n>` | Shows profit or loss per month, over the last n months (n defaults to 6)
|
| `/monthly <n>` | Shows profit or loss per month, over the last n months (n defaults to 6)
|
||||||
| `/stats` | Shows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells
|
| `/stats` | Shows Wins / losses by Exit reason as well as Avg. holding durations for buys and sells
|
||||||
|
| `/exits` | Shows Wins / losses by Exit reason as well as Avg. holding durations for buys and sells
|
||||||
|
| `/entries` | Shows Wins / losses by Exit reason as well as Avg. holding durations for buys and sells
|
||||||
| `/whitelist` | Show the current whitelist
|
| `/whitelist` | Show the current whitelist
|
||||||
| `/blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
| `/blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||||
| `/edge` | Show validated pairs by Edge if it is enabled.
|
| `/edge` | Show validated pairs by Edge if it is enabled.
|
||||||
@ -216,11 +220,14 @@ Once all positions are sold, run `/stop` to completely stop the bot.
|
|||||||
### /status
|
### /status
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
> **Trade ID:** `123` `(since 1 days ago)`
|
> **Trade ID:** `123` `(since 1 days ago)`
|
||||||
> **Current Pair:** CVC/BTC
|
> **Current Pair:** CVC/BTC
|
||||||
> **Open Since:** `1 days ago`
|
> **Direction:** Long
|
||||||
|
> **Leverage:** 1.0
|
||||||
> **Amount:** `26.64180098`
|
> **Amount:** `26.64180098`
|
||||||
|
> **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%`
|
||||||
@ -231,10 +238,10 @@ For each open trade, the bot will send you the following message.
|
|||||||
Return the status of all open trades in a table format.
|
Return the status of all open trades in a table format.
|
||||||
|
|
||||||
```
|
```
|
||||||
ID Pair Since Profit
|
ID L/S Pair Since Profit
|
||||||
---- -------- ------- --------
|
---- -------- ------- --------
|
||||||
67 SC/BTC 1 d 13.33%
|
67 L SC/BTC 1 d 13.33%
|
||||||
123 CVC/BTC 1 h 12.95%
|
123 S CVC/BTC 1 h 12.95%
|
||||||
```
|
```
|
||||||
|
|
||||||
### /count
|
### /count
|
||||||
@ -268,22 +275,27 @@ 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.
|
||||||
|
|
||||||
### /forcesell <trade_id>
|
### /forceexit <trade_id>
|
||||||
|
|
||||||
> **BITTREX:** Selling BTC/LTC with limit `0.01650000 (profit: ~-4.07%, -0.00008168)`
|
> **BINANCE:** Exiting BTC/LTC with limit `0.01650000 (profit: ~-4.07%, -0.00008168)`
|
||||||
|
|
||||||
### /forcebuy <pair> [rate]
|
!!! Tip
|
||||||
|
You can get a list of all open trades by calling `/forceexit` without parameter, which will show a list of buttons to simply exit a trade.
|
||||||
|
|
||||||
> **BITTREX:** Buying ETH/BTC with limit `0.03400000` (`1.000000 ETH`, `225.290 USD`)
|
### /forcelong <pair> [rate] | /forceshort <pair> [rate]
|
||||||
|
|
||||||
Omitting the pair will open a query asking for the pair to buy (based on the current whitelist).
|
`/forcebuy <pair> [rate]` is also supported for longs but should be considered deprecated.
|
||||||
Trades crated through `/forcebuy` will have the buy-tag of `forceentry`.
|
|
||||||
|
> **BINANCE:** Long ETH/BTC with limit `0.03400000` (`1.000000 ETH`, `225.290 USD`)
|
||||||
|
|
||||||
|
Omitting the pair will open a query asking for the pair to trade (based on the current whitelist).
|
||||||
|
Trades created through `/forcelong` will have the buy-tag of `force_entry`.
|
||||||
|
|
||||||
![Telegram force-buy screenshot](assets/telegram_forcebuy.png)
|
![Telegram force-buy screenshot](assets/telegram_forcebuy.png)
|
||||||
|
|
||||||
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
Note that for this to work, `force_entry_enable` needs to be set to true.
|
||||||
|
|
||||||
[More details](configuration.md#understand-forcebuy_enable)
|
[More details](configuration.md#understand-force_entry_enable)
|
||||||
|
|
||||||
### /performance
|
### /performance
|
||||||
|
|
||||||
|
@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.
|
To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.
|
||||||
|
|
||||||
|
!!! Note "Tracking changes"
|
||||||
|
Breaking changes / changed behavior will be documented in the changelog that is posted alongside every release.
|
||||||
|
For the develop branch, please follow PR's to avoid being surprised by changes.
|
||||||
|
|
||||||
## docker-compose
|
## docker-compose
|
||||||
|
|
||||||
!!! Note "Legacy installations using the `master` image"
|
!!! Note "Legacy installations using the `master` image"
|
||||||
|
@ -439,14 +439,15 @@ usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
||||||
[--print-list] [--print-json] [-1] [--print-csv]
|
[--print-list] [--print-json] [-1] [--print-csv]
|
||||||
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||||
[-a]
|
[--trading-mode {spot,margin,futures}]
|
||||||
|
|
||||||
usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
||||||
[--print-list] [--print-json] [-1] [--print-csv]
|
[--print-list] [--print-json] [-1] [--print-csv]
|
||||||
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||||
|
[--trading-mode {spot,margin,futures}]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@ -463,6 +464,8 @@ optional arguments:
|
|||||||
Specify quote currency(-ies). Space-separated list.
|
Specify quote currency(-ies). Space-separated list.
|
||||||
-a, --all Print all pairs or market symbols. By default only
|
-a, --all Print all pairs or market symbols. By default only
|
||||||
active ones are shown.
|
active ones are shown.
|
||||||
|
--trading-mode {spot,margin,futures}
|
||||||
|
Select Trading mode
|
||||||
|
|
||||||
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).
|
||||||
|
@ -10,33 +10,33 @@ 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>/",
|
||||||
"webhookbuy": {
|
"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}"
|
||||||
},
|
},
|
||||||
"webhookbuycancel": {
|
"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}"
|
||||||
},
|
},
|
||||||
"webhookbuyfill": {
|
"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": ""
|
||||||
},
|
},
|
||||||
"webhooksell": {
|
"webhookexit": {
|
||||||
"value1": "Selling {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})"
|
||||||
},
|
},
|
||||||
"webhooksellcancel": {
|
"webhookexitcancel": {
|
||||||
"value1": "Cancelling Open Sell 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})"
|
||||||
},
|
},
|
||||||
"webhooksellfill": {
|
"webhookexitfill": {
|
||||||
"value1": "Sell Order for {pair} filled",
|
"value1": "Exit Order for {pair} filled",
|
||||||
"value2": "at {close_rate:8f}.",
|
"value2": "at {close_rate:8f}.",
|
||||||
"value3": ""
|
"value3": ""
|
||||||
},
|
},
|
||||||
@ -96,14 +96,16 @@ Optional parameters are available to enable automatic retries for webhook messag
|
|||||||
|
|
||||||
Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called.
|
Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called.
|
||||||
|
|
||||||
### Webhookbuy
|
### Webhookentry
|
||||||
|
|
||||||
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. 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`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
|
* `direction`
|
||||||
|
* `leverage`
|
||||||
* ~~`limit` # Deprecated - should no longer be used.~~
|
* ~~`limit` # Deprecated - should no longer be used.~~
|
||||||
* `open_rate`
|
* `open_rate`
|
||||||
* `amount`
|
* `amount`
|
||||||
@ -114,16 +116,18 @@ Possible parameters are:
|
|||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
* `current_rate`
|
* `current_rate`
|
||||||
* `buy_tag`
|
* `enter_tag`
|
||||||
|
|
||||||
### Webhookbuycancel
|
### Webhookentrycancel
|
||||||
|
|
||||||
The fields in `webhook.webhookbuycancel` are filled when the bot cancels a buy 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`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
|
* `direction`
|
||||||
|
* `leverage`
|
||||||
* `limit`
|
* `limit`
|
||||||
* `amount`
|
* `amount`
|
||||||
* `open_date`
|
* `open_date`
|
||||||
@ -133,16 +137,18 @@ Possible parameters are:
|
|||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
* `current_rate`
|
* `current_rate`
|
||||||
* `buy_tag`
|
* `enter_tag`
|
||||||
|
|
||||||
### Webhookbuyfill
|
### Webhookentryfill
|
||||||
|
|
||||||
The fields in `webhook.webhookbuyfill` are filled when the bot filled a buy 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`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
|
* `direction`
|
||||||
|
* `leverage`
|
||||||
* `open_rate`
|
* `open_rate`
|
||||||
* `amount`
|
* `amount`
|
||||||
* `open_date`
|
* `open_date`
|
||||||
@ -152,16 +158,18 @@ Possible parameters are:
|
|||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
* `current_rate`
|
* `current_rate`
|
||||||
* `buy_tag`
|
* `enter_tag`
|
||||||
|
|
||||||
### Webhooksell
|
### Webhookexit
|
||||||
|
|
||||||
The fields in `webhook.webhooksell` are filled when the bot sells 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`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
|
* `direction`
|
||||||
|
* `leverage`
|
||||||
* `gain`
|
* `gain`
|
||||||
* `limit`
|
* `limit`
|
||||||
* `amount`
|
* `amount`
|
||||||
@ -171,19 +179,21 @@ Possible parameters are:
|
|||||||
* `stake_currency`
|
* `stake_currency`
|
||||||
* `base_currency`
|
* `base_currency`
|
||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `sell_reason`
|
* `exit_reason`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
* `open_date`
|
* `open_date`
|
||||||
* `close_date`
|
* `close_date`
|
||||||
|
|
||||||
### Webhooksellfill
|
### Webhookexitfill
|
||||||
|
|
||||||
The fields in `webhook.webhooksellfill` are filled when the bot fills a sell order (closes a Trae). 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`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
|
* `direction`
|
||||||
|
* `leverage`
|
||||||
* `gain`
|
* `gain`
|
||||||
* `close_rate`
|
* `close_rate`
|
||||||
* `amount`
|
* `amount`
|
||||||
@ -194,19 +204,21 @@ Possible parameters are:
|
|||||||
* `stake_currency`
|
* `stake_currency`
|
||||||
* `base_currency`
|
* `base_currency`
|
||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `sell_reason`
|
* `exit_reason`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
* `open_date`
|
* `open_date`
|
||||||
* `close_date`
|
* `close_date`
|
||||||
|
|
||||||
### Webhooksellcancel
|
### Webhookexitcancel
|
||||||
|
|
||||||
The fields in `webhook.webhooksellcancel` are filled when the bot cancels a sell 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`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
|
* `direction`
|
||||||
|
* `leverage`
|
||||||
* `gain`
|
* `gain`
|
||||||
* `limit`
|
* `limit`
|
||||||
* `amount`
|
* `amount`
|
||||||
@ -217,7 +229,7 @@ Possible parameters are:
|
|||||||
* `stake_currency`
|
* `stake_currency`
|
||||||
* `base_currency`
|
* `base_currency`
|
||||||
* `fiat_currency`
|
* `fiat_currency`
|
||||||
* `sell_reason`
|
* `exit_reason`
|
||||||
* `order_type`
|
* `order_type`
|
||||||
* `open_date`
|
* `open_date`
|
||||||
* `close_date`
|
* `close_date`
|
||||||
|
@ -30,7 +30,9 @@ dependencies:
|
|||||||
- colorama
|
- colorama
|
||||||
- questionary
|
- questionary
|
||||||
- prompt-toolkit
|
- prompt-toolkit
|
||||||
|
- schedule
|
||||||
- python-dateutil
|
- python-dateutil
|
||||||
|
- joblib
|
||||||
|
|
||||||
|
|
||||||
# ============================
|
# ============================
|
||||||
@ -53,7 +55,6 @@ dependencies:
|
|||||||
- scikit-learn
|
- scikit-learn
|
||||||
- filelock
|
- filelock
|
||||||
- scikit-optimize
|
- scikit-optimize
|
||||||
- joblib
|
|
||||||
- progressbar2
|
- progressbar2
|
||||||
# ============================
|
# ============================
|
||||||
# 4/4 req plot
|
# 4/4 req plot
|
||||||
|
@ -11,4 +11,3 @@ Restart=on-failure
|
|||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=default.target
|
WantedBy=default.target
|
||||||
|
|
||||||
|
@ -27,4 +27,3 @@ WatchdogSec=20
|
|||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=default.target
|
WantedBy=default.target
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
""" Freqtrade bot """
|
""" Freqtrade bot """
|
||||||
__version__ = '2022.3'
|
__version__ = '2022.4'
|
||||||
|
|
||||||
if 'dev' in __version__:
|
if 'dev' in __version__:
|
||||||
try:
|
try:
|
||||||
|
@ -12,7 +12,7 @@ from freqtrade.constants import DEFAULT_CONFIG
|
|||||||
|
|
||||||
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||||
|
|
||||||
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
ARGS_STRATEGY = ["strategy", "strategy_path", "recursive_strategy_search"]
|
||||||
|
|
||||||
ARGS_TRADE = ["db_url", "sd_notify", "dry_run", "dry_run_wallet", "fee"]
|
ARGS_TRADE = ["db_url", "sd_notify", "dry_run", "dry_run_wallet", "fee"]
|
||||||
|
|
||||||
@ -37,7 +37,8 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
|||||||
|
|
||||||
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"]
|
||||||
|
|
||||||
ARGS_LIST_HYPEROPTS = ["hyperopt_path", "print_one_column", "print_colorized"]
|
ARGS_LIST_HYPEROPTS = ["hyperopt_path", "print_one_column", "print_colorized"]
|
||||||
|
|
||||||
@ -48,7 +49,8 @@ ARGS_LIST_EXCHANGES = ["print_one_column", "list_exchanges_all"]
|
|||||||
ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||||
|
|
||||||
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
||||||
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all"]
|
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all",
|
||||||
|
"trading_mode"]
|
||||||
|
|
||||||
ARGS_TEST_PAIRLIST = ["verbosity", "config", "quote_currencies", "print_one_column",
|
ARGS_TEST_PAIRLIST = ["verbosity", "config", "quote_currencies", "print_one_column",
|
||||||
"list_pairs_print_json", "exchange"]
|
"list_pairs_print_json", "exchange"]
|
||||||
@ -60,15 +62,17 @@ 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"]
|
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase"]
|
||||||
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes"]
|
|
||||||
|
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "exchange", "trading_mode",
|
||||||
|
"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"]
|
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",
|
||||||
"erase", "dataformat_ohlcv", "dataformat_trades"]
|
"erase", "dataformat_ohlcv", "dataformat_trades", "trading_mode"]
|
||||||
|
|
||||||
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
||||||
"db_url", "trade_source", "export", "exportfilename",
|
"db_url", "trade_source", "export", "exportfilename",
|
||||||
|
@ -104,7 +104,7 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
"type": "select",
|
"type": "select",
|
||||||
"name": "exchange_name",
|
"name": "exchange_name",
|
||||||
"message": "Select exchange",
|
"message": "Select exchange",
|
||||||
"choices": [
|
"choices": lambda x: [
|
||||||
"binance",
|
"binance",
|
||||||
"binanceus",
|
"binanceus",
|
||||||
"bittrex",
|
"bittrex",
|
||||||
@ -114,10 +114,18 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
"kraken",
|
"kraken",
|
||||||
"kucoin",
|
"kucoin",
|
||||||
"okx",
|
"okx",
|
||||||
Separator(),
|
Separator("------------------"),
|
||||||
"other",
|
"other",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"type": "confirm",
|
||||||
|
"name": "trading_mode",
|
||||||
|
"message": "Do you want to trade Perpetual Swaps (perpetual futures)?",
|
||||||
|
"default": False,
|
||||||
|
"filter": lambda val: 'futures' if val else 'spot',
|
||||||
|
"when": lambda x: x["exchange_name"] in ['binance', 'gateio', 'okx'],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"type": "autocomplete",
|
"type": "autocomplete",
|
||||||
"name": "exchange_name",
|
"name": "exchange_name",
|
||||||
@ -194,7 +202,13 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
if not answers:
|
if not answers:
|
||||||
# Interrupted questionary sessions return an empty dict.
|
# Interrupted questionary sessions return an empty dict.
|
||||||
raise OperationalException("User interrupted interactive questions.")
|
raise OperationalException("User interrupted interactive questions.")
|
||||||
|
# Ensure default is set for non-futures exchanges
|
||||||
|
answers['trading_mode'] = answers.get('trading_mode', "spot")
|
||||||
|
answers['margin_mode'] = (
|
||||||
|
'isolated'
|
||||||
|
if answers.get('trading_mode') == 'futures'
|
||||||
|
else ''
|
||||||
|
)
|
||||||
# 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()
|
||||||
|
|
||||||
|
@ -5,6 +5,7 @@ from argparse import SUPPRESS, ArgumentTypeError
|
|||||||
|
|
||||||
from freqtrade import __version__, constants
|
from freqtrade import __version__, constants
|
||||||
from freqtrade.constants import HYPEROPT_LOSS_BUILTIN
|
from freqtrade.constants import HYPEROPT_LOSS_BUILTIN
|
||||||
|
from freqtrade.enums import CandleType
|
||||||
|
|
||||||
|
|
||||||
def check_int_positive(value: str) -> int:
|
def check_int_positive(value: str) -> int:
|
||||||
@ -82,6 +83,11 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Reset sample files to their original state.',
|
help='Reset sample files to their original state.',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
|
"recursive_strategy_search": Arg(
|
||||||
|
'--recursive-strategy-search',
|
||||||
|
help='Recursively search for a strategy in the strategies folder.',
|
||||||
|
action='store_true',
|
||||||
|
),
|
||||||
# Main options
|
# Main options
|
||||||
"strategy": Arg(
|
"strategy": Arg(
|
||||||
'-s', '--strategy',
|
'-s', '--strategy',
|
||||||
@ -179,7 +185,6 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
'--export',
|
'--export',
|
||||||
help='Export backtest results (default: trades).',
|
help='Export backtest results (default: trades).',
|
||||||
choices=constants.EXPORT_OPTIONS,
|
choices=constants.EXPORT_OPTIONS,
|
||||||
|
|
||||||
),
|
),
|
||||||
"exportfilename": Arg(
|
"exportfilename": Arg(
|
||||||
"--export-filename",
|
"--export-filename",
|
||||||
@ -356,6 +361,17 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
nargs='+',
|
nargs='+',
|
||||||
metavar='BASE_CURRENCY',
|
metavar='BASE_CURRENCY',
|
||||||
),
|
),
|
||||||
|
"trading_mode": Arg(
|
||||||
|
'--trading-mode',
|
||||||
|
help='Select Trading mode',
|
||||||
|
choices=constants.TRADING_MODES,
|
||||||
|
),
|
||||||
|
"candle_types": Arg(
|
||||||
|
'--candle-types',
|
||||||
|
help='Select candle type to use',
|
||||||
|
choices=[c.value for c in CandleType],
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
# Script options
|
# Script options
|
||||||
"pairs": Arg(
|
"pairs": Arg(
|
||||||
'-p', '--pairs',
|
'-p', '--pairs',
|
||||||
|
@ -8,7 +8,7 @@ from freqtrade.configuration import TimeRange, setup_utils_configuration
|
|||||||
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 RunMode
|
from freqtrade.enums import CandleType, RunMode, TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
from freqtrade.exchange.exchange import market_is_active
|
from freqtrade.exchange.exchange import market_is_active
|
||||||
@ -64,6 +64,8 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
|||||||
try:
|
try:
|
||||||
|
|
||||||
if config.get('download_trades'):
|
if config.get('download_trades'):
|
||||||
|
if config.get('trading_mode') == 'futures':
|
||||||
|
raise OperationalException("Trade download not supported for futures.")
|
||||||
pairs_not_available = refresh_backtest_trades_data(
|
pairs_not_available = refresh_backtest_trades_data(
|
||||||
exchange, pairs=expanded_pairs, datadir=config['datadir'],
|
exchange, pairs=expanded_pairs, datadir=config['datadir'],
|
||||||
timerange=timerange, new_pairs_days=config['new_pairs_days'],
|
timerange=timerange, new_pairs_days=config['new_pairs_days'],
|
||||||
@ -81,7 +83,9 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
|||||||
exchange, pairs=expanded_pairs, timeframes=config['timeframes'],
|
exchange, pairs=expanded_pairs, timeframes=config['timeframes'],
|
||||||
datadir=config['datadir'], timerange=timerange,
|
datadir=config['datadir'], timerange=timerange,
|
||||||
new_pairs_days=config['new_pairs_days'],
|
new_pairs_days=config['new_pairs_days'],
|
||||||
erase=bool(config.get('erase')), data_format=config['dataformat_ohlcv'])
|
erase=bool(config.get('erase')), data_format=config['dataformat_ohlcv'],
|
||||||
|
trading_mode=config.get('trading_mode', 'spot'),
|
||||||
|
)
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
sys.exit("SIGINT received, aborting ...")
|
sys.exit("SIGINT received, aborting ...")
|
||||||
@ -133,9 +137,11 @@ def start_convert_data(args: Dict[str, Any], ohlcv: bool = True) -> None:
|
|||||||
"""
|
"""
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
if ohlcv:
|
if ohlcv:
|
||||||
convert_ohlcv_format(config,
|
candle_types = [CandleType.from_string(ct) for ct in config.get('candle_types', ['spot'])]
|
||||||
convert_from=args['format_from'], convert_to=args['format_to'],
|
for candle_type in candle_types:
|
||||||
erase=args['erase'])
|
convert_ohlcv_format(config,
|
||||||
|
convert_from=args['format_from'], convert_to=args['format_to'],
|
||||||
|
erase=args['erase'], candle_type=candle_type)
|
||||||
else:
|
else:
|
||||||
convert_trades_format(config,
|
convert_trades_format(config,
|
||||||
convert_from=args['format_from'], convert_to=args['format_to'],
|
convert_from=args['format_from'], convert_to=args['format_to'],
|
||||||
@ -154,17 +160,26 @@ def start_list_data(args: Dict[str, Any]) -> None:
|
|||||||
from freqtrade.data.history.idatahandler import get_datahandler
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
dhc = get_datahandler(config['datadir'], config['dataformat_ohlcv'])
|
dhc = get_datahandler(config['datadir'], config['dataformat_ohlcv'])
|
||||||
|
|
||||||
paircombs = dhc.ohlcv_get_available_data(config['datadir'])
|
paircombs = dhc.ohlcv_get_available_data(
|
||||||
|
config['datadir'],
|
||||||
|
config.get('trading_mode', TradingMode.SPOT)
|
||||||
|
)
|
||||||
|
|
||||||
if args['pairs']:
|
if args['pairs']:
|
||||||
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.")
|
||||||
groupedpair = defaultdict(list)
|
groupedpair = defaultdict(list)
|
||||||
for pair, timeframe in sorted(paircombs, key=lambda x: (x[0], timeframe_to_minutes(x[1]))):
|
for pair, timeframe, candle_type in sorted(
|
||||||
groupedpair[pair].append(timeframe)
|
paircombs,
|
||||||
|
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
|
||||||
|
):
|
||||||
|
groupedpair[(pair, candle_type)].append(timeframe)
|
||||||
|
|
||||||
if groupedpair:
|
if groupedpair:
|
||||||
print(tabulate([(pair, ', '.join(timeframes)) for pair, timeframes in groupedpair.items()],
|
print(tabulate([
|
||||||
headers=("Pair", "Timeframe"),
|
(pair, ', '.join(timeframes), candle_type)
|
||||||
tablefmt='psql', stralign='right'))
|
for (pair, candle_type), timeframes in groupedpair.items()
|
||||||
|
],
|
||||||
|
headers=("Pair", "Timeframe", "Type"),
|
||||||
|
tablefmt='psql', stralign='right'))
|
||||||
|
@ -41,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
|
||||||
@ -55,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'].name,
|
'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)
|
||||||
@ -77,7 +77,8 @@ 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))
|
directory = Path(config.get('strategy_path', config['user_data_dir'] / USERPATH_STRATEGIES))
|
||||||
strategy_objs = StrategyResolver.search_all_objects(directory, not args['print_one_column'])
|
strategy_objs = StrategyResolver.search_all_objects(
|
||||||
|
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:
|
||||||
@ -89,7 +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_timeframes(args: Dict[str, Any]) -> None:
|
def start_list_timeframes(args: Dict[str, Any]) -> None:
|
||||||
@ -131,7 +132,7 @@ def start_list_markets(args: Dict[str, Any], pairs_only: bool = False) -> None:
|
|||||||
try:
|
try:
|
||||||
pairs = exchange.get_markets(base_currencies=base_currencies,
|
pairs = exchange.get_markets(base_currencies=base_currencies,
|
||||||
quote_currencies=quote_currencies,
|
quote_currencies=quote_currencies,
|
||||||
pairs_only=pairs_only,
|
tradable_only=pairs_only,
|
||||||
active_only=active_only)
|
active_only=active_only)
|
||||||
# Sort the pairs/markets by symbol
|
# Sort the pairs/markets by symbol
|
||||||
pairs = dict(sorted(pairs.items()))
|
pairs = dict(sorted(pairs.items()))
|
||||||
@ -151,15 +152,19 @@ def start_list_markets(args: Dict[str, Any], pairs_only: bool = False) -> None:
|
|||||||
if quote_currencies else ""))
|
if quote_currencies else ""))
|
||||||
|
|
||||||
headers = ["Id", "Symbol", "Base", "Quote", "Active",
|
headers = ["Id", "Symbol", "Base", "Quote", "Active",
|
||||||
*(['Is pair'] if not pairs_only else [])]
|
"Spot", "Margin", "Future", "Leverage"]
|
||||||
|
|
||||||
tabular_data = []
|
tabular_data = [{
|
||||||
for _, v in pairs.items():
|
'Id': v['id'],
|
||||||
tabular_data.append({'Id': v['id'], 'Symbol': v['symbol'],
|
'Symbol': v['symbol'],
|
||||||
'Base': v['base'], 'Quote': v['quote'],
|
'Base': v['base'],
|
||||||
'Active': market_is_active(v),
|
'Quote': v['quote'],
|
||||||
**({'Is pair': exchange.market_is_tradable(v)}
|
'Active': market_is_active(v),
|
||||||
if not pairs_only else {})})
|
'Spot': 'Spot' if exchange.market_is_spot(v) else '',
|
||||||
|
'Margin': 'Margin' if exchange.market_is_margin(v) else '',
|
||||||
|
'Future': 'Future' if exchange.market_is_future(v) else '',
|
||||||
|
'Leverage': exchange.get_max_leverage(v['symbol'], 20)
|
||||||
|
} for _, v in pairs.items()]
|
||||||
|
|
||||||
if (args.get('print_one_column', False) or
|
if (args.get('print_one_column', False) or
|
||||||
args.get('list_pairs_print_json', False) or
|
args.get('list_pairs_print_json', False) or
|
||||||
|
@ -16,4 +16,4 @@ class PeriodicCache(TTLCache):
|
|||||||
return ts - offset
|
return ts - offset
|
||||||
|
|
||||||
# Init with smlight offset
|
# Init with smlight offset
|
||||||
super().__init__(maxsize=maxsize, ttl=ttl-1e-5, timer=local_timer, getsizeof=getsizeof)
|
super().__init__(maxsize=maxsize, ttl=ttl - 1e-5, timer=local_timer, getsizeof=getsizeof)
|
||||||
|
@ -22,6 +22,6 @@ def setup_utils_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str
|
|||||||
|
|
||||||
# Ensure these modes are using Dry-run
|
# Ensure these modes are using Dry-run
|
||||||
config['dry_run'] = True
|
config['dry_run'] = True
|
||||||
validate_config_consistency(config)
|
validate_config_consistency(config, preliminary=True)
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
@ -6,7 +6,8 @@ from jsonschema import Draft4Validator, validators
|
|||||||
from jsonschema.exceptions import ValidationError, best_match
|
from jsonschema.exceptions import ValidationError, best_match
|
||||||
|
|
||||||
from freqtrade import constants
|
from freqtrade import constants
|
||||||
from freqtrade.enums import RunMode
|
from freqtrade.configuration.deprecated_settings import process_deprecated_setting
|
||||||
|
from freqtrade.enums import RunMode, TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
@ -38,7 +39,7 @@ def _extend_validator(validator_class):
|
|||||||
FreqtradeValidator = _extend_validator(Draft4Validator)
|
FreqtradeValidator = _extend_validator(Draft4Validator)
|
||||||
|
|
||||||
|
|
||||||
def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
|
def validate_config_schema(conf: Dict[str, Any], preliminary: bool = False) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Validate the configuration follow the Config Schema
|
Validate the configuration follow the Config Schema
|
||||||
:param conf: Config in JSON format
|
:param conf: Config in JSON format
|
||||||
@ -48,7 +49,10 @@ def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
if conf.get('runmode', RunMode.OTHER) in (RunMode.DRY_RUN, RunMode.LIVE):
|
if conf.get('runmode', RunMode.OTHER) in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
conf_schema['required'] = constants.SCHEMA_TRADE_REQUIRED
|
conf_schema['required'] = constants.SCHEMA_TRADE_REQUIRED
|
||||||
elif conf.get('runmode', RunMode.OTHER) in (RunMode.BACKTEST, RunMode.HYPEROPT):
|
elif conf.get('runmode', RunMode.OTHER) in (RunMode.BACKTEST, RunMode.HYPEROPT):
|
||||||
conf_schema['required'] = constants.SCHEMA_BACKTEST_REQUIRED
|
if preliminary:
|
||||||
|
conf_schema['required'] = constants.SCHEMA_BACKTEST_REQUIRED
|
||||||
|
else:
|
||||||
|
conf_schema['required'] = constants.SCHEMA_BACKTEST_REQUIRED_FINAL
|
||||||
else:
|
else:
|
||||||
conf_schema['required'] = constants.SCHEMA_MINIMAL_REQUIRED
|
conf_schema['required'] = constants.SCHEMA_MINIMAL_REQUIRED
|
||||||
try:
|
try:
|
||||||
@ -63,7 +67,7 @@ def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
def validate_config_consistency(conf: Dict[str, Any], preliminary: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Validate the configuration consistency.
|
Validate the configuration consistency.
|
||||||
Should be ran after loading both configuration and strategy,
|
Should be ran after loading both configuration and strategy,
|
||||||
@ -80,10 +84,11 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
|||||||
_validate_protections(conf)
|
_validate_protections(conf)
|
||||||
_validate_unlimited_amount(conf)
|
_validate_unlimited_amount(conf)
|
||||||
_validate_ask_orderbook(conf)
|
_validate_ask_orderbook(conf)
|
||||||
|
validate_migrated_strategy_settings(conf)
|
||||||
|
|
||||||
# validate configuration before returning
|
# validate configuration before returning
|
||||||
logger.info('Validating configuration ...')
|
logger.info('Validating configuration ...')
|
||||||
validate_config_schema(conf)
|
validate_config_schema(conf, preliminary=preliminary)
|
||||||
|
|
||||||
|
|
||||||
def _validate_unlimited_amount(conf: Dict[str, Any]) -> None:
|
def _validate_unlimited_amount(conf: Dict[str, Any]) -> None:
|
||||||
@ -92,8 +97,8 @@ def _validate_unlimited_amount(conf: Dict[str, Any]) -> None:
|
|||||||
:raise: OperationalException if config validation failed
|
:raise: OperationalException if config validation failed
|
||||||
"""
|
"""
|
||||||
if (not conf.get('edge', {}).get('enabled')
|
if (not conf.get('edge', {}).get('enabled')
|
||||||
and conf.get('max_open_trades') == float('inf')
|
and conf.get('max_open_trades') == float('inf')
|
||||||
and conf.get('stake_amount') == constants.UNLIMITED_STAKE_AMOUNT):
|
and conf.get('stake_amount') == constants.UNLIMITED_STAKE_AMOUNT):
|
||||||
raise OperationalException("`max_open_trades` and `stake_amount` cannot both be unlimited.")
|
raise OperationalException("`max_open_trades` and `stake_amount` cannot both be unlimited.")
|
||||||
|
|
||||||
|
|
||||||
@ -101,13 +106,15 @@ def _validate_price_config(conf: Dict[str, Any]) -> None:
|
|||||||
"""
|
"""
|
||||||
When using market orders, price sides must be using the "other" side of the price
|
When using market orders, price sides must be using the "other" side of the price
|
||||||
"""
|
"""
|
||||||
if (conf.get('order_types', {}).get('buy') == 'market'
|
# TODO: The below could be an enforced setting when using market orders
|
||||||
and conf.get('bid_strategy', {}).get('price_side') != 'ask'):
|
if (conf.get('order_types', {}).get('entry') == 'market'
|
||||||
raise OperationalException('Market buy orders require bid_strategy.price_side = "ask".')
|
and conf.get('entry_pricing', {}).get('price_side') not in ('ask', 'other')):
|
||||||
|
raise OperationalException(
|
||||||
|
'Market entry orders require entry_pricing.price_side = "other".')
|
||||||
|
|
||||||
if (conf.get('order_types', {}).get('sell') == 'market'
|
if (conf.get('order_types', {}).get('exit') == 'market'
|
||||||
and conf.get('ask_strategy', {}).get('price_side') != 'bid'):
|
and conf.get('exit_pricing', {}).get('price_side') not in ('bid', 'other')):
|
||||||
raise OperationalException('Market sell orders require ask_strategy.price_side = "bid".')
|
raise OperationalException('Market exit orders require exit_pricing.price_side = "other".')
|
||||||
|
|
||||||
|
|
||||||
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
|
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
|
||||||
@ -150,9 +157,9 @@ def _validate_edge(conf: Dict[str, Any]) -> None:
|
|||||||
if not conf.get('edge', {}).get('enabled'):
|
if not conf.get('edge', {}).get('enabled'):
|
||||||
return
|
return
|
||||||
|
|
||||||
if not conf.get('use_sell_signal', True):
|
if not conf.get('use_exit_signal', True):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
"Edge requires `use_sell_signal` to be True, otherwise no sells will happen."
|
"Edge requires `use_exit_signal` to be True, otherwise no sells will happen."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -190,13 +197,13 @@ def _validate_protections(conf: Dict[str, Any]) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _validate_ask_orderbook(conf: Dict[str, Any]) -> None:
|
def _validate_ask_orderbook(conf: Dict[str, Any]) -> None:
|
||||||
ask_strategy = conf.get('ask_strategy', {})
|
ask_strategy = conf.get('exit_pricing', {})
|
||||||
ob_min = ask_strategy.get('order_book_min')
|
ob_min = ask_strategy.get('order_book_min')
|
||||||
ob_max = ask_strategy.get('order_book_max')
|
ob_max = ask_strategy.get('order_book_max')
|
||||||
if ob_min is not None and ob_max is not None and ask_strategy.get('use_order_book'):
|
if ob_min is not None and ob_max is not None and ask_strategy.get('use_order_book'):
|
||||||
if ob_min != ob_max:
|
if ob_min != ob_max:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
"Using order_book_max != order_book_min in ask_strategy is no longer supported."
|
"Using order_book_max != order_book_min in exit_pricing is no longer supported."
|
||||||
"Please pick one value and use `order_book_top` in the future."
|
"Please pick one value and use `order_book_top` in the future."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@ -205,5 +212,121 @@ def _validate_ask_orderbook(conf: Dict[str, Any]) -> None:
|
|||||||
logger.warning(
|
logger.warning(
|
||||||
"DEPRECATED: "
|
"DEPRECATED: "
|
||||||
"Please use `order_book_top` instead of `order_book_min` and `order_book_max` "
|
"Please use `order_book_top` instead of `order_book_min` and `order_book_max` "
|
||||||
"for your `ask_strategy` configuration."
|
"for your `exit_pricing` configuration."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_migrated_strategy_settings(conf: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
_validate_time_in_force(conf)
|
||||||
|
_validate_order_types(conf)
|
||||||
|
_validate_unfilledtimeout(conf)
|
||||||
|
_validate_pricing_rules(conf)
|
||||||
|
_strategy_settings(conf)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_time_in_force(conf: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
time_in_force = conf.get('order_time_in_force', {})
|
||||||
|
if 'buy' in time_in_force or 'sell' in time_in_force:
|
||||||
|
if conf.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT:
|
||||||
|
raise OperationalException(
|
||||||
|
"Please migrate your time_in_force settings to use 'entry' and 'exit'.")
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: Using 'buy' and 'sell' for time_in_force is deprecated."
|
||||||
|
"Please migrate your time_in_force settings to use 'entry' and 'exit'."
|
||||||
|
)
|
||||||
|
process_deprecated_setting(
|
||||||
|
conf, 'order_time_in_force', 'buy', 'order_time_in_force', 'entry')
|
||||||
|
|
||||||
|
process_deprecated_setting(
|
||||||
|
conf, 'order_time_in_force', 'sell', 'order_time_in_force', 'exit')
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_order_types(conf: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
order_types = conf.get('order_types', {})
|
||||||
|
old_order_types = ['buy', 'sell', 'emergencysell', 'forcebuy',
|
||||||
|
'forcesell', 'emergencyexit', 'forceexit', 'forceentry']
|
||||||
|
if any(x in order_types for x in old_order_types):
|
||||||
|
if conf.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT:
|
||||||
|
raise OperationalException(
|
||||||
|
"Please migrate your order_types settings to use the new wording.")
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: Using 'buy' and 'sell' for order_types is deprecated."
|
||||||
|
"Please migrate your order_types settings to use 'entry' and 'exit' wording."
|
||||||
|
)
|
||||||
|
for o, n in [
|
||||||
|
('buy', 'entry'),
|
||||||
|
('sell', 'exit'),
|
||||||
|
('emergencysell', 'emergency_exit'),
|
||||||
|
('forcesell', 'force_exit'),
|
||||||
|
('forcebuy', 'force_entry'),
|
||||||
|
('emergencyexit', 'emergency_exit'),
|
||||||
|
('forceexit', 'force_exit'),
|
||||||
|
('forceentry', 'force_entry'),
|
||||||
|
]:
|
||||||
|
|
||||||
|
process_deprecated_setting(conf, 'order_types', o, 'order_types', n)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_unfilledtimeout(conf: Dict[str, Any]) -> None:
|
||||||
|
unfilledtimeout = conf.get('unfilledtimeout', {})
|
||||||
|
if any(x in unfilledtimeout for x in ['buy', 'sell']):
|
||||||
|
if conf.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT:
|
||||||
|
raise OperationalException(
|
||||||
|
"Please migrate your unfilledtimeout settings to use the new wording.")
|
||||||
|
else:
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: Using 'buy' and 'sell' for unfilledtimeout is deprecated."
|
||||||
|
"Please migrate your unfilledtimeout settings to use 'entry' and 'exit' wording."
|
||||||
|
)
|
||||||
|
for o, n in [
|
||||||
|
('buy', 'entry'),
|
||||||
|
('sell', 'exit'),
|
||||||
|
]:
|
||||||
|
|
||||||
|
process_deprecated_setting(conf, 'unfilledtimeout', o, 'unfilledtimeout', n)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_pricing_rules(conf: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
if conf.get('ask_strategy') or conf.get('bid_strategy'):
|
||||||
|
if conf.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT:
|
||||||
|
raise OperationalException(
|
||||||
|
"Please migrate your pricing settings to use the new wording.")
|
||||||
|
else:
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: Using 'ask_strategy' and 'bid_strategy' is deprecated."
|
||||||
|
"Please migrate your settings to use 'entry_pricing' and 'exit_pricing'."
|
||||||
|
)
|
||||||
|
conf['entry_pricing'] = {}
|
||||||
|
for obj in list(conf.get('bid_strategy', {}).keys()):
|
||||||
|
if obj == 'ask_last_balance':
|
||||||
|
process_deprecated_setting(conf, 'bid_strategy', obj,
|
||||||
|
'entry_pricing', 'price_last_balance')
|
||||||
|
else:
|
||||||
|
process_deprecated_setting(conf, 'bid_strategy', obj, 'entry_pricing', obj)
|
||||||
|
del conf['bid_strategy']
|
||||||
|
|
||||||
|
conf['exit_pricing'] = {}
|
||||||
|
for obj in list(conf.get('ask_strategy', {}).keys()):
|
||||||
|
if obj == 'bid_last_balance':
|
||||||
|
process_deprecated_setting(conf, 'ask_strategy', obj,
|
||||||
|
'exit_pricing', 'price_last_balance')
|
||||||
|
else:
|
||||||
|
process_deprecated_setting(conf, 'ask_strategy', obj, 'exit_pricing', obj)
|
||||||
|
del conf['ask_strategy']
|
||||||
|
|
||||||
|
|
||||||
|
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, 'sell_profit_only', None, 'exit_profit_only')
|
||||||
|
process_deprecated_setting(conf, None, 'sell_profit_offset', None, 'exit_profit_offset')
|
||||||
|
process_deprecated_setting(conf, None, 'ignore_roi_if_buy_signal',
|
||||||
|
None, 'ignore_roi_if_entry_signal')
|
||||||
|
@ -12,8 +12,8 @@ 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_config_file, load_file
|
from freqtrade.configuration.load_config import load_file, load_from_files
|
||||||
from freqtrade.enums import NON_UTIL_MODES, TRADING_MODES, RunMode
|
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
|
||||||
from freqtrade.misc import deep_merge_dicts, parse_db_uri_for_logging
|
from freqtrade.misc import deep_merge_dicts, parse_db_uri_for_logging
|
||||||
@ -55,47 +55,28 @@ class Configuration:
|
|||||||
:param files: List of file paths
|
:param files: List of file paths
|
||||||
:return: configuration dictionary
|
:return: configuration dictionary
|
||||||
"""
|
"""
|
||||||
|
# Keep this method as staticmethod, so it can be used from interactive environments
|
||||||
c = Configuration({'config': files}, RunMode.OTHER)
|
c = Configuration({'config': files}, RunMode.OTHER)
|
||||||
return c.get_config()
|
return c.get_config()
|
||||||
|
|
||||||
def load_from_files(self, files: List[str]) -> Dict[str, Any]:
|
|
||||||
|
|
||||||
# Keep this method as staticmethod, so it can be used from interactive environments
|
|
||||||
config: Dict[str, Any] = {}
|
|
||||||
|
|
||||||
if not files:
|
|
||||||
return deepcopy(constants.MINIMAL_CONFIG)
|
|
||||||
|
|
||||||
# We expect here a list of config filenames
|
|
||||||
for path in files:
|
|
||||||
logger.info(f'Using config: {path} ...')
|
|
||||||
|
|
||||||
# Merge config options, overwriting old values
|
|
||||||
config = deep_merge_dicts(load_config_file(path), config)
|
|
||||||
|
|
||||||
# Load environment variables
|
|
||||||
env_data = enironment_vars_to_dict()
|
|
||||||
config = deep_merge_dicts(env_data, config)
|
|
||||||
|
|
||||||
config['config_files'] = files
|
|
||||||
# Normalize config
|
|
||||||
if 'internals' not in config:
|
|
||||||
config['internals'] = {}
|
|
||||||
if 'ask_strategy' not in config:
|
|
||||||
config['ask_strategy'] = {}
|
|
||||||
|
|
||||||
if 'pairlists' not in config:
|
|
||||||
config['pairlists'] = []
|
|
||||||
|
|
||||||
return config
|
|
||||||
|
|
||||||
def load_config(self) -> Dict[str, Any]:
|
def load_config(self) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Extract information for sys.argv and load the bot configuration
|
Extract information for sys.argv and load the bot configuration
|
||||||
:return: Configuration dictionary
|
:return: Configuration dictionary
|
||||||
"""
|
"""
|
||||||
# Load all configs
|
# Load all configs
|
||||||
config: Dict[str, Any] = self.load_from_files(self.args.get("config", []))
|
config: Dict[str, Any] = load_from_files(self.args.get("config", []))
|
||||||
|
|
||||||
|
# Load environment variables
|
||||||
|
env_data = enironment_vars_to_dict()
|
||||||
|
config = deep_merge_dicts(env_data, config)
|
||||||
|
|
||||||
|
# Normalize config
|
||||||
|
if 'internals' not in config:
|
||||||
|
config['internals'] = {}
|
||||||
|
|
||||||
|
if 'pairlists' not in config:
|
||||||
|
config['pairlists'] = []
|
||||||
|
|
||||||
# Keep a copy of the original configuration file
|
# Keep a copy of the original configuration file
|
||||||
config['original_config'] = deepcopy(config)
|
config['original_config'] = deepcopy(config)
|
||||||
@ -166,8 +147,8 @@ class Configuration:
|
|||||||
config.update({'db_url': self.args['db_url']})
|
config.update({'db_url': self.args['db_url']})
|
||||||
logger.info('Parameter --db-url detected ...')
|
logger.info('Parameter --db-url detected ...')
|
||||||
|
|
||||||
if config.get('forcebuy_enable', False):
|
if config.get('force_entry_enable', False):
|
||||||
logger.warning('`forcebuy` RPC message enabled.')
|
logger.warning('`force_entry_enable` RPC message enabled.')
|
||||||
|
|
||||||
# Support for sd_notify
|
# Support for sd_notify
|
||||||
if 'sd_notify' in self.args and self.args['sd_notify']:
|
if 'sd_notify' in self.args and self.args['sd_notify']:
|
||||||
@ -267,6 +248,12 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='strategy_list',
|
self._args_to_config(config, argname='strategy_list',
|
||||||
logstring='Using strategy list of {} strategies', logfun=len)
|
logstring='Using strategy list of {} strategies', logfun=len)
|
||||||
|
|
||||||
|
self._args_to_config(
|
||||||
|
config,
|
||||||
|
argname='recursive_strategy_search',
|
||||||
|
logstring='Recursively searching for a strategy in the strategies folder.',
|
||||||
|
)
|
||||||
|
|
||||||
self._args_to_config(config, argname='timeframe',
|
self._args_to_config(config, argname='timeframe',
|
||||||
logstring='Overriding timeframe with Command line argument')
|
logstring='Overriding timeframe with Command line argument')
|
||||||
|
|
||||||
@ -433,6 +420,13 @@ class Configuration:
|
|||||||
def _process_data_options(self, config: Dict[str, Any]) -> None:
|
def _process_data_options(self, config: Dict[str, Any]) -> 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',
|
||||||
|
logstring='Detected --trading-mode: {}')
|
||||||
|
config['candle_type_def'] = CandleType.get_default(
|
||||||
|
config.get('trading_mode', 'spot') or 'spot')
|
||||||
|
config['trading_mode'] = TradingMode(config.get('trading_mode', 'spot') or 'spot')
|
||||||
|
self._args_to_config(config, argname='candle_types',
|
||||||
|
logstring='Detected --candle-types: {}')
|
||||||
|
|
||||||
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
|
@ -12,14 +12,15 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
def check_conflicting_settings(config: Dict[str, Any],
|
def check_conflicting_settings(config: Dict[str, Any],
|
||||||
section_old: 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
|
||||||
section_old_config = config.get(section_old, {})
|
section_old_config = config.get(section_old, {}) if section_old else config
|
||||||
if name_new in section_new_config and name_old in section_old_config:
|
if name_new in section_new_config and name_old in section_old_config:
|
||||||
new_name = f"{section_new}.{name_new}" if section_new else f"{name_new}"
|
new_name = f"{section_new}.{name_new}" if section_new else f"{name_new}"
|
||||||
|
old_name = f"{section_old}.{name_old}" if section_old else f"{name_old}"
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
f"Conflicting settings `{new_name}` and `{section_old}.{name_old}` "
|
f"Conflicting settings `{new_name}` and `{old_name}` "
|
||||||
"(DEPRECATED) detected in the configuration file. "
|
"(DEPRECATED) detected in the configuration file. "
|
||||||
"This deprecated setting will be removed in the next versions of Freqtrade. "
|
"This deprecated setting will be removed in the next versions of Freqtrade. "
|
||||||
f"Please delete it from your configuration and use the `{new_name}` "
|
f"Please delete it from your configuration and use the `{new_name}` "
|
||||||
@ -47,23 +48,25 @@ def process_removed_setting(config: Dict[str, Any],
|
|||||||
|
|
||||||
|
|
||||||
def process_deprecated_setting(config: Dict[str, Any],
|
def process_deprecated_setting(config: Dict[str, Any],
|
||||||
section_old: 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:
|
||||||
check_conflicting_settings(config, section_old, name_old, section_new, name_new)
|
check_conflicting_settings(config, section_old, name_old, section_new, name_new)
|
||||||
section_old_config = config.get(section_old, {})
|
section_old_config = config.get(section_old, {}) if section_old else config
|
||||||
|
|
||||||
if name_old in section_old_config:
|
if name_old in section_old_config:
|
||||||
|
section_1 = f"{section_old}.{name_old}" if section_old else f"{name_old}"
|
||||||
section_2 = f"{section_new}.{name_new}" if section_new else f"{name_new}"
|
section_2 = f"{section_new}.{name_new}" if section_new else f"{name_new}"
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"DEPRECATED: "
|
"DEPRECATED: "
|
||||||
f"The `{section_old}.{name_old}` setting is deprecated and "
|
f"The `{section_1}` setting is deprecated and "
|
||||||
"will be removed in the next versions of Freqtrade. "
|
"will be removed in the next versions of Freqtrade. "
|
||||||
f"Please use the `{section_2}` setting in your configuration instead."
|
f"Please use the `{section_2}` setting in your configuration instead."
|
||||||
)
|
)
|
||||||
|
|
||||||
section_new_config = config.get(section_new, {}) if section_new else config
|
section_new_config = config.get(section_new, {}) if section_new else config
|
||||||
section_new_config[name_new] = section_old_config[name_old]
|
section_new_config[name_new] = section_old_config[name_old]
|
||||||
|
del section_old_config[name_old]
|
||||||
|
|
||||||
|
|
||||||
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||||
@ -71,25 +74,51 @@ 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',
|
||||||
# 'experimental', 'use_sell_signal')
|
# 'experimental', 'use_sell_signal')
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
|
||||||
None, 'use_sell_signal')
|
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_only',
|
|
||||||
None, 'sell_profit_only')
|
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_offset',
|
|
||||||
None, 'sell_profit_offset')
|
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
|
||||||
None, 'ignore_roi_if_buy_signal')
|
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'ignore_buying_expired_candle_after',
|
process_deprecated_setting(config, 'ask_strategy', 'ignore_buying_expired_candle_after',
|
||||||
None, 'ignore_buying_expired_candle_after')
|
None, 'ignore_buying_expired_candle_after')
|
||||||
|
|
||||||
# Legacy way - having them in experimental ...
|
process_deprecated_setting(config, None, 'forcebuy_enable', None, 'force_entry_enable')
|
||||||
process_removed_setting(config, 'experimental', 'use_sell_signal',
|
|
||||||
None, 'use_sell_signal')
|
|
||||||
process_removed_setting(config, 'experimental', 'sell_profit_only',
|
|
||||||
None, 'sell_profit_only')
|
|
||||||
process_removed_setting(config, 'experimental', 'ignore_roi_if_buy_signal',
|
|
||||||
None, 'ignore_roi_if_buy_signal')
|
|
||||||
|
|
||||||
|
# New settings
|
||||||
|
if config.get('telegram'):
|
||||||
|
process_deprecated_setting(config['telegram'], 'notification_settings', 'sell',
|
||||||
|
'notification_settings', 'exit')
|
||||||
|
process_deprecated_setting(config['telegram'], 'notification_settings', 'sell_fill',
|
||||||
|
'notification_settings', 'exit_fill')
|
||||||
|
process_deprecated_setting(config['telegram'], 'notification_settings', 'sell_cancel',
|
||||||
|
'notification_settings', 'exit_cancel')
|
||||||
|
process_deprecated_setting(config['telegram'], 'notification_settings', 'buy',
|
||||||
|
'notification_settings', 'entry')
|
||||||
|
process_deprecated_setting(config['telegram'], 'notification_settings', 'buy_fill',
|
||||||
|
'notification_settings', 'entry_fill')
|
||||||
|
process_deprecated_setting(config['telegram'], 'notification_settings', 'buy_cancel',
|
||||||
|
'notification_settings', 'entry_cancel')
|
||||||
|
if config.get('webhook'):
|
||||||
|
process_deprecated_setting(config, 'webhook', 'webhookbuy', 'webhook', 'webhookentry')
|
||||||
|
process_deprecated_setting(config, 'webhook', 'webhookbuycancel',
|
||||||
|
'webhook', 'webhookentrycancel')
|
||||||
|
process_deprecated_setting(config, 'webhook', 'webhookbuyfill',
|
||||||
|
'webhook', 'webhookentryfill')
|
||||||
|
process_deprecated_setting(config, 'webhook', 'webhooksell', 'webhook', 'webhookexit')
|
||||||
|
process_deprecated_setting(config, 'webhook', 'webhooksellcancel',
|
||||||
|
'webhook', 'webhookexitcancel')
|
||||||
|
process_deprecated_setting(config, 'webhook', 'webhooksellfill',
|
||||||
|
'webhook', 'webhookexitfill')
|
||||||
|
|
||||||
|
# Legacy way - having them in experimental ...
|
||||||
|
|
||||||
|
process_removed_setting(config, 'experimental', 'use_sell_signal', None, 'use_exit_signal')
|
||||||
|
process_removed_setting(config, 'experimental', 'sell_profit_only', None, 'exit_profit_only')
|
||||||
|
process_removed_setting(config, 'experimental', 'ignore_roi_if_buy_signal',
|
||||||
|
None, 'ignore_roi_if_entry_signal')
|
||||||
|
|
||||||
|
process_removed_setting(config, 'ask_strategy', 'use_sell_signal', None, 'exit_sell_signal')
|
||||||
|
process_removed_setting(config, 'ask_strategy', 'sell_profit_only', None, 'exit_profit_only')
|
||||||
|
process_removed_setting(config, 'ask_strategy', 'sell_profit_offset',
|
||||||
|
None, 'exit_profit_offset')
|
||||||
|
process_removed_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||||
|
None, 'ignore_roi_if_entry_signal')
|
||||||
if (config.get('edge', {}).get('enabled', False)
|
if (config.get('edge', {}).get('enabled', False)
|
||||||
and 'capital_available_percentage' in config.get('edge', {})):
|
and 'capital_available_percentage' in config.get('edge', {})):
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
|
@ -4,12 +4,15 @@ This module contain functions to load the configuration file
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
from copy import deepcopy
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
import rapidjson
|
import rapidjson
|
||||||
|
|
||||||
|
from freqtrade.constants import MINIMAL_CONFIG
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.misc import deep_merge_dicts
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -28,7 +31,7 @@ def log_config_error_range(path: str, errmsg: str) -> str:
|
|||||||
offset = int(offsetlist[0])
|
offset = int(offsetlist[0])
|
||||||
text = Path(path).read_text()
|
text = Path(path).read_text()
|
||||||
# Fetch an offset of 80 characters around the error line
|
# Fetch an offset of 80 characters around the error line
|
||||||
subtext = text[offset-min(80, offset):offset+80]
|
subtext = text[offset - min(80, offset):offset + 80]
|
||||||
segments = subtext.split('\n')
|
segments = subtext.split('\n')
|
||||||
if len(segments) > 3:
|
if len(segments) > 3:
|
||||||
# Remove first and last lines, to avoid odd truncations
|
# Remove first and last lines, to avoid odd truncations
|
||||||
@ -70,3 +73,43 @@ def load_config_file(path: str) -> Dict[str, Any]:
|
|||||||
)
|
)
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def load_from_files(files: List[str], base_path: Path = None, level: int = 0) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Recursively load configuration files if specified.
|
||||||
|
Sub-files are assumed to be relative to the initial config.
|
||||||
|
"""
|
||||||
|
config: Dict[str, Any] = {}
|
||||||
|
if level > 5:
|
||||||
|
raise OperationalException("Config loop detected.")
|
||||||
|
|
||||||
|
if not files:
|
||||||
|
return deepcopy(MINIMAL_CONFIG)
|
||||||
|
files_loaded = []
|
||||||
|
# We expect here a list of config filenames
|
||||||
|
for filename in files:
|
||||||
|
logger.info(f'Using config: {filename} ...')
|
||||||
|
if filename == '-':
|
||||||
|
# Immediately load stdin and return
|
||||||
|
return load_config_file(filename)
|
||||||
|
file = Path(filename)
|
||||||
|
if base_path:
|
||||||
|
# Prepend basepath to allow for relative assignments
|
||||||
|
file = base_path / file
|
||||||
|
|
||||||
|
config_tmp = load_config_file(str(file))
|
||||||
|
if 'add_config_files' in config_tmp:
|
||||||
|
config_sub = load_from_files(
|
||||||
|
config_tmp['add_config_files'], file.resolve().parent, level + 1)
|
||||||
|
files_loaded.extend(config_sub.get('config_files', []))
|
||||||
|
config_tmp = deep_merge_dicts(config_tmp, config_sub)
|
||||||
|
|
||||||
|
files_loaded.insert(0, str(file))
|
||||||
|
|
||||||
|
# Merge config options, overwriting prior values
|
||||||
|
config = deep_merge_dicts(config_tmp, config)
|
||||||
|
|
||||||
|
config['config_files'] = files_loaded
|
||||||
|
|
||||||
|
return config
|
||||||
|
@ -3,7 +3,9 @@
|
|||||||
"""
|
"""
|
||||||
bot constants
|
bot constants
|
||||||
"""
|
"""
|
||||||
from typing import List, Tuple
|
from typing import List, Literal, Tuple
|
||||||
|
|
||||||
|
from freqtrade.enums import CandleType
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_CONFIG = 'config.json'
|
DEFAULT_CONFIG = 'config.json'
|
||||||
@ -12,14 +14,14 @@ PROCESS_THROTTLE_SECS = 5 # sec
|
|||||||
HYPEROPT_EPOCH = 100 # epochs
|
HYPEROPT_EPOCH = 100 # epochs
|
||||||
RETRY_TIMEOUT = 30 # sec
|
RETRY_TIMEOUT = 30 # sec
|
||||||
TIMEOUT_UNITS = ['minutes', 'seconds']
|
TIMEOUT_UNITS = ['minutes', 'seconds']
|
||||||
EXPORT_OPTIONS = ['none', 'trades']
|
EXPORT_OPTIONS = ['none', 'trades', 'signals']
|
||||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||||
DEFAULT_DB_DRYRUN_URL = 'sqlite:///tradesv3.dryrun.sqlite'
|
DEFAULT_DB_DRYRUN_URL = 'sqlite:///tradesv3.dryrun.sqlite'
|
||||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||||
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
||||||
REQUIRED_ORDERTIF = ['buy', 'sell']
|
REQUIRED_ORDERTIF = ['entry', 'exit']
|
||||||
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
REQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']
|
||||||
ORDERBOOK_SIDES = ['ask', 'bid']
|
PRICING_SIDES = ['ask', 'bid', 'same', 'other']
|
||||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||||
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
||||||
@ -43,6 +45,8 @@ DEFAULT_DATAFRAME_COLUMNS = ['date', 'open', 'high', 'low', 'close', 'volume']
|
|||||||
# Don't modify sequence of DEFAULT_TRADES_COLUMNS
|
# Don't modify sequence of DEFAULT_TRADES_COLUMNS
|
||||||
# it has wide consequences for stored trades files
|
# it has wide consequences for stored trades files
|
||||||
DEFAULT_TRADES_COLUMNS = ['timestamp', 'id', 'type', 'side', 'price', 'amount', 'cost']
|
DEFAULT_TRADES_COLUMNS = ['timestamp', 'id', 'type', 'side', 'price', 'amount', 'cost']
|
||||||
|
TRADING_MODES = ['spot', 'margin', 'futures']
|
||||||
|
MARGIN_MODES = ['cross', 'isolated', '']
|
||||||
|
|
||||||
LAST_BT_RESULT_FN = '.last_result.json'
|
LAST_BT_RESULT_FN = '.last_result.json'
|
||||||
FTHYPT_FILEVERSION = 'fthypt_fileversion'
|
FTHYPT_FILEVERSION = 'fthypt_fileversion'
|
||||||
@ -82,20 +86,19 @@ SUPPORTED_FIAT = [
|
|||||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||||
"EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
|
"EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
|
||||||
"KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN",
|
"KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN",
|
||||||
"RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD",
|
"RUB", "UAH", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR",
|
||||||
"BTC", "ETH", "XRP", "LTC", "BCH"
|
"USD", "BTC", "ETH", "XRP", "LTC", "BCH"
|
||||||
]
|
]
|
||||||
|
|
||||||
MINIMAL_CONFIG = {
|
MINIMAL_CONFIG = {
|
||||||
'stake_currency': '',
|
"stake_currency": "",
|
||||||
'dry_run': True,
|
"dry_run": True,
|
||||||
'exchange': {
|
"exchange": {
|
||||||
'name': '',
|
"name": "",
|
||||||
'key': '',
|
"key": "",
|
||||||
'secret': '',
|
"secret": "",
|
||||||
'pair_whitelist': [],
|
"pair_whitelist": [],
|
||||||
'ccxt_async_config': {
|
"ccxt_async_config": {
|
||||||
'enableRateLimit': True,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -145,11 +148,14 @@ CONF_SCHEMA = {
|
|||||||
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||||
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
|
||||||
'trailing_only_offset_is_reached': {'type': 'boolean'},
|
'trailing_only_offset_is_reached': {'type': 'boolean'},
|
||||||
'use_sell_signal': {'type': 'boolean'},
|
'use_exit_signal': {'type': 'boolean'},
|
||||||
'sell_profit_only': {'type': 'boolean'},
|
'exit_profit_only': {'type': 'boolean'},
|
||||||
'sell_profit_offset': {'type': 'number'},
|
'exit_profit_offset': {'type': 'number'},
|
||||||
'ignore_roi_if_buy_signal': {'type': 'boolean'},
|
'ignore_roi_if_entry_signal': {'type': 'boolean'},
|
||||||
'ignore_buying_expired_candle_after': {'type': 'number'},
|
'ignore_buying_expired_candle_after': {'type': 'number'},
|
||||||
|
'trading_mode': {'type': 'string', 'enum': TRADING_MODES},
|
||||||
|
'margin_mode': {'type': 'string', 'enum': MARGIN_MODES},
|
||||||
|
'liquidation_buffer': {'type': 'number', 'minimum': 0.0, 'maximum': 0.99},
|
||||||
'backtest_breakdown': {
|
'backtest_breakdown': {
|
||||||
'type': 'array',
|
'type': 'array',
|
||||||
'items': {'type': 'string', 'enum': BACKTEST_BREAKDOWNS}
|
'items': {'type': 'string', 'enum': BACKTEST_BREAKDOWNS}
|
||||||
@ -158,22 +164,22 @@ CONF_SCHEMA = {
|
|||||||
'unfilledtimeout': {
|
'unfilledtimeout': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'buy': {'type': 'number', 'minimum': 1},
|
'entry': {'type': 'number', 'minimum': 1},
|
||||||
'sell': {'type': 'number', 'minimum': 1},
|
'exit': {'type': 'number', 'minimum': 1},
|
||||||
'exit_timeout_count': {'type': 'number', 'minimum': 0, 'default': 0},
|
'exit_timeout_count': {'type': 'number', 'minimum': 0, 'default': 0},
|
||||||
'unit': {'type': 'string', 'enum': TIMEOUT_UNITS, 'default': 'minutes'}
|
'unit': {'type': 'string', 'enum': TIMEOUT_UNITS, 'default': 'minutes'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'bid_strategy': {
|
'entry_pricing': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'ask_last_balance': {
|
'price_last_balance': {
|
||||||
'type': 'number',
|
'type': 'number',
|
||||||
'minimum': 0,
|
'minimum': 0,
|
||||||
'maximum': 1,
|
'maximum': 1,
|
||||||
'exclusiveMaximum': False,
|
'exclusiveMaximum': False,
|
||||||
},
|
},
|
||||||
'price_side': {'type': 'string', 'enum': ORDERBOOK_SIDES, 'default': 'bid'},
|
'price_side': {'type': 'string', 'enum': PRICING_SIDES, 'default': 'same'},
|
||||||
'use_order_book': {'type': 'boolean'},
|
'use_order_book': {'type': 'boolean'},
|
||||||
'order_book_top': {'type': 'integer', 'minimum': 1, 'maximum': 50, },
|
'order_book_top': {'type': 'integer', 'minimum': 1, 'maximum': 50, },
|
||||||
'check_depth_of_market': {
|
'check_depth_of_market': {
|
||||||
@ -186,11 +192,11 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'required': ['price_side']
|
'required': ['price_side']
|
||||||
},
|
},
|
||||||
'ask_strategy': {
|
'exit_pricing': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'price_side': {'type': 'string', 'enum': ORDERBOOK_SIDES, 'default': 'ask'},
|
'price_side': {'type': 'string', 'enum': PRICING_SIDES, 'default': 'same'},
|
||||||
'bid_last_balance': {
|
'price_last_balance': {
|
||||||
'type': 'number',
|
'type': 'number',
|
||||||
'minimum': 0,
|
'minimum': 0,
|
||||||
'maximum': 1,
|
'maximum': 1,
|
||||||
@ -207,11 +213,11 @@ CONF_SCHEMA = {
|
|||||||
'order_types': {
|
'order_types': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'buy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'entry': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'sell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'exit': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'forcesell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'force_exit': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'forcebuy': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'force_entry': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'emergencysell': {
|
'emergency_exit': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': ORDERTYPE_POSSIBILITIES,
|
'enum': ORDERTYPE_POSSIBILITIES,
|
||||||
'default': 'market'},
|
'default': 'market'},
|
||||||
@ -221,15 +227,15 @@ CONF_SCHEMA = {
|
|||||||
'stoploss_on_exchange_limit_ratio': {'type': 'number', 'minimum': 0.0,
|
'stoploss_on_exchange_limit_ratio': {'type': 'number', 'minimum': 0.0,
|
||||||
'maximum': 1.0}
|
'maximum': 1.0}
|
||||||
},
|
},
|
||||||
'required': ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
'required': ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']
|
||||||
},
|
},
|
||||||
'order_time_in_force': {
|
'order_time_in_force': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'buy': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES},
|
'entry': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES},
|
||||||
'sell': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES}
|
'exit': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES}
|
||||||
},
|
},
|
||||||
'required': ['buy', 'sell']
|
'required': REQUIRED_ORDERTIF
|
||||||
},
|
},
|
||||||
'exchange': {'$ref': '#/definitions/exchange'},
|
'exchange': {'$ref': '#/definitions/exchange'},
|
||||||
'edge': {'$ref': '#/definitions/edge'},
|
'edge': {'$ref': '#/definitions/edge'},
|
||||||
@ -278,21 +284,21 @@ CONF_SCHEMA = {
|
|||||||
'status': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'status': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'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},
|
||||||
'buy': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'entry': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'buy_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'entry_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'buy_fill': {'type': 'string',
|
'entry_fill': {'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
'default': 'off'
|
'default': 'off'
|
||||||
},
|
},
|
||||||
'sell': {
|
'exit': {
|
||||||
'type': ['string', 'object'],
|
'type': ['string', 'object'],
|
||||||
'additionalProperties': {
|
'additionalProperties': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS
|
'enum': TELEGRAM_SETTING_OPTIONS
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'sell_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
'exit_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
'sell_fill': {
|
'exit_fill': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'enum': TELEGRAM_SETTING_OPTIONS,
|
'enum': TELEGRAM_SETTING_OPTIONS,
|
||||||
'default': 'off'
|
'default': 'off'
|
||||||
@ -320,12 +326,12 @@ 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},
|
||||||
'webhookbuy': {'type': 'object'},
|
'webhookentry': {'type': 'object'},
|
||||||
'webhookbuycancel': {'type': 'object'},
|
'webhookentrycancel': {'type': 'object'},
|
||||||
'webhookbuyfill': {'type': 'object'},
|
'webhookentryfill': {'type': 'object'},
|
||||||
'webhooksell': {'type': 'object'},
|
'webhookexit': {'type': 'object'},
|
||||||
'webhooksellcancel': {'type': 'object'},
|
'webhookexitcancel': {'type': 'object'},
|
||||||
'webhooksellfill': {'type': 'object'},
|
'webhookexitfill': {'type': 'object'},
|
||||||
'webhookstatus': {'type': 'object'},
|
'webhookstatus': {'type': 'object'},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@ -351,7 +357,7 @@ CONF_SCHEMA = {
|
|||||||
'export': {'type': 'string', 'enum': EXPORT_OPTIONS, 'default': 'trades'},
|
'export': {'type': 'string', 'enum': EXPORT_OPTIONS, 'default': 'trades'},
|
||||||
'disableparamexport': {'type': 'boolean'},
|
'disableparamexport': {'type': 'boolean'},
|
||||||
'initial_state': {'type': 'string', 'enum': ['running', 'stopped']},
|
'initial_state': {'type': 'string', 'enum': ['running', 'stopped']},
|
||||||
'forcebuy_enable': {'type': 'boolean'},
|
'force_entry_enable': {'type': 'boolean'},
|
||||||
'disable_dataframe_checks': {'type': 'boolean'},
|
'disable_dataframe_checks': {'type': 'boolean'},
|
||||||
'internals': {
|
'internals': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
@ -438,8 +444,8 @@ SCHEMA_TRADE_REQUIRED = [
|
|||||||
'last_stake_amount_min_ratio',
|
'last_stake_amount_min_ratio',
|
||||||
'dry_run',
|
'dry_run',
|
||||||
'dry_run_wallet',
|
'dry_run_wallet',
|
||||||
'ask_strategy',
|
'exit_pricing',
|
||||||
'bid_strategy',
|
'entry_pricing',
|
||||||
'stoploss',
|
'stoploss',
|
||||||
'minimal_roi',
|
'minimal_roi',
|
||||||
'internals',
|
'internals',
|
||||||
@ -456,6 +462,10 @@ SCHEMA_BACKTEST_REQUIRED = [
|
|||||||
'dataformat_ohlcv',
|
'dataformat_ohlcv',
|
||||||
'dataformat_trades',
|
'dataformat_trades',
|
||||||
]
|
]
|
||||||
|
SCHEMA_BACKTEST_REQUIRED_FINAL = SCHEMA_BACKTEST_REQUIRED + [
|
||||||
|
'stoploss',
|
||||||
|
'minimal_roi',
|
||||||
|
]
|
||||||
|
|
||||||
SCHEMA_MINIMAL_REQUIRED = [
|
SCHEMA_MINIMAL_REQUIRED = [
|
||||||
'exchange',
|
'exchange',
|
||||||
@ -471,12 +481,15 @@ CANCEL_REASON = {
|
|||||||
"FULLY_CANCELLED": "fully cancelled",
|
"FULLY_CANCELLED": "fully cancelled",
|
||||||
"ALL_CANCELLED": "cancelled (all unfilled and partially filled open orders cancelled)",
|
"ALL_CANCELLED": "cancelled (all unfilled and partially filled open orders cancelled)",
|
||||||
"CANCELLED_ON_EXCHANGE": "cancelled on exchange",
|
"CANCELLED_ON_EXCHANGE": "cancelled on exchange",
|
||||||
"FORCE_SELL": "forcesold",
|
"FORCE_EXIT": "forcesold",
|
||||||
}
|
}
|
||||||
|
|
||||||
# List of pairs with their timeframes
|
# List of pairs with their timeframes
|
||||||
PairWithTimeframe = Tuple[str, str]
|
PairWithTimeframe = Tuple[str, str, CandleType]
|
||||||
ListPairsWithTimeframes = List[PairWithTimeframe]
|
ListPairsWithTimeframes = List[PairWithTimeframe]
|
||||||
|
|
||||||
# Type for trades list
|
# Type for trades list
|
||||||
TradeList = List[List]
|
TradeList = List[List]
|
||||||
|
|
||||||
|
LongShort = Literal['long', 'short']
|
||||||
|
EntryExit = Literal['entry', 'exit']
|
||||||
|
@ -5,14 +5,15 @@ import logging
|
|||||||
from copy import copy
|
from copy import copy
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
from typing import Any, Dict, List, Optional, Union
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from freqtrade.constants import LAST_BT_RESULT_FN
|
from freqtrade.constants import LAST_BT_RESULT_FN
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.misc import get_backtest_metadata_filename, json_load
|
from freqtrade.misc import json_load
|
||||||
|
from freqtrade.optimize.backtest_caching import get_backtest_metadata_filename
|
||||||
from freqtrade.persistence import LocalTrade, Trade, init_db
|
from freqtrade.persistence import LocalTrade, Trade, init_db
|
||||||
|
|
||||||
|
|
||||||
@ -22,9 +23,11 @@ logger = logging.getLogger(__name__)
|
|||||||
BT_DATA_COLUMNS = ['pair', 'stake_amount', 'amount', 'open_date', 'close_date',
|
BT_DATA_COLUMNS = ['pair', 'stake_amount', 'amount', 'open_date', 'close_date',
|
||||||
'open_rate', 'close_rate',
|
'open_rate', 'close_rate',
|
||||||
'fee_open', 'fee_close', 'trade_duration',
|
'fee_open', 'fee_close', 'trade_duration',
|
||||||
'profit_ratio', 'profit_abs', 'sell_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', 'buy_tag']
|
'stop_loss_ratio', 'min_rate', 'max_rate', 'is_open', 'enter_tag',
|
||||||
|
'is_short'
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str:
|
def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str:
|
||||||
@ -147,7 +150,14 @@ def load_backtest_stats(filename: Union[Path, str]) -> Dict[str, Any]:
|
|||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
def _load_and_merge_backtest_result(strategy_name: str, filename: Path, results: Dict[str, Any]):
|
def load_and_merge_backtest_result(strategy_name: str, filename: Path, results: Dict[str, Any]):
|
||||||
|
"""
|
||||||
|
Load one strategy from multi-strategy result
|
||||||
|
and merge it with results
|
||||||
|
:param strategy_name: Name of the strategy contained in the result
|
||||||
|
:param filename: Backtest-result-filename to load
|
||||||
|
:param results: dict to merge the result to.
|
||||||
|
"""
|
||||||
bt_data = load_backtest_stats(filename)
|
bt_data = load_backtest_stats(filename)
|
||||||
for k in ('metadata', 'strategy'):
|
for k in ('metadata', 'strategy'):
|
||||||
results[k][strategy_name] = bt_data[k][strategy_name]
|
results[k][strategy_name] = bt_data[k][strategy_name]
|
||||||
@ -158,6 +168,30 @@ def _load_and_merge_backtest_result(strategy_name: str, filename: Path, results:
|
|||||||
break
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def _get_backtest_files(dirname: Path) -> List[Path]:
|
||||||
|
return list(reversed(sorted(dirname.glob('backtest-result-*-[0-9][0-9].json'))))
|
||||||
|
|
||||||
|
|
||||||
|
def get_backtest_resultlist(dirname: Path):
|
||||||
|
"""
|
||||||
|
Get list of backtest results read from metadata files
|
||||||
|
"""
|
||||||
|
results = []
|
||||||
|
for filename in _get_backtest_files(dirname):
|
||||||
|
metadata = load_backtest_metadata(filename)
|
||||||
|
if not metadata:
|
||||||
|
continue
|
||||||
|
for s, v in metadata.items():
|
||||||
|
results.append({
|
||||||
|
'filename': filename.name,
|
||||||
|
'strategy': s,
|
||||||
|
'run_id': v['run_id'],
|
||||||
|
'backtest_start_time': v['backtest_start_time'],
|
||||||
|
|
||||||
|
})
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
def find_existing_backtest_stats(dirname: Union[Path, str], run_ids: Dict[str, str],
|
def find_existing_backtest_stats(dirname: Union[Path, str], run_ids: Dict[str, str],
|
||||||
min_backtest_date: datetime = None) -> Dict[str, Any]:
|
min_backtest_date: datetime = None) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
@ -177,7 +211,7 @@ def find_existing_backtest_stats(dirname: Union[Path, str], run_ids: Dict[str, s
|
|||||||
}
|
}
|
||||||
|
|
||||||
# Weird glob expression here avoids including .meta.json files.
|
# Weird glob expression here avoids including .meta.json files.
|
||||||
for filename in reversed(sorted(dirname.glob('backtest-result-*-[0-9][0-9].json'))):
|
for filename in _get_backtest_files(dirname):
|
||||||
metadata = load_backtest_metadata(filename)
|
metadata = load_backtest_metadata(filename)
|
||||||
if not metadata:
|
if not metadata:
|
||||||
# Files are sorted from newest to oldest. When file without metadata is encountered it
|
# Files are sorted from newest to oldest. When file without metadata is encountered it
|
||||||
@ -191,14 +225,7 @@ def find_existing_backtest_stats(dirname: Union[Path, str], run_ids: Dict[str, s
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
if min_backtest_date is not None:
|
if min_backtest_date is not None:
|
||||||
try:
|
backtest_date = strategy_metadata['backtest_start_time']
|
||||||
backtest_date = strategy_metadata['backtest_start_time']
|
|
||||||
except KeyError:
|
|
||||||
# TODO: this can be removed starting from feb 2022
|
|
||||||
# The metadata-file without start_time was only available in develop
|
|
||||||
# and was never included in an official release.
|
|
||||||
# Older metadata format without backtest time, too old to consider.
|
|
||||||
return results
|
|
||||||
backtest_date = datetime.fromtimestamp(backtest_date, tz=timezone.utc)
|
backtest_date = datetime.fromtimestamp(backtest_date, tz=timezone.utc)
|
||||||
if backtest_date < min_backtest_date:
|
if backtest_date < min_backtest_date:
|
||||||
# Do not use a cached result for this strategy as first result is too old.
|
# Do not use a cached result for this strategy as first result is too old.
|
||||||
@ -207,7 +234,7 @@ def find_existing_backtest_stats(dirname: Union[Path, str], run_ids: Dict[str, s
|
|||||||
|
|
||||||
if strategy_metadata['run_id'] == run_id:
|
if strategy_metadata['run_id'] == run_id:
|
||||||
del run_ids[strategy_name]
|
del run_ids[strategy_name]
|
||||||
_load_and_merge_backtest_result(strategy_name, filename, results)
|
load_and_merge_backtest_result(strategy_name, filename, results)
|
||||||
|
|
||||||
if len(run_ids) == 0:
|
if len(run_ids) == 0:
|
||||||
break
|
break
|
||||||
@ -250,6 +277,13 @@ def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = Non
|
|||||||
utc=True,
|
utc=True,
|
||||||
infer_datetime_format=True
|
infer_datetime_format=True
|
||||||
)
|
)
|
||||||
|
# Compatibility support for pre short Columns
|
||||||
|
if 'is_short' not in df.columns:
|
||||||
|
df['is_short'] = 0
|
||||||
|
if 'enter_tag' not in df.columns:
|
||||||
|
df['enter_tag'] = df['buy_tag']
|
||||||
|
df = df.drop(['buy_tag'], axis=1)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# old format - only with lists.
|
# old format - only with lists.
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
@ -366,157 +400,3 @@ def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame,
|
|||||||
trades = trades.loc[(trades['open_date'] >= trades_start) &
|
trades = trades.loc[(trades['open_date'] >= trades_start) &
|
||||||
(trades['close_date'] <= trades_stop)]
|
(trades['close_date'] <= trades_stop)]
|
||||||
return trades
|
return trades
|
||||||
|
|
||||||
|
|
||||||
def calculate_market_change(data: Dict[str, pd.DataFrame], column: str = "close") -> float:
|
|
||||||
"""
|
|
||||||
Calculate market change based on "column".
|
|
||||||
Calculation is done by taking the first non-null and the last non-null element of each column
|
|
||||||
and calculating the pctchange as "(last - first) / first".
|
|
||||||
Then the results per pair are combined as mean.
|
|
||||||
|
|
||||||
:param data: Dict of Dataframes, dict key should be pair.
|
|
||||||
:param column: Column in the original dataframes to use
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
tmp_means = []
|
|
||||||
for pair, df in data.items():
|
|
||||||
start = df[column].dropna().iloc[0]
|
|
||||||
end = df[column].dropna().iloc[-1]
|
|
||||||
tmp_means.append((end - start) / start)
|
|
||||||
|
|
||||||
return float(np.mean(tmp_means))
|
|
||||||
|
|
||||||
|
|
||||||
def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame],
|
|
||||||
column: str = "close") -> pd.DataFrame:
|
|
||||||
"""
|
|
||||||
Combine multiple dataframes "column"
|
|
||||||
:param data: Dict of Dataframes, dict key should be pair.
|
|
||||||
:param column: Column in the original dataframes to use
|
|
||||||
:return: DataFrame with the column renamed to the dict key, and a column
|
|
||||||
named mean, containing the mean of all pairs.
|
|
||||||
:raise: ValueError if no data is provided.
|
|
||||||
"""
|
|
||||||
df_comb = pd.concat([data[pair].set_index('date').rename(
|
|
||||||
{column: pair}, axis=1)[pair] for pair in data], axis=1)
|
|
||||||
|
|
||||||
df_comb['mean'] = df_comb.mean(axis=1)
|
|
||||||
|
|
||||||
return df_comb
|
|
||||||
|
|
||||||
|
|
||||||
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
|
||||||
timeframe: str) -> pd.DataFrame:
|
|
||||||
"""
|
|
||||||
Adds a column `col_name` with the cumulative profit for the given trades array.
|
|
||||||
:param df: DataFrame with date index
|
|
||||||
:param trades: DataFrame containing trades (requires columns close_date and profit_abs)
|
|
||||||
:param col_name: Column name that will be assigned the results
|
|
||||||
:param timeframe: Timeframe used during the operations
|
|
||||||
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
|
||||||
:raise: ValueError if trade-dataframe was found empty.
|
|
||||||
"""
|
|
||||||
if len(trades) == 0:
|
|
||||||
raise ValueError("Trade dataframe empty.")
|
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
|
||||||
timeframe_minutes = timeframe_to_minutes(timeframe)
|
|
||||||
# Resample to timeframe to make sure trades match candles
|
|
||||||
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_date'
|
|
||||||
)[['profit_abs']].sum()
|
|
||||||
df.loc[:, col_name] = _trades_sum['profit_abs'].cumsum()
|
|
||||||
# Set first value to 0
|
|
||||||
df.loc[df.iloc[0].name, col_name] = 0
|
|
||||||
# FFill to get continuous
|
|
||||||
df[col_name] = df[col_name].ffill()
|
|
||||||
return df
|
|
||||||
|
|
||||||
|
|
||||||
def _calc_drawdown_series(profit_results: pd.DataFrame, *, date_col: str, value_col: str
|
|
||||||
) -> pd.DataFrame:
|
|
||||||
max_drawdown_df = pd.DataFrame()
|
|
||||||
max_drawdown_df['cumulative'] = profit_results[value_col].cumsum()
|
|
||||||
max_drawdown_df['high_value'] = max_drawdown_df['cumulative'].cummax()
|
|
||||||
max_drawdown_df['drawdown'] = max_drawdown_df['cumulative'] - max_drawdown_df['high_value']
|
|
||||||
max_drawdown_df['date'] = profit_results.loc[:, date_col]
|
|
||||||
return max_drawdown_df
|
|
||||||
|
|
||||||
|
|
||||||
def calculate_underwater(trades: pd.DataFrame, *, date_col: str = 'close_date',
|
|
||||||
value_col: str = 'profit_ratio'
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Calculate max drawdown and the corresponding close dates
|
|
||||||
:param trades: DataFrame containing trades (requires columns close_date and profit_ratio)
|
|
||||||
:param date_col: Column in DataFrame to use for dates (defaults to 'close_date')
|
|
||||||
:param value_col: Column in DataFrame to use for values (defaults to 'profit_ratio')
|
|
||||||
:return: Tuple (float, highdate, lowdate, highvalue, lowvalue) with absolute max drawdown,
|
|
||||||
high and low time and high and low value.
|
|
||||||
:raise: ValueError if trade-dataframe was found empty.
|
|
||||||
"""
|
|
||||||
if len(trades) == 0:
|
|
||||||
raise ValueError("Trade dataframe empty.")
|
|
||||||
profit_results = trades.sort_values(date_col).reset_index(drop=True)
|
|
||||||
max_drawdown_df = _calc_drawdown_series(profit_results, date_col=date_col, value_col=value_col)
|
|
||||||
|
|
||||||
return max_drawdown_df
|
|
||||||
|
|
||||||
|
|
||||||
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date',
|
|
||||||
value_col: str = 'profit_abs', starting_balance: float = 0
|
|
||||||
) -> Tuple[float, pd.Timestamp, pd.Timestamp, float, float, float]:
|
|
||||||
"""
|
|
||||||
Calculate max drawdown and the corresponding close dates
|
|
||||||
:param trades: DataFrame containing trades (requires columns close_date and profit_ratio)
|
|
||||||
:param date_col: Column in DataFrame to use for dates (defaults to 'close_date')
|
|
||||||
:param value_col: Column in DataFrame to use for values (defaults to 'profit_abs')
|
|
||||||
:param starting_balance: Portfolio starting balance - properly calculate relative drawdown.
|
|
||||||
:return: Tuple (float, highdate, lowdate, highvalue, lowvalue, relative_drawdown)
|
|
||||||
with absolute max drawdown, high and low time and high and low value,
|
|
||||||
and the relative account drawdown
|
|
||||||
:raise: ValueError if trade-dataframe was found empty.
|
|
||||||
"""
|
|
||||||
if len(trades) == 0:
|
|
||||||
raise ValueError("Trade dataframe empty.")
|
|
||||||
profit_results = trades.sort_values(date_col).reset_index(drop=True)
|
|
||||||
max_drawdown_df = _calc_drawdown_series(profit_results, date_col=date_col, value_col=value_col)
|
|
||||||
|
|
||||||
idxmin = max_drawdown_df['drawdown'].idxmin()
|
|
||||||
if idxmin == 0:
|
|
||||||
raise ValueError("No losing trade, therefore no drawdown.")
|
|
||||||
high_date = profit_results.loc[max_drawdown_df.iloc[:idxmin]['high_value'].idxmax(), date_col]
|
|
||||||
low_date = profit_results.loc[idxmin, date_col]
|
|
||||||
high_val = max_drawdown_df.loc[max_drawdown_df.iloc[:idxmin]
|
|
||||||
['high_value'].idxmax(), 'cumulative']
|
|
||||||
low_val = max_drawdown_df.loc[idxmin, 'cumulative']
|
|
||||||
max_drawdown_rel = 0.0
|
|
||||||
if high_val + starting_balance != 0:
|
|
||||||
max_drawdown_rel = (high_val - low_val) / (high_val + starting_balance)
|
|
||||||
|
|
||||||
return (
|
|
||||||
abs(min(max_drawdown_df['drawdown'])),
|
|
||||||
high_date,
|
|
||||||
low_date,
|
|
||||||
high_val,
|
|
||||||
low_val,
|
|
||||||
max_drawdown_rel
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def calculate_csum(trades: pd.DataFrame, starting_balance: float = 0) -> Tuple[float, float]:
|
|
||||||
"""
|
|
||||||
Calculate min/max cumsum of trades, to show if the wallet/stake amount ratio is sane
|
|
||||||
:param trades: DataFrame containing trades (requires columns close_date and profit_percent)
|
|
||||||
:param starting_balance: Add starting balance to results, to show the wallets high / low points
|
|
||||||
:return: Tuple (float, float) with cumsum of profit_abs
|
|
||||||
:raise: ValueError if trade-dataframe was found empty.
|
|
||||||
"""
|
|
||||||
if len(trades) == 0:
|
|
||||||
raise ValueError("Trade dataframe empty.")
|
|
||||||
|
|
||||||
csum_df = pd.DataFrame()
|
|
||||||
csum_df['sum'] = trades['profit_abs'].cumsum()
|
|
||||||
csum_min = csum_df['sum'].min() + starting_balance
|
|
||||||
csum_max = csum_df['sum'].max() + starting_balance
|
|
||||||
|
|
||||||
return csum_min, csum_max
|
|
||||||
|
@ -11,6 +11,7 @@ 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, TradeList
|
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
|
||||||
|
from freqtrade.enums import CandleType
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -261,13 +262,20 @@ def convert_trades_format(config: Dict[str, Any], convert_from: str, convert_to:
|
|||||||
src.trades_purge(pair=pair)
|
src.trades_purge(pair=pair)
|
||||||
|
|
||||||
|
|
||||||
def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to: str, erase: bool):
|
def convert_ohlcv_format(
|
||||||
|
config: Dict[str, Any],
|
||||||
|
convert_from: str,
|
||||||
|
convert_to: str,
|
||||||
|
erase: bool,
|
||||||
|
candle_type: CandleType
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Convert OHLCV from one format to another
|
Convert OHLCV from one format to another
|
||||||
:param config: Config dictionary
|
:param config: Config dictionary
|
||||||
:param convert_from: Source format
|
:param convert_from: Source format
|
||||||
:param convert_to: Target format
|
:param convert_to: Target format
|
||||||
:param erase: Erase source data (does not apply if source and target format are identical)
|
:param erase: Erase source data (does not apply if source and target format are identical)
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
from freqtrade.data.history.idatahandler import get_datahandler
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
src = get_datahandler(config['datadir'], convert_from)
|
src = get_datahandler(config['datadir'], convert_from)
|
||||||
@ -279,8 +287,11 @@ def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to:
|
|||||||
config['pairs'] = []
|
config['pairs'] = []
|
||||||
# Check timeframes or fall back to timeframe.
|
# Check timeframes or fall back to timeframe.
|
||||||
for timeframe in timeframes:
|
for timeframe in timeframes:
|
||||||
config['pairs'].extend(src.ohlcv_get_pairs(config['datadir'],
|
config['pairs'].extend(src.ohlcv_get_pairs(
|
||||||
timeframe))
|
config['datadir'],
|
||||||
|
timeframe,
|
||||||
|
candle_type=candle_type
|
||||||
|
))
|
||||||
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:
|
||||||
@ -289,10 +300,16 @@ def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to:
|
|||||||
timerange=None,
|
timerange=None,
|
||||||
fill_missing=False,
|
fill_missing=False,
|
||||||
drop_incomplete=False,
|
drop_incomplete=False,
|
||||||
startup_candles=0)
|
startup_candles=0,
|
||||||
logger.info(f"Converting {len(data)} candles for {pair}")
|
candle_type=candle_type)
|
||||||
|
logger.info(f"Converting {len(data)} {candle_type} candles for {pair}")
|
||||||
if len(data) > 0:
|
if len(data) > 0:
|
||||||
trg.ohlcv_store(pair=pair, timeframe=timeframe, data=data)
|
trg.ohlcv_store(
|
||||||
|
pair=pair,
|
||||||
|
timeframe=timeframe,
|
||||||
|
data=data,
|
||||||
|
candle_type=candle_type
|
||||||
|
)
|
||||||
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)
|
src.ohlcv_purge(pair=pair, timeframe=timeframe, candle_type=candle_type)
|
||||||
|
@ -13,7 +13,7 @@ from pandas import DataFrame
|
|||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import 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 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
|
||||||
|
|
||||||
@ -41,7 +41,13 @@ class DataProvider:
|
|||||||
"""
|
"""
|
||||||
self.__slice_index = limit_index
|
self.__slice_index = limit_index
|
||||||
|
|
||||||
def _set_cached_df(self, pair: str, timeframe: str, dataframe: DataFrame) -> None:
|
def _set_cached_df(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str,
|
||||||
|
dataframe: DataFrame,
|
||||||
|
candle_type: CandleType
|
||||||
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Store cached Dataframe.
|
Store cached Dataframe.
|
||||||
Using private method as this should never be used by a user
|
Using private method as this should never be used by a user
|
||||||
@ -49,8 +55,10 @@ class DataProvider:
|
|||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param timeframe: Timeframe to get data for
|
:param timeframe: Timeframe to get data for
|
||||||
:param dataframe: analyzed dataframe
|
:param dataframe: analyzed dataframe
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
self.__cached_pairs[(pair, timeframe)] = (dataframe, datetime.now(timezone.utc))
|
self.__cached_pairs[(pair, timeframe, candle_type)] = (
|
||||||
|
dataframe, datetime.now(timezone.utc))
|
||||||
|
|
||||||
def add_pairlisthandler(self, pairlists) -> None:
|
def add_pairlisthandler(self, pairlists) -> None:
|
||||||
"""
|
"""
|
||||||
@ -58,13 +66,21 @@ class DataProvider:
|
|||||||
"""
|
"""
|
||||||
self._pairlists = pairlists
|
self._pairlists = pairlists
|
||||||
|
|
||||||
def historic_ohlcv(self, pair: str, timeframe: str = None) -> DataFrame:
|
def historic_ohlcv(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str = None,
|
||||||
|
candle_type: str = ''
|
||||||
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Get stored historical candle (OHLCV) data
|
Get stored historical candle (OHLCV) data
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param timeframe: timeframe to get data for
|
:param timeframe: timeframe to get data for
|
||||||
|
:param candle_type: '', mark, index, premiumIndex, or funding_rate
|
||||||
"""
|
"""
|
||||||
saved_pair = (pair, str(timeframe))
|
_candle_type = CandleType.from_string(
|
||||||
|
candle_type) if candle_type != '' else self._config['candle_type_def']
|
||||||
|
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')))
|
||||||
@ -77,26 +93,36 @@ class DataProvider:
|
|||||||
timeframe=timeframe or self._config['timeframe'],
|
timeframe=timeframe or self._config['timeframe'],
|
||||||
datadir=self._config['datadir'],
|
datadir=self._config['datadir'],
|
||||||
timerange=timerange,
|
timerange=timerange,
|
||||||
data_format=self._config.get('dataformat_ohlcv', 'json')
|
data_format=self._config.get('dataformat_ohlcv', 'json'),
|
||||||
|
candle_type=_candle_type,
|
||||||
|
|
||||||
)
|
)
|
||||||
return self.__cached_pairs_backtesting[saved_pair].copy()
|
return self.__cached_pairs_backtesting[saved_pair].copy()
|
||||||
|
|
||||||
def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame:
|
def get_pair_dataframe(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str = None,
|
||||||
|
candle_type: str = ''
|
||||||
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Return pair candle (OHLCV) data, either live or cached historical -- depending
|
Return pair candle (OHLCV) data, either live or cached historical -- depending
|
||||||
on the runmode.
|
on the runmode.
|
||||||
|
Only combinations in the pairlist or which have been specified as informative pairs
|
||||||
|
will be available.
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param timeframe: timeframe to get data for
|
:param timeframe: timeframe to get data for
|
||||||
:return: Dataframe for this pair
|
:return: Dataframe for this pair
|
||||||
|
:param candle_type: '', mark, index, premiumIndex, or funding_rate
|
||||||
"""
|
"""
|
||||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
# Get live OHLCV data.
|
# Get live OHLCV data.
|
||||||
data = self.ohlcv(pair=pair, timeframe=timeframe)
|
data = self.ohlcv(pair=pair, timeframe=timeframe, candle_type=candle_type)
|
||||||
else:
|
else:
|
||||||
# Get historical OHLCV data (cached on disk).
|
# Get historical OHLCV data (cached on disk).
|
||||||
data = self.historic_ohlcv(pair=pair, timeframe=timeframe)
|
data = self.historic_ohlcv(pair=pair, timeframe=timeframe, candle_type=candle_type)
|
||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
logger.warning(f"No data found for ({pair}, {timeframe}).")
|
logger.warning(f"No data found for ({pair}, {timeframe}, {candle_type}).")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def get_analyzed_dataframe(self, pair: str, timeframe: str) -> Tuple[DataFrame, datetime]:
|
def get_analyzed_dataframe(self, pair: str, timeframe: str) -> Tuple[DataFrame, datetime]:
|
||||||
@ -109,7 +135,7 @@ class DataProvider:
|
|||||||
combination.
|
combination.
|
||||||
Returns empty dataframe and Epoch 0 (1970-01-01) if no dataframe was cached.
|
Returns empty dataframe and Epoch 0 (1970-01-01) if no dataframe was cached.
|
||||||
"""
|
"""
|
||||||
pair_key = (pair, timeframe)
|
pair_key = (pair, timeframe, self._config.get('candle_type_def', CandleType.SPOT))
|
||||||
if pair_key in self.__cached_pairs:
|
if pair_key in self.__cached_pairs:
|
||||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
df, date = self.__cached_pairs[pair_key]
|
df, date = self.__cached_pairs[pair_key]
|
||||||
@ -177,20 +203,31 @@ class DataProvider:
|
|||||||
raise OperationalException(NO_EXCHANGE_EXCEPTION)
|
raise OperationalException(NO_EXCHANGE_EXCEPTION)
|
||||||
return list(self._exchange._klines.keys())
|
return list(self._exchange._klines.keys())
|
||||||
|
|
||||||
def ohlcv(self, pair: str, timeframe: str = None, copy: bool = True) -> DataFrame:
|
def ohlcv(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str = None,
|
||||||
|
copy: bool = True,
|
||||||
|
candle_type: str = ''
|
||||||
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Get candle (OHLCV) data for the given pair as DataFrame
|
Get candle (OHLCV) data for the given pair as DataFrame
|
||||||
Please use the `available_pairs` method to verify which pairs are currently cached.
|
Please use the `available_pairs` method to verify which pairs are currently cached.
|
||||||
:param pair: pair to get the data for
|
:param pair: pair to get the data for
|
||||||
:param timeframe: Timeframe to get data for
|
:param timeframe: Timeframe to get data for
|
||||||
|
:param candle_type: '', mark, index, premiumIndex, or funding_rate
|
||||||
:param copy: copy dataframe before returning if True.
|
:param copy: copy dataframe before returning if True.
|
||||||
Use False only for read-only operations (where the dataframe is not modified)
|
Use False only for read-only operations (where the dataframe is not modified)
|
||||||
"""
|
"""
|
||||||
if self._exchange is None:
|
if self._exchange is None:
|
||||||
raise OperationalException(NO_EXCHANGE_EXCEPTION)
|
raise OperationalException(NO_EXCHANGE_EXCEPTION)
|
||||||
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||||
return self._exchange.klines((pair, timeframe or self._config['timeframe']),
|
_candle_type = CandleType.from_string(
|
||||||
copy=copy)
|
candle_type) if candle_type != '' else self._config['candle_type_def']
|
||||||
|
return self._exchange.klines(
|
||||||
|
(pair, timeframe or self._config['timeframe'], _candle_type),
|
||||||
|
copy=copy
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
return DataFrame()
|
return DataFrame()
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ import pandas as pd
|
|||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS,
|
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS,
|
||||||
ListPairsWithTimeframes, TradeList)
|
ListPairsWithTimeframes, TradeList)
|
||||||
|
from freqtrade.enums import CandleType, TradingMode
|
||||||
|
|
||||||
from .idatahandler import IDataHandler
|
from .idatahandler import IDataHandler
|
||||||
|
|
||||||
@ -21,44 +22,63 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def ohlcv_get_available_data(cls, datadir: Path) -> ListPairsWithTimeframes:
|
def ohlcv_get_available_data(
|
||||||
|
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
|
||||||
"""
|
"""
|
||||||
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
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:param trading_mode: trading-mode to be used
|
||||||
:return: List of Tuples of (pair, timeframe)
|
:return: List of Tuples of (pair, timeframe)
|
||||||
"""
|
"""
|
||||||
_tmp = [re.search(r'^([a-zA-Z_]+)\-(\d+\S+)(?=.h5)', p.name)
|
if trading_mode == TradingMode.FUTURES:
|
||||||
for p in datadir.glob("*.h5")]
|
datadir = datadir.joinpath('futures')
|
||||||
return [(match[1].replace('_', '/'), match[2]) for match in _tmp
|
_tmp = [
|
||||||
if match and len(match.groups()) > 1]
|
re.search(
|
||||||
|
cls._OHLCV_REGEX, p.name
|
||||||
|
) for p in datadir.glob("*.h5")
|
||||||
|
]
|
||||||
|
return [
|
||||||
|
(
|
||||||
|
cls.rebuild_pair_from_filename(match[1]),
|
||||||
|
match[2],
|
||||||
|
CandleType.from_string(match[3])
|
||||||
|
) for match in _tmp if match and len(match.groups()) > 1]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str) -> 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
|
||||||
for the specified timeframe
|
for the specified timeframe
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
:param timeframe: Timeframe to search pairs for
|
:param timeframe: Timeframe to search pairs for
|
||||||
|
: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}"
|
||||||
|
|
||||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + '.h5)', p.name)
|
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + '.h5)', p.name)
|
||||||
for p in datadir.glob(f"*{timeframe}.h5")]
|
for p in datadir.glob(f"*{timeframe}{candle}.h5")]
|
||||||
# Check if regex found something and only return these results
|
# Check if regex found something and only return these results
|
||||||
return [match[0].replace('_', '/') for match in _tmp if match]
|
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||||
|
|
||||||
def ohlcv_store(self, pair: str, timeframe: str, data: pd.DataFrame) -> None:
|
def ohlcv_store(
|
||||||
|
self, pair: str, timeframe: str, data: pd.DataFrame, candle_type: CandleType) -> None:
|
||||||
"""
|
"""
|
||||||
Store data in hdf5 file.
|
Store data in hdf5 file.
|
||||||
:param pair: Pair - used to generate filename
|
:param pair: Pair - used to generate filename
|
||||||
:param timeframe: Timeframe - used to generate filename
|
:param timeframe: Timeframe - used to generate filename
|
||||||
:param data: Dataframe containing OHLCV data
|
:param data: Dataframe containing OHLCV data
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
key = self._pair_ohlcv_key(pair, timeframe)
|
key = self._pair_ohlcv_key(pair, timeframe)
|
||||||
_data = data.copy()
|
_data = data.copy()
|
||||||
|
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
||||||
|
self.create_dir_if_needed(filename)
|
||||||
|
|
||||||
_data.loc[:, self._columns].to_hdf(
|
_data.loc[:, self._columns].to_hdf(
|
||||||
filename, key, mode='a', complevel=9, complib='blosc',
|
filename, key, mode='a', complevel=9, complib='blosc',
|
||||||
@ -66,7 +86,8 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||||
timerange: Optional[TimeRange] = None) -> pd.DataFrame:
|
timerange: Optional[TimeRange], candle_type: CandleType
|
||||||
|
) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Internal method used to load data for one pair from disk.
|
Internal method used to load data for one pair from disk.
|
||||||
Implements the loading and conversion to a Pandas dataframe.
|
Implements the loading and conversion to a Pandas dataframe.
|
||||||
@ -76,10 +97,16 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
:param timerange: Limit data to be loaded to this timerange.
|
:param timerange: Limit data to be loaded to this timerange.
|
||||||
Optionally implemented by subclasses to avoid loading
|
Optionally implemented by subclasses to avoid loading
|
||||||
all data where possible.
|
all data where possible.
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
"""
|
"""
|
||||||
key = self._pair_ohlcv_key(pair, timeframe)
|
key = self._pair_ohlcv_key(pair, timeframe)
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
filename = self._pair_data_filename(
|
||||||
|
self._datadir,
|
||||||
|
pair,
|
||||||
|
timeframe,
|
||||||
|
candle_type=candle_type
|
||||||
|
)
|
||||||
|
|
||||||
if not filename.exists():
|
if not filename.exists():
|
||||||
return pd.DataFrame(columns=self._columns)
|
return pd.DataFrame(columns=self._columns)
|
||||||
@ -98,12 +125,19 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
'low': 'float', 'close': 'float', 'volume': 'float'})
|
||||||
return pairdata
|
return pairdata
|
||||||
|
|
||||||
def ohlcv_append(self, pair: str, timeframe: str, data: pd.DataFrame) -> None:
|
def ohlcv_append(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str,
|
||||||
|
data: pd.DataFrame,
|
||||||
|
candle_type: CandleType
|
||||||
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Append data to existing data structures
|
Append data to existing data structures
|
||||||
:param pair: Pair
|
:param pair: Pair
|
||||||
:param timeframe: Timeframe this ohlcv data is for
|
:param timeframe: Timeframe this ohlcv data is for
|
||||||
:param data: Data to append.
|
:param data: Data to append.
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
@ -117,7 +151,7 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
_tmp = [re.search(r'^(\S+)(?=\-trades.h5)', p.name)
|
_tmp = [re.search(r'^(\S+)(?=\-trades.h5)', p.name)
|
||||||
for p in datadir.glob("*trades.h5")]
|
for p in datadir.glob("*trades.h5")]
|
||||||
# Check if regex found something and only return these results to avoid exceptions.
|
# Check if regex found something and only return these results to avoid exceptions.
|
||||||
return [match[0].replace('_', '/') for match in _tmp if match]
|
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:
|
||||||
"""
|
"""
|
||||||
@ -172,7 +206,9 @@ class HDF5DataHandler(IDataHandler):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _pair_ohlcv_key(cls, pair: str, timeframe: str) -> str:
|
def _pair_ohlcv_key(cls, pair: str, timeframe: str) -> str:
|
||||||
return f"{pair}/ohlcv/tf_{timeframe}"
|
# Escape futures pairs to avoid warnings
|
||||||
|
pair_esc = pair.replace(':', '_')
|
||||||
|
return f"{pair_esc}/ohlcv/tf_{timeframe}"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _pair_trades_key(cls, pair: str) -> str:
|
def _pair_trades_key(cls, pair: str) -> str:
|
||||||
|
@ -12,6 +12,7 @@ from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
|||||||
from freqtrade.data.converter import (clean_ohlcv_dataframe, ohlcv_to_dataframe,
|
from freqtrade.data.converter import (clean_ohlcv_dataframe, ohlcv_to_dataframe,
|
||||||
trades_remove_duplicates, trades_to_ohlcv)
|
trades_remove_duplicates, trades_to_ohlcv)
|
||||||
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
||||||
|
from freqtrade.enums import CandleType
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.misc import format_ms_time
|
from freqtrade.misc import format_ms_time
|
||||||
@ -29,6 +30,7 @@ def load_pair_history(pair: str,
|
|||||||
startup_candles: int = 0,
|
startup_candles: int = 0,
|
||||||
data_format: str = None,
|
data_format: str = None,
|
||||||
data_handler: IDataHandler = None,
|
data_handler: IDataHandler = None,
|
||||||
|
candle_type: CandleType = CandleType.SPOT
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Load cached ohlcv history for the given pair.
|
Load cached ohlcv history for the given pair.
|
||||||
@ -43,6 +45,7 @@ def load_pair_history(pair: str,
|
|||||||
:param startup_candles: Additional candles to load at the start of the period
|
:param startup_candles: Additional candles to load at the start of the period
|
||||||
:param data_handler: Initialized data-handler to use.
|
:param data_handler: Initialized data-handler to use.
|
||||||
Will be initialized from data_format if not set
|
Will be initialized from data_format if not set
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
"""
|
"""
|
||||||
data_handler = get_datahandler(datadir, data_format, data_handler)
|
data_handler = get_datahandler(datadir, data_format, data_handler)
|
||||||
@ -53,6 +56,7 @@ def load_pair_history(pair: str,
|
|||||||
fill_missing=fill_up_missing,
|
fill_missing=fill_up_missing,
|
||||||
drop_incomplete=drop_incomplete,
|
drop_incomplete=drop_incomplete,
|
||||||
startup_candles=startup_candles,
|
startup_candles=startup_candles,
|
||||||
|
candle_type=candle_type
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -64,6 +68,7 @@ def load_data(datadir: Path,
|
|||||||
startup_candles: int = 0,
|
startup_candles: int = 0,
|
||||||
fail_without_data: bool = False,
|
fail_without_data: bool = False,
|
||||||
data_format: str = 'json',
|
data_format: str = 'json',
|
||||||
|
candle_type: CandleType = CandleType.SPOT
|
||||||
) -> Dict[str, DataFrame]:
|
) -> Dict[str, DataFrame]:
|
||||||
"""
|
"""
|
||||||
Load ohlcv history data for a list of pairs.
|
Load ohlcv history data for a list of pairs.
|
||||||
@ -76,6 +81,7 @@ def load_data(datadir: Path,
|
|||||||
:param startup_candles: Additional candles to load at the start of the period
|
:param startup_candles: Additional candles to load at the start of the period
|
||||||
:param fail_without_data: Raise OperationalException if no data is found.
|
:param fail_without_data: Raise OperationalException if no data is found.
|
||||||
:param data_format: Data format which should be used. Defaults to json
|
:param data_format: Data format which should be used. Defaults to json
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: dict(<pair>:<Dataframe>)
|
:return: dict(<pair>:<Dataframe>)
|
||||||
"""
|
"""
|
||||||
result: Dict[str, DataFrame] = {}
|
result: Dict[str, DataFrame] = {}
|
||||||
@ -89,7 +95,8 @@ def load_data(datadir: Path,
|
|||||||
datadir=datadir, timerange=timerange,
|
datadir=datadir, timerange=timerange,
|
||||||
fill_up_missing=fill_up_missing,
|
fill_up_missing=fill_up_missing,
|
||||||
startup_candles=startup_candles,
|
startup_candles=startup_candles,
|
||||||
data_handler=data_handler
|
data_handler=data_handler,
|
||||||
|
candle_type=candle_type
|
||||||
)
|
)
|
||||||
if not hist.empty:
|
if not hist.empty:
|
||||||
result[pair] = hist
|
result[pair] = hist
|
||||||
@ -99,12 +106,13 @@ def load_data(datadir: Path,
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def refresh_data(datadir: Path,
|
def refresh_data(*, datadir: Path,
|
||||||
timeframe: str,
|
timeframe: str,
|
||||||
pairs: List[str],
|
pairs: List[str],
|
||||||
exchange: Exchange,
|
exchange: Exchange,
|
||||||
data_format: str = None,
|
data_format: str = None,
|
||||||
timerange: Optional[TimeRange] = None,
|
timerange: Optional[TimeRange] = None,
|
||||||
|
candle_type: CandleType,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Refresh ohlcv history data for a list of pairs.
|
Refresh ohlcv history data for a list of pairs.
|
||||||
@ -115,17 +123,24 @@ def refresh_data(datadir: Path,
|
|||||||
:param exchange: Exchange object
|
:param exchange: Exchange object
|
||||||
:param data_format: dataformat to use
|
:param data_format: dataformat to use
|
||||||
:param timerange: Limit data to be loaded to this timerange
|
:param timerange: Limit data to be loaded to this timerange
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
data_handler = get_datahandler(datadir, data_format)
|
data_handler = get_datahandler(datadir, data_format)
|
||||||
for idx, pair in enumerate(pairs):
|
for idx, pair in enumerate(pairs):
|
||||||
process = f'{idx}/{len(pairs)}'
|
process = f'{idx}/{len(pairs)}'
|
||||||
_download_pair_history(pair=pair, process=process,
|
_download_pair_history(pair=pair, process=process,
|
||||||
timeframe=timeframe, datadir=datadir,
|
timeframe=timeframe, datadir=datadir,
|
||||||
timerange=timerange, exchange=exchange, data_handler=data_handler)
|
timerange=timerange, exchange=exchange, data_handler=data_handler,
|
||||||
|
candle_type=candle_type)
|
||||||
|
|
||||||
|
|
||||||
def _load_cached_data_for_updating(pair: str, timeframe: str, timerange: Optional[TimeRange],
|
def _load_cached_data_for_updating(
|
||||||
data_handler: IDataHandler) -> Tuple[DataFrame, Optional[int]]:
|
pair: str,
|
||||||
|
timeframe: str,
|
||||||
|
timerange: Optional[TimeRange],
|
||||||
|
data_handler: IDataHandler,
|
||||||
|
candle_type: CandleType
|
||||||
|
) -> Tuple[DataFrame, Optional[int]]:
|
||||||
"""
|
"""
|
||||||
Load cached data to download more data.
|
Load cached data to download more data.
|
||||||
If timerange is passed in, checks whether data from an before the stored data will be
|
If timerange is passed in, checks whether data from an before the stored data will be
|
||||||
@ -142,7 +157,8 @@ def _load_cached_data_for_updating(pair: str, timeframe: str, timerange: Optiona
|
|||||||
# 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,
|
||||||
timerange=None, fill_missing=False,
|
timerange=None, fill_missing=False,
|
||||||
drop_incomplete=True, warn_no_data=False)
|
drop_incomplete=True, warn_no_data=False,
|
||||||
|
candle_type=candle_type)
|
||||||
if not data.empty:
|
if not data.empty:
|
||||||
if start and start < data.iloc[0]['date']:
|
if start and start < data.iloc[0]['date']:
|
||||||
# Earlier data than existing data requested, redownload all
|
# Earlier data than existing data requested, redownload all
|
||||||
@ -161,7 +177,10 @@ def _download_pair_history(pair: str, *,
|
|||||||
process: str = '',
|
process: str = '',
|
||||||
new_pairs_days: int = 30,
|
new_pairs_days: int = 30,
|
||||||
data_handler: IDataHandler = None,
|
data_handler: IDataHandler = None,
|
||||||
timerange: Optional[TimeRange] = None) -> bool:
|
timerange: Optional[TimeRange] = None,
|
||||||
|
candle_type: CandleType,
|
||||||
|
erase: bool = False,
|
||||||
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Download latest candles from the exchange for the pair and timeframe passed in parameters
|
Download latest candles from the exchange for the pair and timeframe passed in parameters
|
||||||
The data is downloaded starting from the last correct data that
|
The data is downloaded starting from the last correct data that
|
||||||
@ -173,19 +192,25 @@ def _download_pair_history(pair: str, *,
|
|||||||
:param pair: pair to download
|
:param pair: pair to download
|
||||||
:param timeframe: Timeframe (e.g "5m")
|
:param timeframe: Timeframe (e.g "5m")
|
||||||
:param timerange: range of time to download
|
:param timerange: range of time to download
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
|
:param erase: Erase existing data
|
||||||
:return: bool with success state
|
:return: bool with success state
|
||||||
"""
|
"""
|
||||||
data_handler = get_datahandler(datadir, data_handler=data_handler)
|
data_handler = get_datahandler(datadir, data_handler=data_handler)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if erase:
|
||||||
|
if data_handler.ohlcv_purge(pair, timeframe, candle_type=candle_type):
|
||||||
|
logger.info(f'Deleting existing data for pair {pair}, {timeframe}, {candle_type}.')
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
f'Download history data for pair: "{pair}" ({process}), timeframe: {timeframe} '
|
f'Download history data for pair: "{pair}" ({process}), timeframe: {timeframe}, '
|
||||||
f'and store in {datadir}.'
|
f'candle type: {candle_type} and store in {datadir}.'
|
||||||
)
|
)
|
||||||
|
|
||||||
# data, since_ms = _load_cached_data_for_updating_old(datadir, pair, timeframe, timerange)
|
|
||||||
data, since_ms = _load_cached_data_for_updating(pair, timeframe, timerange,
|
data, since_ms = _load_cached_data_for_updating(pair, timeframe, timerange,
|
||||||
data_handler=data_handler)
|
data_handler=data_handler,
|
||||||
|
candle_type=candle_type)
|
||||||
|
|
||||||
logger.debug("Current Start: %s",
|
logger.debug("Current Start: %s",
|
||||||
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||||
@ -198,7 +223,8 @@ def _download_pair_history(pair: str, *,
|
|||||||
since_ms=since_ms if since_ms else
|
since_ms=since_ms if since_ms else
|
||||||
arrow.utcnow().shift(
|
arrow.utcnow().shift(
|
||||||
days=-new_pairs_days).int_timestamp * 1000,
|
days=-new_pairs_days).int_timestamp * 1000,
|
||||||
is_new_pair=data.empty
|
is_new_pair=data.empty,
|
||||||
|
candle_type=candle_type,
|
||||||
)
|
)
|
||||||
# TODO: Maybe move parsing to exchange class (?)
|
# TODO: Maybe move parsing to exchange class (?)
|
||||||
new_dataframe = ohlcv_to_dataframe(new_data, timeframe, pair,
|
new_dataframe = ohlcv_to_dataframe(new_data, timeframe, pair,
|
||||||
@ -216,7 +242,7 @@ def _download_pair_history(pair: str, *,
|
|||||||
logger.debug("New End: %s",
|
logger.debug("New End: %s",
|
||||||
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" 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)
|
data_handler.ohlcv_store(pair, timeframe, data=data, candle_type=candle_type)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -227,9 +253,11 @@ def _download_pair_history(pair: str, *,
|
|||||||
|
|
||||||
|
|
||||||
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
||||||
datadir: Path, timerange: Optional[TimeRange] = None,
|
datadir: Path, trading_mode: str,
|
||||||
|
timerange: Optional[TimeRange] = None,
|
||||||
new_pairs_days: int = 30, erase: bool = False,
|
new_pairs_days: int = 30, erase: bool = False,
|
||||||
data_format: str = None) -> List[str]:
|
data_format: str = None,
|
||||||
|
) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
||||||
Used by freqtrade download-data subcommand.
|
Used by freqtrade download-data subcommand.
|
||||||
@ -237,6 +265,7 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
|
|||||||
"""
|
"""
|
||||||
pairs_not_available = []
|
pairs_not_available = []
|
||||||
data_handler = get_datahandler(datadir, data_format)
|
data_handler = get_datahandler(datadir, data_format)
|
||||||
|
candle_type = CandleType.get_default(trading_mode)
|
||||||
for idx, pair in enumerate(pairs, start=1):
|
for idx, pair in enumerate(pairs, start=1):
|
||||||
if pair not in exchange.markets:
|
if pair not in exchange.markets:
|
||||||
pairs_not_available.append(pair)
|
pairs_not_available.append(pair)
|
||||||
@ -244,17 +273,29 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
|
|||||||
continue
|
continue
|
||||||
for timeframe in timeframes:
|
for timeframe in timeframes:
|
||||||
|
|
||||||
if erase:
|
|
||||||
if data_handler.ohlcv_purge(pair, timeframe):
|
|
||||||
logger.info(
|
|
||||||
f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
|
||||||
|
|
||||||
logger.info(f'Downloading pair {pair}, interval {timeframe}.')
|
logger.info(f'Downloading pair {pair}, interval {timeframe}.')
|
||||||
process = f'{idx}/{len(pairs)}'
|
process = f'{idx}/{len(pairs)}'
|
||||||
_download_pair_history(pair=pair, process=process,
|
_download_pair_history(pair=pair, process=process,
|
||||||
datadir=datadir, exchange=exchange,
|
datadir=datadir, exchange=exchange,
|
||||||
timerange=timerange, data_handler=data_handler,
|
timerange=timerange, data_handler=data_handler,
|
||||||
timeframe=str(timeframe), new_pairs_days=new_pairs_days)
|
timeframe=str(timeframe), new_pairs_days=new_pairs_days,
|
||||||
|
candle_type=candle_type,
|
||||||
|
erase=erase)
|
||||||
|
if trading_mode == 'futures':
|
||||||
|
# Predefined candletype (and timeframe) depending on exchange
|
||||||
|
# Downloads what is necessary to backtest based on futures data.
|
||||||
|
tf_mark = exchange._ft_has['mark_ohlcv_timeframe']
|
||||||
|
fr_candle_type = CandleType.from_string(exchange._ft_has['mark_ohlcv_price'])
|
||||||
|
# All exchanges need FundingRate for futures trading.
|
||||||
|
# The timeframe is aligned to the mark-price timeframe.
|
||||||
|
for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type):
|
||||||
|
_download_pair_history(pair=pair, process=process,
|
||||||
|
datadir=datadir, exchange=exchange,
|
||||||
|
timerange=timerange, data_handler=data_handler,
|
||||||
|
timeframe=str(tf_mark), new_pairs_days=new_pairs_days,
|
||||||
|
candle_type=funding_candle_type,
|
||||||
|
erase=erase)
|
||||||
|
|
||||||
return pairs_not_available
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
@ -353,10 +394,16 @@ def refresh_backtest_trades_data(exchange: Exchange, pairs: List[str], datadir:
|
|||||||
return pairs_not_available
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
def convert_trades_to_ohlcv(
|
||||||
datadir: Path, timerange: TimeRange, erase: bool = False,
|
pairs: List[str],
|
||||||
data_format_ohlcv: str = 'json',
|
timeframes: List[str],
|
||||||
data_format_trades: str = 'jsongz') -> None:
|
datadir: Path,
|
||||||
|
timerange: TimeRange,
|
||||||
|
erase: bool = False,
|
||||||
|
data_format_ohlcv: str = 'json',
|
||||||
|
data_format_trades: str = 'jsongz',
|
||||||
|
candle_type: CandleType = CandleType.SPOT
|
||||||
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Convert stored trades data to ohlcv data
|
Convert stored trades data to ohlcv data
|
||||||
"""
|
"""
|
||||||
@ -367,12 +414,12 @@ def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
|||||||
trades = data_handler_trades.trades_load(pair)
|
trades = data_handler_trades.trades_load(pair)
|
||||||
for timeframe in timeframes:
|
for timeframe in timeframes:
|
||||||
if erase:
|
if erase:
|
||||||
if data_handler_ohlcv.ohlcv_purge(pair, timeframe):
|
if data_handler_ohlcv.ohlcv_purge(pair, timeframe, candle_type=candle_type):
|
||||||
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
try:
|
try:
|
||||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||||
# Store ohlcv
|
# Store ohlcv
|
||||||
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv)
|
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv, candle_type=candle_type)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
logger.exception(f'Could not convert {pair} to OHLCV.')
|
logger.exception(f'Could not convert {pair} to OHLCV.')
|
||||||
|
|
||||||
|
@ -4,6 +4,7 @@ It's subclasses handle and storing data from disk.
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
from abc import ABC, abstractclassmethod, abstractmethod
|
from abc import ABC, abstractclassmethod, abstractmethod
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
@ -16,6 +17,7 @@ from freqtrade import misc
|
|||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import ListPairsWithTimeframes, TradeList
|
from freqtrade.constants import ListPairsWithTimeframes, TradeList
|
||||||
from freqtrade.data.converter import clean_ohlcv_dataframe, trades_remove_duplicates, trim_dataframe
|
from freqtrade.data.converter import clean_ohlcv_dataframe, trades_remove_duplicates, trim_dataframe
|
||||||
|
from freqtrade.enums import CandleType, TradingMode
|
||||||
from freqtrade.exchange import timeframe_to_seconds
|
from freqtrade.exchange import timeframe_to_seconds
|
||||||
|
|
||||||
|
|
||||||
@ -24,6 +26,8 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class IDataHandler(ABC):
|
class IDataHandler(ABC):
|
||||||
|
|
||||||
|
_OHLCV_REGEX = r'^([a-zA-Z_-]+)\-(\d+\S)\-?([a-zA-Z_]*)?(?=\.)'
|
||||||
|
|
||||||
def __init__(self, datadir: Path) -> None:
|
def __init__(self, datadir: Path) -> None:
|
||||||
self._datadir = datadir
|
self._datadir = datadir
|
||||||
|
|
||||||
@ -35,36 +39,41 @@ class IDataHandler(ABC):
|
|||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
@abstractclassmethod
|
@abstractclassmethod
|
||||||
def ohlcv_get_available_data(cls, datadir: Path) -> ListPairsWithTimeframes:
|
def ohlcv_get_available_data(
|
||||||
|
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
|
||||||
"""
|
"""
|
||||||
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
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:param trading_mode: trading-mode to be used
|
||||||
:return: List of Tuples of (pair, timeframe)
|
:return: List of Tuples of (pair, timeframe)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractclassmethod
|
@abstractclassmethod
|
||||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str) -> 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
|
||||||
for the specified timeframe
|
for the specified timeframe
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
:param timeframe: Timeframe to search pairs for
|
:param timeframe: Timeframe to search pairs for
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: List of Pairs
|
:return: List of Pairs
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def ohlcv_store(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
def ohlcv_store(
|
||||||
|
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
||||||
"""
|
"""
|
||||||
Store ohlcv data.
|
Store ohlcv data.
|
||||||
:param pair: Pair - used to generate filename
|
:param pair: Pair - used to generate filename
|
||||||
:param timeframe: Timeframe - used to generate filename
|
:param timeframe: Timeframe - used to generate filename
|
||||||
:param data: Dataframe containing OHLCV data
|
:param data: Dataframe containing OHLCV data
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange],
|
||||||
timerange: Optional[TimeRange] = None,
|
candle_type: CandleType
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Internal method used to load data for one pair from disk.
|
Internal method used to load data for one pair from disk.
|
||||||
@ -75,29 +84,38 @@ class IDataHandler(ABC):
|
|||||||
:param timerange: Limit data to be loaded to this timerange.
|
:param timerange: Limit data to be loaded to this timerange.
|
||||||
Optionally implemented by subclasses to avoid loading
|
Optionally implemented by subclasses to avoid loading
|
||||||
all data where possible.
|
all data where possible.
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def ohlcv_purge(self, pair: str, timeframe: str) -> bool:
|
def ohlcv_purge(self, pair: str, timeframe: str, candle_type: CandleType) -> bool:
|
||||||
"""
|
"""
|
||||||
Remove data for this pair
|
Remove data for this pair
|
||||||
:param pair: Delete data for this pair.
|
:param pair: Delete data for this pair.
|
||||||
:param timeframe: Timeframe (e.g. "5m")
|
:param timeframe: Timeframe (e.g. "5m")
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: True when deleted, false if file did not exist.
|
:return: True when deleted, false if file did not exist.
|
||||||
"""
|
"""
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
||||||
if filename.exists():
|
if filename.exists():
|
||||||
filename.unlink()
|
filename.unlink()
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def ohlcv_append(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
def ohlcv_append(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str,
|
||||||
|
data: DataFrame,
|
||||||
|
candle_type: CandleType
|
||||||
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Append data to existing data structures
|
Append data to existing data structures
|
||||||
:param pair: Pair
|
:param pair: Pair
|
||||||
:param timeframe: Timeframe this ohlcv data is for
|
:param timeframe: Timeframe this ohlcv data is for
|
||||||
:param data: Data to append.
|
:param data: Data to append.
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractclassmethod
|
@abstractclassmethod
|
||||||
@ -158,9 +176,29 @@ class IDataHandler(ABC):
|
|||||||
return trades_remove_duplicates(self._trades_load(pair, timerange=timerange))
|
return trades_remove_duplicates(self._trades_load(pair, timerange=timerange))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _pair_data_filename(cls, datadir: Path, pair: str, timeframe: str) -> Path:
|
def create_dir_if_needed(cls, datadir: Path):
|
||||||
|
"""
|
||||||
|
Creates datadir if necessary
|
||||||
|
should only create directories for "futures" mode at the moment.
|
||||||
|
"""
|
||||||
|
if not datadir.parent.is_dir():
|
||||||
|
datadir.parent.mkdir()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _pair_data_filename(
|
||||||
|
cls,
|
||||||
|
datadir: Path,
|
||||||
|
pair: str,
|
||||||
|
timeframe: str,
|
||||||
|
candle_type: CandleType
|
||||||
|
) -> Path:
|
||||||
pair_s = misc.pair_to_filename(pair)
|
pair_s = misc.pair_to_filename(pair)
|
||||||
filename = datadir.joinpath(f'{pair_s}-{timeframe}.{cls._get_file_extension()}')
|
candle = ""
|
||||||
|
if candle_type != CandleType.SPOT:
|
||||||
|
datadir = datadir.joinpath('futures')
|
||||||
|
candle = f"-{candle_type}"
|
||||||
|
filename = datadir.joinpath(
|
||||||
|
f'{pair_s}-{timeframe}{candle}.{cls._get_file_extension()}')
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -169,12 +207,23 @@ class IDataHandler(ABC):
|
|||||||
filename = datadir.joinpath(f'{pair_s}-trades.{cls._get_file_extension()}')
|
filename = datadir.joinpath(f'{pair_s}-trades.{cls._get_file_extension()}')
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def rebuild_pair_from_filename(pair: str) -> str:
|
||||||
|
"""
|
||||||
|
Rebuild pair name from filename
|
||||||
|
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]{1,10})|^([A-Za-z\-]{1,6}))(_)', r'\g<1>/', pair, 1)
|
||||||
|
res = re.sub('_', ':', res, 1)
|
||||||
|
return res
|
||||||
|
|
||||||
def ohlcv_load(self, pair, timeframe: str,
|
def ohlcv_load(self, pair, timeframe: str,
|
||||||
|
candle_type: CandleType,
|
||||||
timerange: Optional[TimeRange] = None,
|
timerange: Optional[TimeRange] = None,
|
||||||
fill_missing: bool = True,
|
fill_missing: bool = True,
|
||||||
drop_incomplete: bool = True,
|
drop_incomplete: bool = True,
|
||||||
startup_candles: int = 0,
|
startup_candles: int = 0,
|
||||||
warn_no_data: bool = True
|
warn_no_data: bool = True,
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Load cached candle (OHLCV) data for the given pair.
|
Load cached candle (OHLCV) data for the given pair.
|
||||||
@ -186,6 +235,7 @@ class IDataHandler(ABC):
|
|||||||
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||||
:param startup_candles: Additional candles to load at the start of the period
|
:param startup_candles: Additional candles to load at the start of the period
|
||||||
:param warn_no_data: Log a warning message when no data is found
|
:param warn_no_data: Log a warning message when no data is found
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
"""
|
"""
|
||||||
# Fix startup period
|
# Fix startup period
|
||||||
@ -193,17 +243,21 @@ class IDataHandler(ABC):
|
|||||||
if startup_candles > 0 and timerange_startup:
|
if startup_candles > 0 and timerange_startup:
|
||||||
timerange_startup.subtract_start(timeframe_to_seconds(timeframe) * startup_candles)
|
timerange_startup.subtract_start(timeframe_to_seconds(timeframe) * startup_candles)
|
||||||
|
|
||||||
pairdf = self._ohlcv_load(pair, timeframe,
|
pairdf = self._ohlcv_load(
|
||||||
timerange=timerange_startup)
|
pair,
|
||||||
if self._check_empty_df(pairdf, pair, timeframe, warn_no_data):
|
timeframe,
|
||||||
|
timerange=timerange_startup,
|
||||||
|
candle_type=candle_type
|
||||||
|
)
|
||||||
|
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']
|
||||||
|
|
||||||
if timerange_startup:
|
if timerange_startup:
|
||||||
self._validate_pairdata(pair, pairdf, timeframe, timerange_startup)
|
self._validate_pairdata(pair, pairdf, timeframe, candle_type, timerange_startup)
|
||||||
pairdf = trim_dataframe(pairdf, timerange_startup)
|
pairdf = trim_dataframe(pairdf, timerange_startup)
|
||||||
if self._check_empty_df(pairdf, pair, timeframe, warn_no_data):
|
if self._check_empty_df(pairdf, pair, timeframe, candle_type, warn_no_data):
|
||||||
return pairdf
|
return pairdf
|
||||||
|
|
||||||
# incomplete candles should only be dropped if we didn't trim the end beforehand.
|
# incomplete candles should only be dropped if we didn't trim the end beforehand.
|
||||||
@ -212,23 +266,25 @@ class IDataHandler(ABC):
|
|||||||
fill_missing=fill_missing,
|
fill_missing=fill_missing,
|
||||||
drop_incomplete=(drop_incomplete and
|
drop_incomplete=(drop_incomplete and
|
||||||
enddate == pairdf.iloc[-1]['date']))
|
enddate == pairdf.iloc[-1]['date']))
|
||||||
self._check_empty_df(pairdf, pair, timeframe, warn_no_data)
|
self._check_empty_df(pairdf, pair, timeframe, candle_type, warn_no_data)
|
||||||
return pairdf
|
return pairdf
|
||||||
|
|
||||||
def _check_empty_df(self, pairdf: DataFrame, pair: str, timeframe: str, warn_no_data: bool):
|
def _check_empty_df(self, pairdf: DataFrame, pair: str, timeframe: str,
|
||||||
|
candle_type: CandleType, warn_no_data: bool):
|
||||||
"""
|
"""
|
||||||
Warn on empty dataframe
|
Warn on empty dataframe
|
||||||
"""
|
"""
|
||||||
if pairdf.empty:
|
if pairdf.empty:
|
||||||
if warn_no_data:
|
if warn_no_data:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'No history data for pair: "{pair}", timeframe: {timeframe}. '
|
f"No history for {pair}, {candle_type}, {timeframe} found. "
|
||||||
'Use `freqtrade download-data` to download the data'
|
"Use `freqtrade download-data` to download the data"
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _validate_pairdata(self, pair, pairdata: DataFrame, timeframe: str, timerange: TimeRange):
|
def _validate_pairdata(self, pair, pairdata: DataFrame, timeframe: str,
|
||||||
|
candle_type: CandleType, timerange: TimeRange):
|
||||||
"""
|
"""
|
||||||
Validates pairdata for missing data at start end end and logs warnings.
|
Validates pairdata for missing data at start end end and logs warnings.
|
||||||
:param pairdata: Dataframe to validate
|
:param pairdata: Dataframe to validate
|
||||||
@ -238,12 +294,12 @@ class IDataHandler(ABC):
|
|||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||||
if pairdata.iloc[0]['date'] > start:
|
if pairdata.iloc[0]['date'] > start:
|
||||||
logger.warning(f"Missing data at start for pair {pair} at {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':
|
||||||
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||||
if pairdata.iloc[-1]['date'] < stop:
|
if pairdata.iloc[-1]['date'] < stop:
|
||||||
logger.warning(f"Missing data at end for pair {pair} at {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}")
|
||||||
|
|
||||||
|
|
||||||
|
@ -10,6 +10,7 @@ from freqtrade import misc
|
|||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, ListPairsWithTimeframes, TradeList
|
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, ListPairsWithTimeframes, TradeList
|
||||||
from freqtrade.data.converter import trades_dict_to_list
|
from freqtrade.data.converter import trades_dict_to_list
|
||||||
|
from freqtrade.enums import CandleType, TradingMode
|
||||||
|
|
||||||
from .idatahandler import IDataHandler
|
from .idatahandler import IDataHandler
|
||||||
|
|
||||||
@ -23,33 +24,49 @@ class JsonDataHandler(IDataHandler):
|
|||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def ohlcv_get_available_data(cls, datadir: Path) -> ListPairsWithTimeframes:
|
def ohlcv_get_available_data(
|
||||||
|
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
|
||||||
"""
|
"""
|
||||||
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
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:param trading_mode: trading-mode to be used
|
||||||
:return: List of Tuples of (pair, timeframe)
|
:return: List of Tuples of (pair, timeframe)
|
||||||
"""
|
"""
|
||||||
_tmp = [re.search(r'^([a-zA-Z_]+)\-(\d+\S+)(?=.json)', p.name)
|
if trading_mode == 'futures':
|
||||||
for p in datadir.glob(f"*.{cls._get_file_extension()}")]
|
datadir = datadir.joinpath('futures')
|
||||||
return [(match[1].replace('_', '/'), match[2]) for match in _tmp
|
_tmp = [
|
||||||
if match and len(match.groups()) > 1]
|
re.search(
|
||||||
|
cls._OHLCV_REGEX, p.name
|
||||||
|
) for p in datadir.glob(f"*.{cls._get_file_extension()}")]
|
||||||
|
return [
|
||||||
|
(
|
||||||
|
cls.rebuild_pair_from_filename(match[1]),
|
||||||
|
match[2],
|
||||||
|
CandleType.from_string(match[3])
|
||||||
|
) for match in _tmp if match and len(match.groups()) > 1]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str) -> 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
|
||||||
for the specified timeframe
|
for the specified timeframe
|
||||||
:param datadir: Directory to search for ohlcv files
|
:param datadir: Directory to search for ohlcv files
|
||||||
:param timeframe: Timeframe to search pairs for
|
:param timeframe: Timeframe to search pairs for
|
||||||
|
: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}"
|
||||||
|
|
||||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + '.json)', p.name)
|
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + candle + '.json)', p.name)
|
||||||
for p in datadir.glob(f"*{timeframe}.{cls._get_file_extension()}")]
|
for p in datadir.glob(f"*{timeframe}{candle}.{cls._get_file_extension()}")]
|
||||||
# Check if regex found something and only return these results
|
# Check if regex found something and only return these results
|
||||||
return [match[0].replace('_', '/') for match in _tmp if match]
|
return [cls.rebuild_pair_from_filename(match[0]) for match in _tmp if match]
|
||||||
|
|
||||||
def ohlcv_store(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
def ohlcv_store(
|
||||||
|
self, pair: str, timeframe: str, data: DataFrame, candle_type: CandleType) -> None:
|
||||||
"""
|
"""
|
||||||
Store data in json format "values".
|
Store data in json format "values".
|
||||||
format looks as follows:
|
format looks as follows:
|
||||||
@ -57,9 +74,11 @@ class JsonDataHandler(IDataHandler):
|
|||||||
:param pair: Pair - used to generate filename
|
:param pair: Pair - used to generate filename
|
||||||
:param timeframe: Timeframe - used to generate filename
|
:param timeframe: Timeframe - used to generate filename
|
||||||
:param data: Dataframe containing OHLCV data
|
:param data: Dataframe containing OHLCV data
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type)
|
||||||
|
self.create_dir_if_needed(filename)
|
||||||
_data = data.copy()
|
_data = data.copy()
|
||||||
# Convert date to int
|
# Convert date to int
|
||||||
_data['date'] = _data['date'].view(np.int64) // 1000 // 1000
|
_data['date'] = _data['date'].view(np.int64) // 1000 // 1000
|
||||||
@ -70,7 +89,7 @@ class JsonDataHandler(IDataHandler):
|
|||||||
compression='gzip' if self._use_zip else None)
|
compression='gzip' if self._use_zip else None)
|
||||||
|
|
||||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||||
timerange: Optional[TimeRange] = None,
|
timerange: Optional[TimeRange], candle_type: CandleType
|
||||||
) -> DataFrame:
|
) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Internal method used to load data for one pair from disk.
|
Internal method used to load data for one pair from disk.
|
||||||
@ -81,9 +100,10 @@ class JsonDataHandler(IDataHandler):
|
|||||||
:param timerange: Limit data to be loaded to this timerange.
|
:param timerange: Limit data to be loaded to this timerange.
|
||||||
Optionally implemented by subclasses to avoid loading
|
Optionally implemented by subclasses to avoid loading
|
||||||
all data where possible.
|
all data where possible.
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
"""
|
"""
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
filename = self._pair_data_filename(self._datadir, pair, timeframe, candle_type=candle_type)
|
||||||
if not filename.exists():
|
if not filename.exists():
|
||||||
return DataFrame(columns=self._columns)
|
return DataFrame(columns=self._columns)
|
||||||
try:
|
try:
|
||||||
@ -100,25 +120,19 @@ class JsonDataHandler(IDataHandler):
|
|||||||
infer_datetime_format=True)
|
infer_datetime_format=True)
|
||||||
return pairdata
|
return pairdata
|
||||||
|
|
||||||
def ohlcv_purge(self, pair: str, timeframe: str) -> bool:
|
def ohlcv_append(
|
||||||
"""
|
self,
|
||||||
Remove data for this pair
|
pair: str,
|
||||||
:param pair: Delete data for this pair.
|
timeframe: str,
|
||||||
:param timeframe: Timeframe (e.g. "5m")
|
data: DataFrame,
|
||||||
:return: True when deleted, false if file did not exist.
|
candle_type: CandleType
|
||||||
"""
|
) -> None:
|
||||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
|
||||||
if filename.exists():
|
|
||||||
filename.unlink()
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
def ohlcv_append(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
|
||||||
"""
|
"""
|
||||||
Append data to existing data structures
|
Append data to existing data structures
|
||||||
:param pair: Pair
|
:param pair: Pair
|
||||||
:param timeframe: Timeframe this ohlcv data is for
|
:param timeframe: Timeframe this ohlcv data is for
|
||||||
:param data: Data to append.
|
:param data: Data to append.
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
@ -132,7 +146,7 @@ class JsonDataHandler(IDataHandler):
|
|||||||
_tmp = [re.search(r'^(\S+)(?=\-trades.json)', p.name)
|
_tmp = [re.search(r'^(\S+)(?=\-trades.json)', p.name)
|
||||||
for p in datadir.glob(f"*trades.{cls._get_file_extension()}")]
|
for p in datadir.glob(f"*trades.{cls._get_file_extension()}")]
|
||||||
# Check if regex found something and only return these results to avoid exceptions.
|
# Check if regex found something and only return these results to avoid exceptions.
|
||||||
return [match[0].replace('_', '/') for match in _tmp if match]
|
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:
|
||||||
"""
|
"""
|
||||||
|
173
freqtrade/data/metrics.py
Normal file
173
freqtrade/data/metrics.py
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Dict, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_market_change(data: Dict[str, pd.DataFrame], column: str = "close") -> float:
|
||||||
|
"""
|
||||||
|
Calculate market change based on "column".
|
||||||
|
Calculation is done by taking the first non-null and the last non-null element of each column
|
||||||
|
and calculating the pctchange as "(last - first) / first".
|
||||||
|
Then the results per pair are combined as mean.
|
||||||
|
|
||||||
|
:param data: Dict of Dataframes, dict key should be pair.
|
||||||
|
:param column: Column in the original dataframes to use
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
tmp_means = []
|
||||||
|
for pair, df in data.items():
|
||||||
|
start = df[column].dropna().iloc[0]
|
||||||
|
end = df[column].dropna().iloc[-1]
|
||||||
|
tmp_means.append((end - start) / start)
|
||||||
|
|
||||||
|
return float(np.mean(tmp_means))
|
||||||
|
|
||||||
|
|
||||||
|
def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame],
|
||||||
|
column: str = "close") -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Combine multiple dataframes "column"
|
||||||
|
:param data: Dict of Dataframes, dict key should be pair.
|
||||||
|
:param column: Column in the original dataframes to use
|
||||||
|
:return: DataFrame with the column renamed to the dict key, and a column
|
||||||
|
named mean, containing the mean of all pairs.
|
||||||
|
:raise: ValueError if no data is provided.
|
||||||
|
"""
|
||||||
|
df_comb = pd.concat([data[pair].set_index('date').rename(
|
||||||
|
{column: pair}, axis=1)[pair] for pair in data], axis=1)
|
||||||
|
|
||||||
|
df_comb['mean'] = df_comb.mean(axis=1)
|
||||||
|
|
||||||
|
return df_comb
|
||||||
|
|
||||||
|
|
||||||
|
def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
||||||
|
timeframe: str) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Adds a column `col_name` with the cumulative profit for the given trades array.
|
||||||
|
:param df: DataFrame with date index
|
||||||
|
:param trades: DataFrame containing trades (requires columns close_date and profit_abs)
|
||||||
|
:param col_name: Column name that will be assigned the results
|
||||||
|
:param timeframe: Timeframe used during the operations
|
||||||
|
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
||||||
|
:raise: ValueError if trade-dataframe was found empty.
|
||||||
|
"""
|
||||||
|
if len(trades) == 0:
|
||||||
|
raise ValueError("Trade dataframe empty.")
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
# Resample to timeframe to make sure trades match candles
|
||||||
|
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_date'
|
||||||
|
)[['profit_abs']].sum()
|
||||||
|
df.loc[:, col_name] = _trades_sum['profit_abs'].cumsum()
|
||||||
|
# Set first value to 0
|
||||||
|
df.loc[df.iloc[0].name, col_name] = 0
|
||||||
|
# FFill to get continuous
|
||||||
|
df[col_name] = df[col_name].ffill()
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
def _calc_drawdown_series(profit_results: pd.DataFrame, *, date_col: str, value_col: str
|
||||||
|
) -> pd.DataFrame:
|
||||||
|
max_drawdown_df = pd.DataFrame()
|
||||||
|
max_drawdown_df['cumulative'] = profit_results[value_col].cumsum()
|
||||||
|
max_drawdown_df['high_value'] = max_drawdown_df['cumulative'].cummax()
|
||||||
|
max_drawdown_df['drawdown'] = max_drawdown_df['cumulative'] - max_drawdown_df['high_value']
|
||||||
|
max_drawdown_df['date'] = profit_results.loc[:, date_col]
|
||||||
|
return max_drawdown_df
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_underwater(trades: pd.DataFrame, *, date_col: str = 'close_date',
|
||||||
|
value_col: str = 'profit_ratio'
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Calculate max drawdown and the corresponding close dates
|
||||||
|
:param trades: DataFrame containing trades (requires columns close_date and profit_ratio)
|
||||||
|
:param date_col: Column in DataFrame to use for dates (defaults to 'close_date')
|
||||||
|
:param value_col: Column in DataFrame to use for values (defaults to 'profit_ratio')
|
||||||
|
:return: Tuple (float, highdate, lowdate, highvalue, lowvalue) with absolute max drawdown,
|
||||||
|
high and low time and high and low value.
|
||||||
|
:raise: ValueError if trade-dataframe was found empty.
|
||||||
|
"""
|
||||||
|
if len(trades) == 0:
|
||||||
|
raise ValueError("Trade dataframe empty.")
|
||||||
|
profit_results = trades.sort_values(date_col).reset_index(drop=True)
|
||||||
|
max_drawdown_df = _calc_drawdown_series(profit_results, date_col=date_col, value_col=value_col)
|
||||||
|
|
||||||
|
return max_drawdown_df
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date',
|
||||||
|
value_col: str = 'profit_abs', starting_balance: float = 0
|
||||||
|
) -> Tuple[float, pd.Timestamp, pd.Timestamp, float, float, float]:
|
||||||
|
"""
|
||||||
|
Calculate max drawdown and the corresponding close dates
|
||||||
|
:param trades: DataFrame containing trades (requires columns close_date and profit_ratio)
|
||||||
|
:param date_col: Column in DataFrame to use for dates (defaults to 'close_date')
|
||||||
|
:param value_col: Column in DataFrame to use for values (defaults to 'profit_abs')
|
||||||
|
:param starting_balance: Portfolio starting balance - properly calculate relative drawdown.
|
||||||
|
:return: Tuple (float, highdate, lowdate, highvalue, lowvalue, relative_drawdown)
|
||||||
|
with absolute max drawdown, high and low time and high and low value,
|
||||||
|
and the relative account drawdown
|
||||||
|
:raise: ValueError if trade-dataframe was found empty.
|
||||||
|
"""
|
||||||
|
if len(trades) == 0:
|
||||||
|
raise ValueError("Trade dataframe empty.")
|
||||||
|
profit_results = trades.sort_values(date_col).reset_index(drop=True)
|
||||||
|
max_drawdown_df = _calc_drawdown_series(profit_results, date_col=date_col, value_col=value_col)
|
||||||
|
|
||||||
|
idxmin = max_drawdown_df['drawdown'].idxmin()
|
||||||
|
if idxmin == 0:
|
||||||
|
raise ValueError("No losing trade, therefore no drawdown.")
|
||||||
|
high_date = profit_results.loc[max_drawdown_df.iloc[:idxmin]['high_value'].idxmax(), date_col]
|
||||||
|
low_date = profit_results.loc[idxmin, date_col]
|
||||||
|
high_val = max_drawdown_df.loc[max_drawdown_df.iloc[:idxmin]
|
||||||
|
['high_value'].idxmax(), 'cumulative']
|
||||||
|
low_val = max_drawdown_df.loc[idxmin, 'cumulative']
|
||||||
|
max_drawdown_rel = 0.0
|
||||||
|
if high_val + starting_balance != 0:
|
||||||
|
max_drawdown_rel = (high_val - low_val) / (high_val + starting_balance)
|
||||||
|
|
||||||
|
return (
|
||||||
|
abs(min(max_drawdown_df['drawdown'])),
|
||||||
|
high_date,
|
||||||
|
low_date,
|
||||||
|
high_val,
|
||||||
|
low_val,
|
||||||
|
max_drawdown_rel
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_csum(trades: pd.DataFrame, starting_balance: float = 0) -> Tuple[float, float]:
|
||||||
|
"""
|
||||||
|
Calculate min/max cumsum of trades, to show if the wallet/stake amount ratio is sane
|
||||||
|
:param trades: DataFrame containing trades (requires columns close_date and profit_percent)
|
||||||
|
:param starting_balance: Add starting balance to results, to show the wallets high / low points
|
||||||
|
:return: Tuple (float, float) with cumsum of profit_abs
|
||||||
|
:raise: ValueError if trade-dataframe was found empty.
|
||||||
|
"""
|
||||||
|
if len(trades) == 0:
|
||||||
|
raise ValueError("Trade dataframe empty.")
|
||||||
|
|
||||||
|
csum_df = pd.DataFrame()
|
||||||
|
csum_df['sum'] = trades['profit_abs'].cumsum()
|
||||||
|
csum_min = csum_df['sum'].min() + starting_balance
|
||||||
|
csum_max = csum_df['sum'].max() + starting_balance
|
||||||
|
|
||||||
|
return csum_min, csum_max
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_cagr(days_passed: int, starting_balance: float, final_balance: float) -> float:
|
||||||
|
"""
|
||||||
|
Calculate CAGR
|
||||||
|
:param days_passed: Days passed between start and ending balance
|
||||||
|
:param starting_balance: Starting balance
|
||||||
|
:param final_balance: Final balance to calculate CAGR against
|
||||||
|
:return: CAGR
|
||||||
|
"""
|
||||||
|
return (final_balance / starting_balance) ** (1 / (days_passed / 365)) - 1
|
@ -13,7 +13,7 @@ from pandas import DataFrame
|
|||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
|
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
|
||||||
from freqtrade.data.history import get_timerange, load_data, refresh_data
|
from freqtrade.data.history import get_timerange, load_data, refresh_data
|
||||||
from freqtrade.enums import RunMode, SellType
|
from freqtrade.enums import CandleType, ExitType, RunMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange.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
|
||||||
@ -116,11 +116,12 @@ class Edge:
|
|||||||
timeframe=self.strategy.timeframe,
|
timeframe=self.strategy.timeframe,
|
||||||
timerange=timerange_startup,
|
timerange=timerange_startup,
|
||||||
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
||||||
|
candle_type=self.config.get('candle_type_def', CandleType.SPOT),
|
||||||
)
|
)
|
||||||
# Download informative pairs too
|
# Download informative pairs too
|
||||||
res = defaultdict(list)
|
res = defaultdict(list)
|
||||||
for p, t in self.strategy.gather_informative_pairs():
|
for pair, timeframe, _ in self.strategy.gather_informative_pairs():
|
||||||
res[t].append(p)
|
res[timeframe].append(pair)
|
||||||
for timeframe, inf_pairs in res.items():
|
for timeframe, inf_pairs in res.items():
|
||||||
timerange_startup = deepcopy(self._timerange)
|
timerange_startup = deepcopy(self._timerange)
|
||||||
timerange_startup.subtract_start(timeframe_to_seconds(
|
timerange_startup.subtract_start(timeframe_to_seconds(
|
||||||
@ -132,6 +133,7 @@ class Edge:
|
|||||||
timeframe=timeframe,
|
timeframe=timeframe,
|
||||||
timerange=timerange_startup,
|
timerange=timerange_startup,
|
||||||
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
||||||
|
candle_type=self.config.get('candle_type_def', CandleType.SPOT),
|
||||||
)
|
)
|
||||||
|
|
||||||
data = load_data(
|
data = load_data(
|
||||||
@ -141,6 +143,7 @@ class Edge:
|
|||||||
timerange=self._timerange,
|
timerange=self._timerange,
|
||||||
startup_candles=self.strategy.startup_candle_count,
|
startup_candles=self.strategy.startup_candle_count,
|
||||||
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
||||||
|
candle_type=self.config.get('candle_type_def', CandleType.SPOT),
|
||||||
)
|
)
|
||||||
|
|
||||||
if not data:
|
if not data:
|
||||||
@ -159,7 +162,9 @@ class Edge:
|
|||||||
logger.info(f'Measuring data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
|
logger.info(f'Measuring data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
|
||||||
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
|
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
|
||||||
f'({(max_date - min_date).days} days)..')
|
f'({(max_date - min_date).days} days)..')
|
||||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'high', 'low']
|
# TODO: Should edge support shorts? needs to be investigated further
|
||||||
|
# * (add enter_short exit_short)
|
||||||
|
headers = ['date', 'open', 'high', 'low', 'close', 'enter_long', 'exit_long']
|
||||||
|
|
||||||
trades: list = []
|
trades: list = []
|
||||||
for pair, pair_data in preprocessed.items():
|
for pair, pair_data in preprocessed.items():
|
||||||
@ -167,8 +172,13 @@ class Edge:
|
|||||||
pair_data = pair_data.sort_values(by=['date'])
|
pair_data = pair_data.sort_values(by=['date'])
|
||||||
pair_data = pair_data.reset_index(drop=True)
|
pair_data = pair_data.reset_index(drop=True)
|
||||||
|
|
||||||
df_analyzed = self.strategy.advise_sell(
|
df_analyzed = self.strategy.advise_exit(
|
||||||
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
dataframe=self.strategy.advise_entry(
|
||||||
|
dataframe=pair_data,
|
||||||
|
metadata={'pair': pair}
|
||||||
|
),
|
||||||
|
metadata={'pair': pair}
|
||||||
|
)[headers].copy()
|
||||||
|
|
||||||
trades += self._find_trades_for_stoploss_range(df_analyzed, pair, self._stoploss_range)
|
trades += self._find_trades_for_stoploss_range(df_analyzed, pair, self._stoploss_range)
|
||||||
|
|
||||||
@ -384,8 +394,8 @@ class Edge:
|
|||||||
return final
|
return final
|
||||||
|
|
||||||
def _find_trades_for_stoploss_range(self, df, pair, stoploss_range):
|
def _find_trades_for_stoploss_range(self, df, pair, stoploss_range):
|
||||||
buy_column = df['buy'].values
|
buy_column = df['enter_long'].values
|
||||||
sell_column = df['sell'].values
|
sell_column = df['exit_long'].values
|
||||||
date_column = df['date'].values
|
date_column = df['date'].values
|
||||||
ohlc_columns = df[['open', 'high', 'low', 'close']].values
|
ohlc_columns = df[['open', 'high', 'low', 'close']].values
|
||||||
|
|
||||||
@ -450,7 +460,7 @@ class Edge:
|
|||||||
|
|
||||||
if stop_index <= sell_index:
|
if stop_index <= sell_index:
|
||||||
exit_index = open_trade_index + stop_index
|
exit_index = open_trade_index + stop_index
|
||||||
exit_type = SellType.STOP_LOSS
|
exit_type = ExitType.STOP_LOSS
|
||||||
exit_price = stop_price
|
exit_price = stop_price
|
||||||
elif stop_index > sell_index:
|
elif stop_index > sell_index:
|
||||||
# If exit is SELL then we exit at the next candle
|
# If exit is SELL then we exit at the next candle
|
||||||
@ -460,7 +470,7 @@ class Edge:
|
|||||||
if len(ohlc_columns) - 1 < exit_index:
|
if len(ohlc_columns) - 1 < exit_index:
|
||||||
break
|
break
|
||||||
|
|
||||||
exit_type = SellType.SELL_SIGNAL
|
exit_type = ExitType.EXIT_SIGNAL
|
||||||
exit_price = ohlc_columns[exit_index, 0]
|
exit_price = ohlc_columns[exit_index, 0]
|
||||||
|
|
||||||
trade = {'pair': pair,
|
trade = {'pair': pair,
|
||||||
|
@ -1,8 +1,12 @@
|
|||||||
# flake8: noqa: F401
|
# flake8: noqa: F401
|
||||||
from freqtrade.enums.backteststate import BacktestState
|
from freqtrade.enums.backteststate import BacktestState
|
||||||
|
from freqtrade.enums.candletype import CandleType
|
||||||
|
from freqtrade.enums.exitchecktuple import ExitCheckTuple
|
||||||
|
from freqtrade.enums.exittype import ExitType
|
||||||
|
from freqtrade.enums.marginmode import MarginMode
|
||||||
from freqtrade.enums.ordertypevalue import OrderTypeValues
|
from freqtrade.enums.ordertypevalue import OrderTypeValues
|
||||||
from freqtrade.enums.rpcmessagetype import RPCMessageType
|
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.selltype import SellType
|
from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType
|
||||||
from freqtrade.enums.signaltype import SignalTagType, SignalType
|
|
||||||
from freqtrade.enums.state import State
|
from freqtrade.enums.state import State
|
||||||
|
from freqtrade.enums.tradingmode import TradingMode
|
||||||
|
27
freqtrade/enums/candletype.py
Normal file
27
freqtrade/enums/candletype.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class CandleType(str, Enum):
|
||||||
|
"""Enum to distinguish candle types"""
|
||||||
|
SPOT = "spot"
|
||||||
|
FUTURES = "futures"
|
||||||
|
MARK = "mark"
|
||||||
|
INDEX = "index"
|
||||||
|
PREMIUMINDEX = "premiumIndex"
|
||||||
|
|
||||||
|
# TODO: Could take up less memory if these weren't a CandleType
|
||||||
|
FUNDING_RATE = "funding_rate"
|
||||||
|
# BORROW_RATE = "borrow_rate" # * unimplemented
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_string(value: str) -> 'CandleType':
|
||||||
|
if not value:
|
||||||
|
# Default to spot
|
||||||
|
return CandleType.SPOT
|
||||||
|
return CandleType(value)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_default(trading_mode: str) -> 'CandleType':
|
||||||
|
if trading_mode == 'futures':
|
||||||
|
return CandleType.FUTURES
|
||||||
|
return CandleType.SPOT
|
17
freqtrade/enums/exitchecktuple.py
Normal file
17
freqtrade/enums/exitchecktuple.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
from freqtrade.enums.exittype import ExitType
|
||||||
|
|
||||||
|
|
||||||
|
class ExitCheckTuple:
|
||||||
|
"""
|
||||||
|
NamedTuple for Exit type + reason
|
||||||
|
"""
|
||||||
|
exit_type: ExitType
|
||||||
|
exit_reason: str = ''
|
||||||
|
|
||||||
|
def __init__(self, exit_type: ExitType, exit_reason: str = ''):
|
||||||
|
self.exit_type = exit_type
|
||||||
|
self.exit_reason = exit_reason or exit_type.value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def exit_flag(self):
|
||||||
|
return self.exit_type != ExitType.NONE
|
@ -1,18 +1,18 @@
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
class SellType(Enum):
|
class ExitType(Enum):
|
||||||
"""
|
"""
|
||||||
Enum to distinguish between sell reasons
|
Enum to distinguish between exit reasons
|
||||||
"""
|
"""
|
||||||
ROI = "roi"
|
ROI = "roi"
|
||||||
STOP_LOSS = "stop_loss"
|
STOP_LOSS = "stop_loss"
|
||||||
STOPLOSS_ON_EXCHANGE = "stoploss_on_exchange"
|
STOPLOSS_ON_EXCHANGE = "stoploss_on_exchange"
|
||||||
TRAILING_STOP_LOSS = "trailing_stop_loss"
|
TRAILING_STOP_LOSS = "trailing_stop_loss"
|
||||||
SELL_SIGNAL = "sell_signal"
|
EXIT_SIGNAL = "exit_signal"
|
||||||
FORCE_SELL = "force_sell"
|
FORCE_EXIT = "force_exit"
|
||||||
EMERGENCY_SELL = "emergency_sell"
|
EMERGENCY_EXIT = "emergency_exit"
|
||||||
CUSTOM_SELL = "custom_sell"
|
CUSTOM_EXIT = "custom_exit"
|
||||||
NONE = ""
|
NONE = ""
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
12
freqtrade/enums/marginmode.py
Normal file
12
freqtrade/enums/marginmode.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class MarginMode(Enum):
|
||||||
|
"""
|
||||||
|
Enum to distinguish between
|
||||||
|
cross margin/futures margin_mode and
|
||||||
|
isolated margin/futures margin_mode
|
||||||
|
"""
|
||||||
|
CROSS = "cross"
|
||||||
|
ISOLATED = "isolated"
|
||||||
|
NONE = ''
|
@ -5,12 +5,15 @@ class RPCMessageType(Enum):
|
|||||||
STATUS = 'status'
|
STATUS = 'status'
|
||||||
WARNING = 'warning'
|
WARNING = 'warning'
|
||||||
STARTUP = 'startup'
|
STARTUP = 'startup'
|
||||||
BUY = 'buy'
|
|
||||||
BUY_FILL = 'buy_fill'
|
ENTRY = 'entry'
|
||||||
BUY_CANCEL = 'buy_cancel'
|
ENTRY_FILL = 'entry_fill'
|
||||||
SELL = 'sell'
|
ENTRY_CANCEL = 'entry_cancel'
|
||||||
SELL_FILL = 'sell_fill'
|
|
||||||
SELL_CANCEL = 'sell_cancel'
|
EXIT = 'exit'
|
||||||
|
EXIT_FILL = 'exit_fill'
|
||||||
|
EXIT_CANCEL = 'exit_cancel'
|
||||||
|
|
||||||
PROTECTION_TRIGGER = 'protection_trigger'
|
PROTECTION_TRIGGER = 'protection_trigger'
|
||||||
PROTECTION_TRIGGER_GLOBAL = 'protection_trigger_global'
|
PROTECTION_TRIGGER_GLOBAL = 'protection_trigger_global'
|
||||||
|
|
||||||
|
@ -3,15 +3,22 @@ from enum import Enum
|
|||||||
|
|
||||||
class SignalType(Enum):
|
class SignalType(Enum):
|
||||||
"""
|
"""
|
||||||
Enum to distinguish between buy and sell signals
|
Enum to distinguish between enter and exit signals
|
||||||
"""
|
"""
|
||||||
BUY = "buy"
|
ENTER_LONG = "enter_long"
|
||||||
SELL = "sell"
|
EXIT_LONG = "exit_long"
|
||||||
|
ENTER_SHORT = "enter_short"
|
||||||
|
EXIT_SHORT = "exit_short"
|
||||||
|
|
||||||
|
|
||||||
class SignalTagType(Enum):
|
class SignalTagType(Enum):
|
||||||
"""
|
"""
|
||||||
Enum for signal columns
|
Enum for signal columns
|
||||||
"""
|
"""
|
||||||
BUY_TAG = "buy_tag"
|
ENTER_TAG = "enter_tag"
|
||||||
EXIT_TAG = "exit_tag"
|
EXIT_TAG = "exit_tag"
|
||||||
|
|
||||||
|
|
||||||
|
class SignalDirection(str, Enum):
|
||||||
|
LONG = 'long'
|
||||||
|
SHORT = 'short'
|
||||||
|
11
freqtrade/enums/tradingmode.py
Normal file
11
freqtrade/enums/tradingmode.py
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class TradingMode(str, Enum):
|
||||||
|
"""
|
||||||
|
Enum to distinguish between
|
||||||
|
spot, margin, futures or any other trading method
|
||||||
|
"""
|
||||||
|
SPOT = "spot"
|
||||||
|
MARGIN = "margin"
|
||||||
|
FUTURES = "futures"
|
@ -20,4 +20,9 @@ class Bibox(Exchange):
|
|||||||
|
|
||||||
# fetchCurrencies API point requires authentication for Bibox,
|
# fetchCurrencies API point requires authentication for Bibox,
|
||||||
# so switch it off for Freqtrade load_markets()
|
# so switch it off for Freqtrade load_markets()
|
||||||
_ccxt_config: Dict = {"has": {"fetchCurrencies": False}}
|
@property
|
||||||
|
def _ccxt_config(self) -> Dict:
|
||||||
|
# Parameters to add directly to ccxt sync/async initialization.
|
||||||
|
config = {"has": {"fetchCurrencies": False}}
|
||||||
|
config.update(super()._ccxt_config)
|
||||||
|
return config
|
||||||
|
@ -1,10 +1,18 @@
|
|||||||
""" Binance exchange subclass """
|
""" Binance exchange subclass """
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, List, Tuple
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade.enums import CandleType, MarginMode, TradingMode
|
||||||
|
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.misc import deep_merge_dicts
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -21,30 +29,179 @@ class Binance(Exchange):
|
|||||||
"trades_pagination": "id",
|
"trades_pagination": "id",
|
||||||
"trades_pagination_arg": "fromId",
|
"trades_pagination_arg": "fromId",
|
||||||
"l2_limit_range": [5, 10, 20, 50, 100, 500, 1000],
|
"l2_limit_range": [5, 10, 20, 50, 100, 500, 1000],
|
||||||
|
"ccxt_futures_name": "future"
|
||||||
|
}
|
||||||
|
_ft_has_futures: Dict = {
|
||||||
|
"stoploss_order_types": {"limit": "stop"},
|
||||||
|
"tickers_have_price": False,
|
||||||
}
|
}
|
||||||
|
|
||||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
||||||
|
# TradingMode.SPOT always supported and not required in this list
|
||||||
|
# (TradingMode.MARGIN, MarginMode.CROSS),
|
||||||
|
# (TradingMode.FUTURES, MarginMode.CROSS),
|
||||||
|
(TradingMode.FUTURES, MarginMode.ISOLATED)
|
||||||
|
]
|
||||||
|
|
||||||
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Verify stop_loss against stoploss-order value (limit or price)
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
Returns True if adjustment is necessary.
|
Returns True if adjustment is necessary.
|
||||||
|
:param side: "buy" or "sell"
|
||||||
"""
|
"""
|
||||||
return order['type'] == 'stop_loss_limit' and stop_loss > float(order['info']['stopPrice'])
|
|
||||||
|
ordertype = 'stop' if self.trading_mode == TradingMode.FUTURES else 'stop_loss_limit'
|
||||||
|
|
||||||
|
return order['type'] == ordertype and (
|
||||||
|
(side == "sell" and stop_loss > float(order['info']['stopPrice'])) or
|
||||||
|
(side == "buy" and stop_loss < float(order['info']['stopPrice']))
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_tickers(self, symbols: List[str] = None, cached: bool = False) -> Dict:
|
||||||
|
tickers = super().get_tickers(symbols=symbols, cached=cached)
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
# Binance's future result has no bid/ask values.
|
||||||
|
# Therefore we must fetch that from fetch_bids_asks and combine the two results.
|
||||||
|
bidsasks = self.fetch_bids_asks(symbols, cached)
|
||||||
|
tickers = deep_merge_dicts(bidsasks, tickers, allow_null_overrides=False)
|
||||||
|
return tickers
|
||||||
|
|
||||||
|
@retrier
|
||||||
|
def _set_leverage(
|
||||||
|
self,
|
||||||
|
leverage: float,
|
||||||
|
pair: Optional[str] = None,
|
||||||
|
trading_mode: Optional[TradingMode] = None
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Set's the leverage before making a trade, in order to not
|
||||||
|
have the same leverage on every trade
|
||||||
|
"""
|
||||||
|
trading_mode = trading_mode or self.trading_mode
|
||||||
|
|
||||||
|
if self._config['dry_run'] or trading_mode != TradingMode.FUTURES:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._api.set_leverage(symbol=pair, leverage=round(leverage))
|
||||||
|
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
|
||||||
|
|
||||||
async def _async_get_historic_ohlcv(self, pair: str, timeframe: str,
|
async def _async_get_historic_ohlcv(self, pair: str, timeframe: str,
|
||||||
since_ms: int, is_new_pair: bool = False,
|
since_ms: int, candle_type: CandleType,
|
||||||
raise_: bool = False
|
is_new_pair: bool = False, raise_: bool = False,
|
||||||
) -> Tuple[str, str, List]:
|
) -> Tuple[str, str, str, List]:
|
||||||
"""
|
"""
|
||||||
Overwrite to introduce "fast new pair" functionality by detecting the pair's listing date
|
Overwrite to introduce "fast new pair" functionality by detecting the pair's listing date
|
||||||
Does not work for other exchanges, which don't return the earliest data when called with "0"
|
Does not work for other exchanges, which don't return the earliest data when called with "0"
|
||||||
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
||||||
"""
|
"""
|
||||||
if is_new_pair:
|
if is_new_pair:
|
||||||
x = await self._async_get_candle_history(pair, timeframe, 0)
|
x = await self._async_get_candle_history(pair, timeframe, candle_type, 0)
|
||||||
if x and x[2] and x[2][0] and x[2][0][0] > since_ms:
|
if x and x[3] and x[3][0] and x[3][0][0] > since_ms:
|
||||||
# Set starting date to first available candle.
|
# Set starting date to first available candle.
|
||||||
since_ms = x[2][0][0]
|
since_ms = x[3][0][0]
|
||||||
logger.info(f"Candle-data for {pair} available starting with "
|
logger.info(f"Candle-data for {pair} available starting with "
|
||||||
f"{arrow.get(since_ms // 1000).isoformat()}.")
|
f"{arrow.get(since_ms // 1000).isoformat()}.")
|
||||||
|
|
||||||
return await super()._async_get_historic_ohlcv(
|
return await super()._async_get_historic_ohlcv(
|
||||||
pair=pair, timeframe=timeframe, since_ms=since_ms, is_new_pair=is_new_pair,
|
pair=pair,
|
||||||
raise_=raise_)
|
timeframe=timeframe,
|
||||||
|
since_ms=since_ms,
|
||||||
|
is_new_pair=is_new_pair,
|
||||||
|
raise_=raise_,
|
||||||
|
candle_type=candle_type
|
||||||
|
)
|
||||||
|
|
||||||
|
def funding_fee_cutoff(self, open_date: datetime):
|
||||||
|
"""
|
||||||
|
:param open_date: The open date for a trade
|
||||||
|
:return: The cutoff open time for when a funding fee is charged
|
||||||
|
"""
|
||||||
|
return open_date.minute > 0 or (open_date.minute == 0 and open_date.second > 15)
|
||||||
|
|
||||||
|
def dry_run_liquidation_price(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
open_rate: float, # Entry price of position
|
||||||
|
is_short: bool,
|
||||||
|
position: float, # Absolute value of position size
|
||||||
|
wallet_balance: float, # Or margin balance
|
||||||
|
mm_ex_1: float = 0.0, # (Binance) Cross only
|
||||||
|
upnl_ex_1: float = 0.0, # (Binance) Cross only
|
||||||
|
) -> Optional[float]:
|
||||||
|
"""
|
||||||
|
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
|
||||||
|
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
|
||||||
|
|
||||||
|
:param exchange_name:
|
||||||
|
:param open_rate: (EP1) Entry price of position
|
||||||
|
:param is_short: True if the trade is a short, false otherwise
|
||||||
|
:param position: Absolute value of position size (in base currency)
|
||||||
|
:param wallet_balance: (WB)
|
||||||
|
Cross-Margin Mode: crossWalletBalance
|
||||||
|
Isolated-Margin Mode: isolatedWalletBalance
|
||||||
|
:param maintenance_amt:
|
||||||
|
|
||||||
|
# * Only required for Cross
|
||||||
|
:param mm_ex_1: (TMM)
|
||||||
|
Cross-Margin Mode: Maintenance Margin of all other contracts, excluding Contract 1
|
||||||
|
Isolated-Margin Mode: 0
|
||||||
|
:param upnl_ex_1: (UPNL)
|
||||||
|
Cross-Margin Mode: Unrealized PNL of all other contracts, excluding Contract 1.
|
||||||
|
Isolated-Margin Mode: 0
|
||||||
|
"""
|
||||||
|
|
||||||
|
side_1 = -1 if is_short else 1
|
||||||
|
position = abs(position)
|
||||||
|
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
|
||||||
|
|
||||||
|
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
|
||||||
|
# maintenance_amt: (CUM) Maintenance Amount of position
|
||||||
|
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, position)
|
||||||
|
|
||||||
|
if (maintenance_amt is None):
|
||||||
|
raise OperationalException(
|
||||||
|
"Parameter maintenance_amt is required by Binance.liquidation_price"
|
||||||
|
f"for {self.trading_mode.value}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
return (
|
||||||
|
(
|
||||||
|
(wallet_balance + cross_vars + maintenance_amt) -
|
||||||
|
(side_1 * position * open_rate)
|
||||||
|
) / (
|
||||||
|
(position * mm_ratio) - (side_1 * position)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise OperationalException(
|
||||||
|
"Freqtrade only supports isolated futures for leverage trading")
|
||||||
|
|
||||||
|
@retrier
|
||||||
|
def load_leverage_tiers(self) -> Dict[str, List[Dict]]:
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
if self._config['dry_run']:
|
||||||
|
leverage_tiers_path = (
|
||||||
|
Path(__file__).parent / 'binance_leverage_tiers.json'
|
||||||
|
)
|
||||||
|
with open(leverage_tiers_path) as json_file:
|
||||||
|
return json.load(json_file)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
return self._api.fetch_leverage_tiers()
|
||||||
|
except ccxt.DDoSProtection as e:
|
||||||
|
raise DDosProtection(e) from e
|
||||||
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
|
raise TemporaryError(f'Could not fetch leverage amounts due to'
|
||||||
|
f'{e.__class__.__name__}. Message: {e}') from e
|
||||||
|
except ccxt.BaseError as e:
|
||||||
|
raise OperationalException(e) from e
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
16481
freqtrade/exchange/binance_leverage_tiers.json
Normal file
16481
freqtrade/exchange/binance_leverage_tiers.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,8 @@
|
|||||||
""" Bybit exchange subclass """
|
""" Bybit exchange subclass """
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict
|
from typing import Dict, List, Tuple
|
||||||
|
|
||||||
|
from freqtrade.enums import MarginMode, TradingMode
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
|
|
||||||
@ -20,4 +21,11 @@ class Bybit(Exchange):
|
|||||||
|
|
||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"ohlcv_candle_limit": 200,
|
"ohlcv_candle_limit": 200,
|
||||||
|
"ccxt_futures_name": "linear"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
||||||
|
# TradingMode.SPOT always supported and not required in this list
|
||||||
|
# (TradingMode.FUTURES, MarginMode.CROSS),
|
||||||
|
# (TradingMode.FUTURES, MarginMode.ISOLATED)
|
||||||
|
]
|
||||||
|
@ -35,9 +35,19 @@ BAD_EXCHANGES = {
|
|||||||
MAP_EXCHANGE_CHILDCLASS = {
|
MAP_EXCHANGE_CHILDCLASS = {
|
||||||
'binanceus': 'binance',
|
'binanceus': 'binance',
|
||||||
'binanceje': 'binance',
|
'binanceje': 'binance',
|
||||||
|
'binanceusdm': 'binance',
|
||||||
'okex': 'okx',
|
'okex': 'okx',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
SUPPORTED_EXCHANGES = [
|
||||||
|
'binance',
|
||||||
|
'bittrex',
|
||||||
|
'ftx',
|
||||||
|
'gateio',
|
||||||
|
'huobi',
|
||||||
|
'kraken',
|
||||||
|
'okx',
|
||||||
|
]
|
||||||
|
|
||||||
EXCHANGE_HAS_REQUIRED = [
|
EXCHANGE_HAS_REQUIRED = [
|
||||||
# Required / private
|
# Required / private
|
||||||
@ -55,10 +65,17 @@ EXCHANGE_HAS_REQUIRED = [
|
|||||||
EXCHANGE_HAS_OPTIONAL = [
|
EXCHANGE_HAS_OPTIONAL = [
|
||||||
# Private
|
# Private
|
||||||
'fetchMyTrades', # Trades for order - fee detection
|
'fetchMyTrades', # Trades for order - fee detection
|
||||||
|
# 'setLeverage', # Margin/Futures trading
|
||||||
|
# 'setMarginMode', # Margin/Futures trading
|
||||||
|
# 'fetchFundingHistory', # Futures trading
|
||||||
# Public
|
# Public
|
||||||
'fetchOrderBook', 'fetchL2OrderBook', 'fetchTicker', # OR for pricing
|
'fetchOrderBook', 'fetchL2OrderBook', 'fetchTicker', # OR for pricing
|
||||||
'fetchTickers', # For volumepairlist?
|
'fetchTickers', # For volumepairlist?
|
||||||
'fetchTrades', # Downloading trades data
|
'fetchTrades', # Downloading trades data
|
||||||
|
# 'fetchFundingRateHistory', # Futures trading
|
||||||
|
# 'fetchPositions', # Futures trading
|
||||||
|
# 'fetchLeverageTiers', # Futures initialization
|
||||||
|
# 'fetchMarketLeverageTiers', # Futures initialization
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -85,7 +102,7 @@ def calculate_backoff(retrycount, max_retries):
|
|||||||
def retrier_async(f):
|
def retrier_async(f):
|
||||||
async def wrapper(*args, **kwargs):
|
async def wrapper(*args, **kwargs):
|
||||||
count = kwargs.pop('count', API_RETRY_COUNT)
|
count = kwargs.pop('count', API_RETRY_COUNT)
|
||||||
kucoin = args[0].name == "Kucoin" # Check if the exchange is KuCoin.
|
kucoin = args[0].name == "KuCoin" # Check if the exchange is KuCoin.
|
||||||
try:
|
try:
|
||||||
return await f(*args, **kwargs)
|
return await f(*args, **kwargs)
|
||||||
except TemporaryError as ex:
|
except TemporaryError as ex:
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -1,9 +1,10 @@
|
|||||||
""" FTX exchange subclass """
|
""" FTX exchange subclass """
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict, List, Tuple
|
||||||
|
|
||||||
import ccxt
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade.enums import MarginMode, TradingMode
|
||||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
||||||
OperationalException, TemporaryError)
|
OperationalException, TemporaryError)
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
@ -19,28 +20,31 @@ class Ftx(Exchange):
|
|||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
"ohlcv_candle_limit": 1500,
|
"ohlcv_candle_limit": 1500,
|
||||||
|
"ohlcv_require_since": True,
|
||||||
"ohlcv_volume_currency": "quote",
|
"ohlcv_volume_currency": "quote",
|
||||||
|
"mark_ohlcv_price": "index",
|
||||||
|
"mark_ohlcv_timeframe": "1h",
|
||||||
}
|
}
|
||||||
|
|
||||||
def market_is_tradable(self, market: Dict[str, Any]) -> bool:
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
||||||
"""
|
# TradingMode.SPOT always supported and not required in this list
|
||||||
Check if the market symbol is tradable by Freqtrade.
|
# (TradingMode.MARGIN, MarginMode.CROSS),
|
||||||
Default checks + check if pair is spot pair (no futures trading yet).
|
# (TradingMode.FUTURES, MarginMode.CROSS)
|
||||||
"""
|
]
|
||||||
parent_check = super().market_is_tradable(market)
|
|
||||||
|
|
||||||
return (parent_check and
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
market.get('spot', False) is True)
|
|
||||||
|
|
||||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
|
||||||
"""
|
"""
|
||||||
Verify stop_loss against stoploss-order value (limit or price)
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
Returns True if adjustment is necessary.
|
Returns True if adjustment is necessary.
|
||||||
"""
|
"""
|
||||||
return order['type'] == 'stop' and stop_loss > float(order['price'])
|
return order['type'] == 'stop' and (
|
||||||
|
side == "sell" and stop_loss > float(order['price']) or
|
||||||
|
side == "buy" and stop_loss < float(order['price'])
|
||||||
|
)
|
||||||
|
|
||||||
@retrier(retries=0)
|
@retrier(retries=0)
|
||||||
def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict:
|
def stoploss(self, pair: str, amount: float, stop_price: float,
|
||||||
|
order_types: Dict, side: str, leverage: float) -> Dict:
|
||||||
"""
|
"""
|
||||||
Creates a stoploss order.
|
Creates a stoploss order.
|
||||||
depending on order_types.stoploss configuration, uses 'market' or limit order.
|
depending on order_types.stoploss configuration, uses 'market' or limit order.
|
||||||
@ -48,7 +52,10 @@ class Ftx(Exchange):
|
|||||||
Limit orders are defined by having orderPrice set, otherwise a market order is used.
|
Limit orders are defined by having orderPrice set, otherwise a market order is used.
|
||||||
"""
|
"""
|
||||||
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
||||||
limit_rate = stop_price * limit_price_pct
|
if side == "sell":
|
||||||
|
limit_rate = stop_price * limit_price_pct
|
||||||
|
else:
|
||||||
|
limit_rate = stop_price * (2 - limit_price_pct)
|
||||||
|
|
||||||
ordertype = "stop"
|
ordertype = "stop"
|
||||||
|
|
||||||
@ -56,7 +63,7 @@ class Ftx(Exchange):
|
|||||||
|
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
dry_order = self.create_dry_run_order(
|
dry_order = self.create_dry_run_order(
|
||||||
pair, ordertype, "sell", amount, stop_price, stop_loss=True)
|
pair, ordertype, side, amount, stop_price, leverage, stop_loss=True)
|
||||||
return dry_order
|
return dry_order
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@ -64,11 +71,14 @@ class Ftx(Exchange):
|
|||||||
if order_types.get('stoploss', 'market') == 'limit':
|
if order_types.get('stoploss', 'market') == 'limit':
|
||||||
# set orderPrice to place limit order, otherwise it's a market order
|
# set orderPrice to place limit order, otherwise it's a market order
|
||||||
params['orderPrice'] = limit_rate
|
params['orderPrice'] = limit_rate
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
params.update({'reduceOnly': True})
|
||||||
|
|
||||||
params['stopPrice'] = stop_price
|
params['stopPrice'] = stop_price
|
||||||
amount = self.amount_to_precision(pair, amount)
|
amount = self.amount_to_precision(pair, amount)
|
||||||
|
|
||||||
order = self._api.create_order(symbol=pair, type=ordertype, side='sell',
|
self._lev_prep(pair, leverage, side)
|
||||||
|
order = self._api.create_order(symbol=pair, type=ordertype, side=side,
|
||||||
amount=amount, params=params)
|
amount=amount, params=params)
|
||||||
self._log_exchange_response('create_stoploss_order', order)
|
self._log_exchange_response('create_stoploss_order', order)
|
||||||
logger.info('stoploss order added for %s. '
|
logger.info('stoploss order added for %s. '
|
||||||
@ -76,19 +86,19 @@ class Ftx(Exchange):
|
|||||||
return order
|
return order
|
||||||
except ccxt.InsufficientFunds as e:
|
except ccxt.InsufficientFunds as e:
|
||||||
raise InsufficientFundsError(
|
raise InsufficientFundsError(
|
||||||
f'Insufficient funds to create {ordertype} sell order on market {pair}. '
|
f'Insufficient funds to create {ordertype} {side} order on market {pair}. '
|
||||||
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
except ccxt.InvalidOrder as e:
|
except ccxt.InvalidOrder as e:
|
||||||
raise InvalidOrderException(
|
raise InvalidOrderException(
|
||||||
f'Could not create {ordertype} sell order on market {pair}. '
|
f'Could not create {ordertype} {side} order on market {pair}. '
|
||||||
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
except ccxt.DDoSProtection as e:
|
except ccxt.DDoSProtection as e:
|
||||||
raise DDosProtection(e) from e
|
raise DDosProtection(e) from e
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
raise TemporaryError(
|
raise TemporaryError(
|
||||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}') from e
|
f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}') from e
|
||||||
except ccxt.BaseError as e:
|
except ccxt.BaseError as e:
|
||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
""" Gate.io exchange subclass """
|
""" Gate.io exchange subclass """
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict
|
from datetime import datetime
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
from freqtrade.enums import MarginMode, TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
|
|
||||||
@ -26,12 +28,48 @@ class Gateio(Exchange):
|
|||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_ft_has_futures: Dict = {
|
||||||
|
"needs_trading_fees": True
|
||||||
|
}
|
||||||
|
|
||||||
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
||||||
|
# TradingMode.SPOT always supported and not required in this list
|
||||||
|
# (TradingMode.MARGIN, MarginMode.CROSS),
|
||||||
|
# (TradingMode.FUTURES, MarginMode.CROSS),
|
||||||
|
(TradingMode.FUTURES, MarginMode.ISOLATED)
|
||||||
|
]
|
||||||
|
|
||||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||||
super().validate_ordertypes(order_types)
|
super().validate_ordertypes(order_types)
|
||||||
|
|
||||||
if any(v == 'market' for k, v in order_types.items()):
|
if self.trading_mode != TradingMode.FUTURES:
|
||||||
raise OperationalException(
|
if any(v == 'market' for k, v in order_types.items()):
|
||||||
f'Exchange {self.name} does not support market orders.')
|
raise OperationalException(
|
||||||
|
f'Exchange {self.name} does not support market orders.')
|
||||||
|
|
||||||
|
def get_trades_for_order(self, order_id: str, pair: str, since: datetime,
|
||||||
|
params: Optional[Dict] = None) -> List:
|
||||||
|
trades = super().get_trades_for_order(order_id, pair, since, params)
|
||||||
|
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
# Futures usually don't contain fees in the response.
|
||||||
|
# As such, futures orders on gateio will not contain a fee, which causes
|
||||||
|
# a repeated "update fee" cycle and wrong calculations.
|
||||||
|
# Therefore we patch the response with fees if it's not available.
|
||||||
|
# An alternative also contianing fees would be
|
||||||
|
# privateFuturesGetSettleAccountBook({"settle": "usdt"})
|
||||||
|
pair_fees = self._trading_fees.get(pair, {})
|
||||||
|
if pair_fees:
|
||||||
|
for idx, trade in enumerate(trades):
|
||||||
|
if trade.get('fee', {}).get('cost') is None:
|
||||||
|
takerOrMaker = trade.get('takerOrMaker', 'taker')
|
||||||
|
if pair_fees.get(takerOrMaker) is not None:
|
||||||
|
trades[idx]['fee'] = {
|
||||||
|
'currency': self.get_pair_quote_currency(pair),
|
||||||
|
'cost': trade['cost'] * pair_fees[takerOrMaker],
|
||||||
|
'rate': pair_fees[takerOrMaker],
|
||||||
|
}
|
||||||
|
return trades
|
||||||
|
|
||||||
def fetch_stoploss_order(self, order_id: str, pair: str, params={}) -> Dict:
|
def fetch_stoploss_order(self, order_id: str, pair: str, params={}) -> Dict:
|
||||||
return self.fetch_order(
|
return self.fetch_order(
|
||||||
@ -47,9 +85,10 @@ class Gateio(Exchange):
|
|||||||
params={'stop': True}
|
params={'stop': True}
|
||||||
)
|
)
|
||||||
|
|
||||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Verify stop_loss against stoploss-order value (limit or price)
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
Returns True if adjustment is necessary.
|
Returns True if adjustment is necessary.
|
||||||
"""
|
"""
|
||||||
return stop_loss > float(order['stopPrice'])
|
return ((side == "sell" and stop_loss > float(order['stopPrice'])) or
|
||||||
|
(side == "buy" and stop_loss < float(order['stopPrice'])))
|
||||||
|
@ -22,7 +22,7 @@ class Huobi(Exchange):
|
|||||||
"l2_limit_range_required": False,
|
"l2_limit_range_required": False,
|
||||||
}
|
}
|
||||||
|
|
||||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Verify stop_loss against stoploss-order value (limit or price)
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
Returns True if adjustment is necessary.
|
Returns True if adjustment is necessary.
|
||||||
|
@ -1,9 +1,12 @@
|
|||||||
""" Kraken exchange subclass """
|
""" Kraken exchange subclass """
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, List
|
from datetime import datetime
|
||||||
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import ccxt
|
import ccxt
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
from freqtrade.enums import MarginMode, TradingMode
|
||||||
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
||||||
OperationalException, TemporaryError)
|
OperationalException, TemporaryError)
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
@ -21,8 +24,15 @@ class Kraken(Exchange):
|
|||||||
"ohlcv_candle_limit": 720,
|
"ohlcv_candle_limit": 720,
|
||||||
"trades_pagination": "id",
|
"trades_pagination": "id",
|
||||||
"trades_pagination_arg": "since",
|
"trades_pagination_arg": "since",
|
||||||
|
"mark_ohlcv_timeframe": "4h",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
||||||
|
# TradingMode.SPOT always supported and not required in this list
|
||||||
|
# (TradingMode.MARGIN, MarginMode.CROSS),
|
||||||
|
# (TradingMode.FUTURES, MarginMode.CROSS)
|
||||||
|
]
|
||||||
|
|
||||||
def market_is_tradable(self, market: Dict[str, Any]) -> bool:
|
def market_is_tradable(self, market: Dict[str, Any]) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if the market symbol is tradable by Freqtrade.
|
Check if the market symbol is tradable by Freqtrade.
|
||||||
@ -73,16 +83,19 @@ class Kraken(Exchange):
|
|||||||
except ccxt.BaseError as e:
|
except ccxt.BaseError as e:
|
||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Verify stop_loss against stoploss-order value (limit or price)
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
Returns True if adjustment is necessary.
|
Returns True if adjustment is necessary.
|
||||||
"""
|
"""
|
||||||
return (order['type'] in ('stop-loss', 'stop-loss-limit')
|
return (order['type'] in ('stop-loss', 'stop-loss-limit') and (
|
||||||
and stop_loss > float(order['price']))
|
(side == "sell" and stop_loss > float(order['price'])) or
|
||||||
|
(side == "buy" and stop_loss < float(order['price']))
|
||||||
|
))
|
||||||
|
|
||||||
@retrier(retries=0)
|
@retrier(retries=0)
|
||||||
def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict:
|
def stoploss(self, pair: str, amount: float, stop_price: float,
|
||||||
|
order_types: Dict, side: str, leverage: float) -> Dict:
|
||||||
"""
|
"""
|
||||||
Creates a stoploss market order.
|
Creates a stoploss market order.
|
||||||
Stoploss market orders is the only stoploss type supported by kraken.
|
Stoploss market orders is the only stoploss type supported by kraken.
|
||||||
@ -90,11 +103,16 @@ class Kraken(Exchange):
|
|||||||
(careful, prices are reversed)
|
(careful, prices are reversed)
|
||||||
"""
|
"""
|
||||||
params = self._params.copy()
|
params = self._params.copy()
|
||||||
|
if self.trading_mode == TradingMode.FUTURES:
|
||||||
|
params.update({'reduceOnly': True})
|
||||||
|
|
||||||
if order_types.get('stoploss', 'market') == 'limit':
|
if order_types.get('stoploss', 'market') == 'limit':
|
||||||
ordertype = "stop-loss-limit"
|
ordertype = "stop-loss-limit"
|
||||||
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
||||||
limit_rate = stop_price * limit_price_pct
|
if side == "sell":
|
||||||
|
limit_rate = stop_price * limit_price_pct
|
||||||
|
else:
|
||||||
|
limit_rate = stop_price * (2 - limit_price_pct)
|
||||||
params['price2'] = self.price_to_precision(pair, limit_rate)
|
params['price2'] = self.price_to_precision(pair, limit_rate)
|
||||||
else:
|
else:
|
||||||
ordertype = "stop-loss"
|
ordertype = "stop-loss"
|
||||||
@ -103,13 +121,13 @@ class Kraken(Exchange):
|
|||||||
|
|
||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
dry_order = self.create_dry_run_order(
|
dry_order = self.create_dry_run_order(
|
||||||
pair, ordertype, "sell", amount, stop_price, stop_loss=True)
|
pair, ordertype, side, amount, stop_price, leverage, stop_loss=True)
|
||||||
return dry_order
|
return dry_order
|
||||||
|
|
||||||
try:
|
try:
|
||||||
amount = self.amount_to_precision(pair, amount)
|
amount = self.amount_to_precision(pair, amount)
|
||||||
|
|
||||||
order = self._api.create_order(symbol=pair, type=ordertype, side='sell',
|
order = self._api.create_order(symbol=pair, type=ordertype, side=side,
|
||||||
amount=amount, price=stop_price, params=params)
|
amount=amount, price=stop_price, params=params)
|
||||||
self._log_exchange_response('create_stoploss_order', order)
|
self._log_exchange_response('create_stoploss_order', order)
|
||||||
logger.info('stoploss order added for %s. '
|
logger.info('stoploss order added for %s. '
|
||||||
@ -117,18 +135,81 @@ class Kraken(Exchange):
|
|||||||
return order
|
return order
|
||||||
except ccxt.InsufficientFunds as e:
|
except ccxt.InsufficientFunds as e:
|
||||||
raise InsufficientFundsError(
|
raise InsufficientFundsError(
|
||||||
f'Insufficient funds to create {ordertype} sell order on market {pair}. '
|
f'Insufficient funds to create {ordertype} {side} order on market {pair}. '
|
||||||
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
except ccxt.InvalidOrder as e:
|
except ccxt.InvalidOrder as e:
|
||||||
raise InvalidOrderException(
|
raise InvalidOrderException(
|
||||||
f'Could not create {ordertype} sell order on market {pair}. '
|
f'Could not create {ordertype} {side} order on market {pair}. '
|
||||||
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
||||||
f'Message: {e}') from e
|
f'Message: {e}') from e
|
||||||
except ccxt.DDoSProtection as e:
|
except ccxt.DDoSProtection as e:
|
||||||
raise DDosProtection(e) from e
|
raise DDosProtection(e) from e
|
||||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||||
raise TemporaryError(
|
raise TemporaryError(
|
||||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}') from e
|
f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}') from e
|
||||||
except ccxt.BaseError as e:
|
except ccxt.BaseError as e:
|
||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
|
def _set_leverage(
|
||||||
|
self,
|
||||||
|
leverage: float,
|
||||||
|
pair: Optional[str] = None,
|
||||||
|
trading_mode: Optional[TradingMode] = None
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Kraken set's the leverage as an option in the order object, so we need to
|
||||||
|
add it to params
|
||||||
|
"""
|
||||||
|
return
|
||||||
|
|
||||||
|
def _get_params(
|
||||||
|
self,
|
||||||
|
ordertype: str,
|
||||||
|
leverage: float,
|
||||||
|
reduceOnly: bool,
|
||||||
|
time_in_force: str = 'gtc'
|
||||||
|
) -> Dict:
|
||||||
|
params = super()._get_params(
|
||||||
|
ordertype=ordertype,
|
||||||
|
leverage=leverage,
|
||||||
|
reduceOnly=reduceOnly,
|
||||||
|
time_in_force=time_in_force,
|
||||||
|
)
|
||||||
|
if leverage > 1.0:
|
||||||
|
params['leverage'] = round(leverage)
|
||||||
|
return params
|
||||||
|
|
||||||
|
def calculate_funding_fees(
|
||||||
|
self,
|
||||||
|
df: DataFrame,
|
||||||
|
amount: float,
|
||||||
|
is_short: bool,
|
||||||
|
open_date: datetime,
|
||||||
|
close_date: Optional[datetime] = None,
|
||||||
|
time_in_ratio: Optional[float] = None
|
||||||
|
) -> float:
|
||||||
|
"""
|
||||||
|
# ! This method will always error when run by Freqtrade because time_in_ratio is never
|
||||||
|
# ! passed to _get_funding_fee. For kraken futures to work in dry run and backtesting
|
||||||
|
# ! functionality must be added that passes the parameter time_in_ratio to
|
||||||
|
# ! _get_funding_fee when using Kraken
|
||||||
|
calculates the sum of all funding fees that occurred for a pair during a futures trade
|
||||||
|
:param df: Dataframe containing combined funding and mark rates
|
||||||
|
as `open_fund` and `open_mark`.
|
||||||
|
:param amount: The quantity of the trade
|
||||||
|
:param is_short: trade direction
|
||||||
|
:param open_date: The date and time that the trade started
|
||||||
|
:param close_date: The date and time that the trade ended
|
||||||
|
:param time_in_ratio: Not used by most exchange classes
|
||||||
|
"""
|
||||||
|
if not time_in_ratio:
|
||||||
|
raise OperationalException(
|
||||||
|
f"time_in_ratio is required for {self.name}._get_funding_fee")
|
||||||
|
fees: float = 0
|
||||||
|
|
||||||
|
if not df.empty:
|
||||||
|
df = df[(df['date'] >= open_date) & (df['date'] <= close_date)]
|
||||||
|
fees = sum(df['open_fund'] * df['open_mark'] * amount * time_in_ratio)
|
||||||
|
|
||||||
|
return fees if is_short else -fees
|
||||||
|
@ -25,9 +25,10 @@ class Kucoin(Exchange):
|
|||||||
"l2_limit_range_required": False,
|
"l2_limit_range_required": False,
|
||||||
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
||||||
"time_in_force_parameter": "timeInForce",
|
"time_in_force_parameter": "timeInForce",
|
||||||
|
"ohlcv_candle_limit": 1500,
|
||||||
}
|
}
|
||||||
|
|
||||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Verify stop_loss against stoploss-order value (limit or price)
|
Verify stop_loss against stoploss-order value (limit or price)
|
||||||
Returns True if adjustment is necessary.
|
Returns True if adjustment is necessary.
|
||||||
|
@ -1,7 +1,12 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Dict
|
from typing import Dict, List, Tuple
|
||||||
|
|
||||||
|
import ccxt
|
||||||
|
|
||||||
|
from freqtrade.enums import MarginMode, TradingMode
|
||||||
|
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
|
from freqtrade.exchange.common import retrier
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -15,4 +20,69 @@ class Okx(Exchange):
|
|||||||
|
|
||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"ohlcv_candle_limit": 300,
|
"ohlcv_candle_limit": 300,
|
||||||
|
"mark_ohlcv_timeframe": "4h",
|
||||||
|
"funding_fee_timeframe": "8h",
|
||||||
}
|
}
|
||||||
|
_ft_has_futures: Dict = {
|
||||||
|
"tickers_have_quoteVolume": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
||||||
|
# TradingMode.SPOT always supported and not required in this list
|
||||||
|
# (TradingMode.MARGIN, MarginMode.CROSS),
|
||||||
|
# (TradingMode.FUTURES, MarginMode.CROSS),
|
||||||
|
(TradingMode.FUTURES, MarginMode.ISOLATED),
|
||||||
|
]
|
||||||
|
|
||||||
|
def _get_params(
|
||||||
|
self,
|
||||||
|
ordertype: str,
|
||||||
|
leverage: float,
|
||||||
|
reduceOnly: bool,
|
||||||
|
time_in_force: str = 'gtc',
|
||||||
|
) -> Dict:
|
||||||
|
params = super()._get_params(
|
||||||
|
ordertype=ordertype,
|
||||||
|
leverage=leverage,
|
||||||
|
reduceOnly=reduceOnly,
|
||||||
|
time_in_force=time_in_force,
|
||||||
|
)
|
||||||
|
if self.trading_mode == TradingMode.FUTURES and self.margin_mode:
|
||||||
|
params['tdMode'] = self.margin_mode.value
|
||||||
|
return params
|
||||||
|
|
||||||
|
@retrier
|
||||||
|
def _lev_prep(self, pair: str, leverage: float, side: str):
|
||||||
|
if self.trading_mode != TradingMode.SPOT and self.margin_mode is not None:
|
||||||
|
try:
|
||||||
|
# TODO-lev: Test me properly (check mgnMode passed)
|
||||||
|
self._api.set_leverage(
|
||||||
|
leverage=leverage,
|
||||||
|
symbol=pair,
|
||||||
|
params={
|
||||||
|
"mgnMode": self.margin_mode.value,
|
||||||
|
# "posSide": "net"",
|
||||||
|
})
|
||||||
|
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
|
||||||
|
|
||||||
|
def get_max_pair_stake_amount(
|
||||||
|
self,
|
||||||
|
pair: str,
|
||||||
|
price: float,
|
||||||
|
leverage: float = 1.0
|
||||||
|
) -> float:
|
||||||
|
|
||||||
|
if self.trading_mode == TradingMode.SPOT:
|
||||||
|
return float('inf') # Not actually inf, but this probably won't matter for SPOT
|
||||||
|
|
||||||
|
if pair not in self._leverage_tiers:
|
||||||
|
return float('inf')
|
||||||
|
|
||||||
|
pair_tiers = self._leverage_tiers[pair]
|
||||||
|
return pair_tiers[-1]['max'] / leverage
|
||||||
|
File diff suppressed because it is too large
Load Diff
2
freqtrade/leverage/__init__.py
Normal file
2
freqtrade/leverage/__init__.py
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# flake8: noqa: F401
|
||||||
|
from freqtrade.leverage.interest import interest
|
43
freqtrade/leverage/interest.py
Normal file
43
freqtrade/leverage/interest.py
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
from decimal import Decimal
|
||||||
|
from math import ceil
|
||||||
|
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
|
one = Decimal(1.0)
|
||||||
|
four = Decimal(4.0)
|
||||||
|
twenty_four = Decimal(24.0)
|
||||||
|
|
||||||
|
|
||||||
|
def interest(
|
||||||
|
exchange_name: str,
|
||||||
|
borrowed: Decimal,
|
||||||
|
rate: Decimal,
|
||||||
|
hours: Decimal
|
||||||
|
) -> Decimal:
|
||||||
|
"""
|
||||||
|
Equation to calculate interest on margin trades
|
||||||
|
|
||||||
|
:param exchange_name: The exchanged being trading on
|
||||||
|
:param borrowed: The amount of currency being borrowed
|
||||||
|
:param rate: The rate of interest (i.e daily interest rate)
|
||||||
|
:param hours: The time in hours that the currency has been borrowed for
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OperationalException: Raised if freqtrade does
|
||||||
|
not support margin trading for this exchange
|
||||||
|
|
||||||
|
Returns: The amount of interest owed (currency matches borrowed)
|
||||||
|
"""
|
||||||
|
exchange_name = exchange_name.lower()
|
||||||
|
if exchange_name == "binance":
|
||||||
|
return borrowed * rate * ceil(hours) / twenty_four
|
||||||
|
elif exchange_name == "kraken":
|
||||||
|
# Rounded based on https://kraken-fees-calculator.github.io/
|
||||||
|
return borrowed * rate * (one + ceil(hours / four))
|
||||||
|
elif exchange_name == "ftx":
|
||||||
|
# As Explained under #Interest rates section in
|
||||||
|
# https://help.ftx.com/hc/en-us/articles/360053007671-Spot-Margin-Trading-Explainer
|
||||||
|
return borrowed * rate * ceil(hours) / twenty_four
|
||||||
|
else:
|
||||||
|
raise OperationalException(f"Leverage not available on {exchange_name} with freqtrade")
|
@ -2,13 +2,11 @@
|
|||||||
Various tool function for Freqtrade and scripts
|
Various tool function for Freqtrade and scripts
|
||||||
"""
|
"""
|
||||||
import gzip
|
import gzip
|
||||||
import hashlib
|
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
from copy import deepcopy
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterator, List, Union
|
from typing import Any, Iterator, List
|
||||||
from typing.io import IO
|
from typing.io import IO
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
@ -86,6 +84,22 @@ def file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool =
|
|||||||
logger.debug(f'done json to "{filename}"')
|
logger.debug(f'done json to "{filename}"')
|
||||||
|
|
||||||
|
|
||||||
|
def file_dump_joblib(filename: Path, data: Any, log: bool = True) -> None:
|
||||||
|
"""
|
||||||
|
Dump object data into a file
|
||||||
|
:param filename: file to create
|
||||||
|
:param data: Object data to save
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
import joblib
|
||||||
|
|
||||||
|
if log:
|
||||||
|
logger.info(f'dumping joblib to "{filename}"')
|
||||||
|
with open(filename, 'wb') as fp:
|
||||||
|
joblib.dump(data, fp)
|
||||||
|
logger.debug(f'done joblib dump to "{filename}"')
|
||||||
|
|
||||||
|
|
||||||
def json_load(datafile: IO) -> Any:
|
def json_load(datafile: IO) -> Any:
|
||||||
"""
|
"""
|
||||||
load data with rapidjson
|
load data with rapidjson
|
||||||
@ -116,7 +130,7 @@ def file_load_json(file):
|
|||||||
|
|
||||||
|
|
||||||
def pair_to_filename(pair: str) -> str:
|
def pair_to_filename(pair: str) -> str:
|
||||||
for ch in ['/', '-', ' ', '.', '@', '$', '+', ':']:
|
for ch in ['/', ' ', '.', '@', '$', '+', ':']:
|
||||||
pair = pair.replace(ch, '_')
|
pair = pair.replace(ch, '_')
|
||||||
return pair
|
return pair
|
||||||
|
|
||||||
@ -126,10 +140,10 @@ def format_ms_time(date: int) -> str:
|
|||||||
convert MS date to readable format.
|
convert MS date to readable format.
|
||||||
: epoch-string in ms
|
: epoch-string in ms
|
||||||
"""
|
"""
|
||||||
return datetime.fromtimestamp(date/1000.0).strftime('%Y-%m-%dT%H:%M:%S')
|
return datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%dT%H:%M:%S')
|
||||||
|
|
||||||
|
|
||||||
def deep_merge_dicts(source, destination):
|
def deep_merge_dicts(source, destination, allow_null_overrides: bool = True):
|
||||||
"""
|
"""
|
||||||
Values from Source override destination, destination is returned (and modified!!)
|
Values from Source override destination, destination is returned (and modified!!)
|
||||||
Sample:
|
Sample:
|
||||||
@ -142,8 +156,8 @@ def deep_merge_dicts(source, destination):
|
|||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
# get node or create one
|
# get node or create one
|
||||||
node = destination.setdefault(key, {})
|
node = destination.setdefault(key, {})
|
||||||
deep_merge_dicts(value, node)
|
deep_merge_dicts(value, node, allow_null_overrides)
|
||||||
else:
|
elif value is not None or allow_null_overrides:
|
||||||
destination[key] = value
|
destination[key] = value
|
||||||
|
|
||||||
return destination
|
return destination
|
||||||
@ -235,34 +249,3 @@ def parse_db_uri_for_logging(uri: str):
|
|||||||
return uri
|
return uri
|
||||||
pwd = parsed_db_uri.netloc.split(':')[1].split('@')[0]
|
pwd = parsed_db_uri.netloc.split(':')[1].split('@')[0]
|
||||||
return parsed_db_uri.geturl().replace(f':{pwd}@', ':*****@')
|
return parsed_db_uri.geturl().replace(f':{pwd}@', ':*****@')
|
||||||
|
|
||||||
|
|
||||||
def get_strategy_run_id(strategy) -> str:
|
|
||||||
"""
|
|
||||||
Generate unique identification hash for a backtest run. Identical config and strategy file will
|
|
||||||
always return an identical hash.
|
|
||||||
:param strategy: strategy object.
|
|
||||||
:return: hex string id.
|
|
||||||
"""
|
|
||||||
digest = hashlib.sha1()
|
|
||||||
config = deepcopy(strategy.config)
|
|
||||||
|
|
||||||
# Options that have no impact on results of individual backtest.
|
|
||||||
not_important_keys = ('strategy_list', 'original_config', 'telegram', 'api_server')
|
|
||||||
for k in not_important_keys:
|
|
||||||
if k in config:
|
|
||||||
del config[k]
|
|
||||||
|
|
||||||
# Explicitly allow NaN values (e.g. max_open_trades).
|
|
||||||
# as it does not matter for getting the hash.
|
|
||||||
digest.update(rapidjson.dumps(config, default=str,
|
|
||||||
number_mode=rapidjson.NM_NAN).encode('utf-8'))
|
|
||||||
with open(strategy.__file__, 'rb') as fp:
|
|
||||||
digest.update(fp.read())
|
|
||||||
return digest.hexdigest().lower()
|
|
||||||
|
|
||||||
|
|
||||||
def get_backtest_metadata_filename(filename: Union[Path, str]) -> Path:
|
|
||||||
"""Return metadata filename for specified backtest results file."""
|
|
||||||
filename = Path(filename)
|
|
||||||
return filename.parent / Path(f'{filename.stem}.meta{filename.suffix}')
|
|
||||||
|
40
freqtrade/optimize/backtest_caching.py
Normal file
40
freqtrade/optimize/backtest_caching.py
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import hashlib
|
||||||
|
from copy import deepcopy
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
import rapidjson
|
||||||
|
|
||||||
|
|
||||||
|
def get_strategy_run_id(strategy) -> str:
|
||||||
|
"""
|
||||||
|
Generate unique identification hash for a backtest run. Identical config and strategy file will
|
||||||
|
always return an identical hash.
|
||||||
|
:param strategy: strategy object.
|
||||||
|
:return: hex string id.
|
||||||
|
"""
|
||||||
|
digest = hashlib.sha1()
|
||||||
|
config = deepcopy(strategy.config)
|
||||||
|
|
||||||
|
# Options that have no impact on results of individual backtest.
|
||||||
|
not_important_keys = ('strategy_list', 'original_config', 'telegram', 'api_server')
|
||||||
|
for k in not_important_keys:
|
||||||
|
if k in config:
|
||||||
|
del config[k]
|
||||||
|
|
||||||
|
# Explicitly allow NaN values (e.g. max_open_trades).
|
||||||
|
# as it does not matter for getting the hash.
|
||||||
|
digest.update(rapidjson.dumps(config, default=str,
|
||||||
|
number_mode=rapidjson.NM_NAN).encode('utf-8'))
|
||||||
|
# Include _ft_params_from_file - so changing parameter files cause cache eviction
|
||||||
|
digest.update(rapidjson.dumps(
|
||||||
|
strategy._ft_params_from_file, default=str, number_mode=rapidjson.NM_NAN).encode('utf-8'))
|
||||||
|
with open(strategy.__file__, 'rb') as fp:
|
||||||
|
digest.update(fp.read())
|
||||||
|
return digest.hexdigest().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def get_backtest_metadata_filename(filename: Union[Path, str]) -> Path:
|
||||||
|
"""Return metadata filename for specified backtest results file."""
|
||||||
|
filename = Path(filename)
|
||||||
|
return filename.parent / Path(f'{filename.stem}.meta{filename.suffix}')
|
673
freqtrade/optimize/backtesting.py
Normal file → Executable file
673
freqtrade/optimize/backtesting.py
Normal file → Executable file
File diff suppressed because it is too large
Load Diff
@ -44,6 +44,7 @@ class EdgeCli:
|
|||||||
|
|
||||||
self.edge._timerange = TimeRange.parse_timerange(None if self.config.get(
|
self.edge._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')))
|
||||||
|
self.strategy.bot_start()
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
result = self.edge.calculate(self.config['exchange']['pair_whitelist'])
|
result = self.edge.calculate(self.config['exchange']['pair_whitelist'])
|
||||||
|
@ -10,7 +10,7 @@ import warnings
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from math import ceil
|
from math import ceil
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import progressbar
|
import progressbar
|
||||||
import rapidjson
|
import rapidjson
|
||||||
@ -114,10 +114,8 @@ class Hyperopt:
|
|||||||
self.position_stacking = self.config.get('position_stacking', False)
|
self.position_stacking = self.config.get('position_stacking', False)
|
||||||
|
|
||||||
if HyperoptTools.has_space(self.config, 'sell'):
|
if HyperoptTools.has_space(self.config, 'sell'):
|
||||||
# Make sure use_sell_signal is enabled
|
# Make sure use_exit_signal is enabled
|
||||||
if 'ask_strategy' not in self.config:
|
self.config['use_exit_signal'] = True
|
||||||
self.config['ask_strategy'] = {}
|
|
||||||
self.config['ask_strategy']['use_sell_signal'] = True
|
|
||||||
|
|
||||||
self.print_all = self.config.get('print_all', False)
|
self.print_all = self.config.get('print_all', False)
|
||||||
self.hyperopt_table_header = 0
|
self.hyperopt_table_header = 0
|
||||||
@ -292,7 +290,7 @@ class Hyperopt:
|
|||||||
self.assign_params(params_dict, 'protection')
|
self.assign_params(params_dict, 'protection')
|
||||||
|
|
||||||
if HyperoptTools.has_space(self.config, 'roi'):
|
if HyperoptTools.has_space(self.config, 'roi'):
|
||||||
self.backtesting.strategy.minimal_roi = ( # type: ignore
|
self.backtesting.strategy.minimal_roi = (
|
||||||
self.custom_hyperopt.generate_roi_table(params_dict))
|
self.custom_hyperopt.generate_roi_table(params_dict))
|
||||||
|
|
||||||
if HyperoptTools.has_space(self.config, 'stoploss'):
|
if HyperoptTools.has_space(self.config, 'stoploss'):
|
||||||
@ -396,6 +394,7 @@ class Hyperopt:
|
|||||||
|
|
||||||
def prepare_hyperopt_data(self) -> None:
|
def prepare_hyperopt_data(self) -> None:
|
||||||
data, timerange = self.backtesting.load_bt_data()
|
data, timerange = self.backtesting.load_bt_data()
|
||||||
|
self.backtesting.load_bt_data_detail()
|
||||||
logger.info("Dataload complete. Calculating indicators")
|
logger.info("Dataload complete. Calculating indicators")
|
||||||
|
|
||||||
preprocessed = self.backtesting.strategy.advise_all_indicators(data)
|
preprocessed = self.backtesting.strategy.advise_all_indicators(data)
|
||||||
@ -410,6 +409,51 @@ class Hyperopt:
|
|||||||
# Store non-trimmed data - will be trimmed after signal generation.
|
# Store non-trimmed data - will be trimmed after signal generation.
|
||||||
dump(preprocessed, self.data_pickle_file)
|
dump(preprocessed, self.data_pickle_file)
|
||||||
|
|
||||||
|
def get_asked_points(self, n_points: int) -> Tuple[List[List[Any]], List[bool]]:
|
||||||
|
"""
|
||||||
|
Enforce points returned from `self.opt.ask` have not been already evaluated
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. Try to get points using `self.opt.ask` first
|
||||||
|
2. Discard the points that have already been evaluated
|
||||||
|
3. Retry using `self.opt.ask` up to 3 times
|
||||||
|
4. If still some points are missing in respect to `n_points`, random sample some points
|
||||||
|
5. Repeat until at least `n_points` points in the `asked_non_tried` list
|
||||||
|
6. Return a list with length truncated at `n_points`
|
||||||
|
"""
|
||||||
|
def unique_list(a_list):
|
||||||
|
new_list = []
|
||||||
|
for item in a_list:
|
||||||
|
if item not in new_list:
|
||||||
|
new_list.append(item)
|
||||||
|
return new_list
|
||||||
|
i = 0
|
||||||
|
asked_non_tried: List[List[Any]] = []
|
||||||
|
is_random: List[bool] = []
|
||||||
|
while i < 5 and len(asked_non_tried) < n_points:
|
||||||
|
if i < 3:
|
||||||
|
self.opt.cache_ = {}
|
||||||
|
asked = unique_list(self.opt.ask(n_points=n_points * 5))
|
||||||
|
is_random = [False for _ in range(len(asked))]
|
||||||
|
else:
|
||||||
|
asked = unique_list(self.opt.space.rvs(n_samples=n_points * 5))
|
||||||
|
is_random = [True for _ in range(len(asked))]
|
||||||
|
is_random += [rand for x, rand in zip(asked, is_random)
|
||||||
|
if x not in self.opt.Xi
|
||||||
|
and x not in asked_non_tried]
|
||||||
|
asked_non_tried += [x for x in asked
|
||||||
|
if x not in self.opt.Xi
|
||||||
|
and x not in asked_non_tried]
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
if asked_non_tried:
|
||||||
|
return (
|
||||||
|
asked_non_tried[:min(len(asked_non_tried), n_points)],
|
||||||
|
is_random[:min(len(asked_non_tried), n_points)]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return self.opt.ask(n_points=n_points), [False for _ in range(n_points)]
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
self.random_state = self._set_random_state(self.config.get('hyperopt_random_state', None))
|
self.random_state = self._set_random_state(self.config.get('hyperopt_random_state', None))
|
||||||
logger.info(f"Using optimizer random state: {self.random_state}")
|
logger.info(f"Using optimizer random state: {self.random_state}")
|
||||||
@ -421,9 +465,10 @@ class Hyperopt:
|
|||||||
|
|
||||||
# We don't need exchange instance anymore while running hyperopt
|
# We don't need exchange instance anymore while running hyperopt
|
||||||
self.backtesting.exchange.close()
|
self.backtesting.exchange.close()
|
||||||
self.backtesting.exchange._api = None # type: ignore
|
self.backtesting.exchange._api = None
|
||||||
self.backtesting.exchange._api_async = None # type: ignore
|
self.backtesting.exchange._api_async = None
|
||||||
self.backtesting.exchange.loop = None # type: ignore
|
self.backtesting.exchange.loop = None # type: ignore
|
||||||
|
self.backtesting.exchange._loop_lock = None # type: ignore
|
||||||
# self.backtesting.exchange = None # type: ignore
|
# self.backtesting.exchange = None # type: ignore
|
||||||
self.backtesting.pairlists = None # type: ignore
|
self.backtesting.pairlists = None # type: ignore
|
||||||
|
|
||||||
@ -474,7 +519,7 @@ class Hyperopt:
|
|||||||
n_rest = (i + 1) * jobs - self.total_epochs
|
n_rest = (i + 1) * jobs - self.total_epochs
|
||||||
current_jobs = jobs - n_rest if n_rest > 0 else jobs
|
current_jobs = jobs - n_rest if n_rest > 0 else jobs
|
||||||
|
|
||||||
asked = self.opt.ask(n_points=current_jobs)
|
asked, is_random = self.get_asked_points(n_points=current_jobs)
|
||||||
f_val = self.run_optimizer_parallel(parallel, asked, i)
|
f_val = self.run_optimizer_parallel(parallel, asked, i)
|
||||||
self.opt.tell(asked, [v['loss'] for v in f_val])
|
self.opt.tell(asked, [v['loss'] for v in f_val])
|
||||||
|
|
||||||
@ -493,6 +538,7 @@ class Hyperopt:
|
|||||||
# evaluations can take different time. Here they are aligned in the
|
# evaluations can take different time. Here they are aligned in the
|
||||||
# order they will be shown to the user.
|
# order they will be shown to the user.
|
||||||
val['is_best'] = is_best
|
val['is_best'] = is_best
|
||||||
|
val['is_random'] = is_random[j]
|
||||||
self.print_results(val)
|
self.print_results(val)
|
||||||
|
|
||||||
if is_best:
|
if is_best:
|
||||||
|
@ -10,7 +10,7 @@ from typing import Any, Dict
|
|||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.data.btanalysis import calculate_max_drawdown
|
from freqtrade.data.metrics import calculate_max_drawdown
|
||||||
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||||
|
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user