Merge branch 'develop' into pr/orehunt/3059
This commit is contained in:
commit
b990ace32d
@ -1,17 +0,0 @@
|
|||||||
version: 1
|
|
||||||
|
|
||||||
update_configs:
|
|
||||||
- package_manager: "python"
|
|
||||||
directory: "/"
|
|
||||||
update_schedule: "weekly"
|
|
||||||
allowed_updates:
|
|
||||||
- match:
|
|
||||||
update_type: "all"
|
|
||||||
target_branch: "develop"
|
|
||||||
|
|
||||||
- package_manager: "docker"
|
|
||||||
directory: "/"
|
|
||||||
update_schedule: "daily"
|
|
||||||
allowed_updates:
|
|
||||||
- match:
|
|
||||||
update_type: "all"
|
|
18
.devcontainer/Dockerfile
Normal file
18
.devcontainer/Dockerfile
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
FROM freqtradeorg/freqtrade:develop
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
COPY requirements-dev.txt /freqtrade/
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get -y install git sudo vim \
|
||||||
|
&& apt-get clean \
|
||||||
|
&& pip install autopep8 -r docs/requirements-docs.txt -r requirements-dev.txt --no-cache-dir \
|
||||||
|
&& useradd -u 1000 -U -m ftuser \
|
||||||
|
&& mkdir -p /home/ftuser/.vscode-server /home/ftuser/.vscode-server-insiders /home/ftuser/commandhistory \
|
||||||
|
&& echo "export PROMPT_COMMAND='history -a'" >> /home/ftuser/.bashrc \
|
||||||
|
&& echo "export HISTFILE=~/commandhistory/.bash_history" >> /home/ftuser/.bashrc \
|
||||||
|
&& chown ftuser: -R /home/ftuser/
|
||||||
|
|
||||||
|
USER ftuser
|
||||||
|
|
||||||
|
# Empty the ENTRYPOINT to allow all commands
|
||||||
|
ENTRYPOINT []
|
44
.devcontainer/devcontainer.json
Normal file
44
.devcontainer/devcontainer.json
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "freqtrade Develop",
|
||||||
|
|
||||||
|
"dockerComposeFile": [
|
||||||
|
"docker-compose.yml"
|
||||||
|
],
|
||||||
|
|
||||||
|
"service": "ft_vscode",
|
||||||
|
|
||||||
|
"workspaceFolder": "/freqtrade/",
|
||||||
|
|
||||||
|
"settings": {
|
||||||
|
"terminal.integrated.shell.linux": "/bin/bash",
|
||||||
|
"editor.insertSpaces": true,
|
||||||
|
"files.trimTrailingWhitespace": true,
|
||||||
|
"[markdown]": {
|
||||||
|
"files.trimTrailingWhitespace": false,
|
||||||
|
},
|
||||||
|
"python.pythonPath": "/usr/local/bin/python",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Add the IDs of extensions you want installed when the container is created.
|
||||||
|
"extensions": [
|
||||||
|
"ms-python.python",
|
||||||
|
"ms-python.vscode-pylance",
|
||||||
|
"davidanson.vscode-markdownlint",
|
||||||
|
"ms-azuretools.vscode-docker",
|
||||||
|
],
|
||||||
|
|
||||||
|
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||||
|
// "forwardPorts": [],
|
||||||
|
|
||||||
|
// Uncomment the next line if you want start specific services in your Docker Compose config.
|
||||||
|
// "runServices": [],
|
||||||
|
|
||||||
|
// Uncomment the next line if you want to keep your containers running after VS Code shuts down.
|
||||||
|
// "shutdownAction": "none",
|
||||||
|
|
||||||
|
// Uncomment the next line to run commands after the container is created - for example installing curl.
|
||||||
|
// "postCreateCommand": "sudo apt-get update && apt-get install -y git",
|
||||||
|
|
||||||
|
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
|
||||||
|
"remoteUser": "ftuser"
|
||||||
|
}
|
24
.devcontainer/docker-compose.yml
Normal file
24
.devcontainer/docker-compose.yml
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
ft_vscode:
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: ".devcontainer/Dockerfile"
|
||||||
|
volumes:
|
||||||
|
# Allow git usage within container
|
||||||
|
- "${HOME}/.ssh:/home/ftuser/.ssh:ro"
|
||||||
|
- "${HOME}/.gitconfig:/home/ftuser/.gitconfig:ro"
|
||||||
|
- ..:/freqtrade:cached
|
||||||
|
# Persist bash-history
|
||||||
|
- freqtrade-vscode-server:/home/ftuser/.vscode-server
|
||||||
|
- freqtrade-bashhistory:/home/ftuser/commandhistory
|
||||||
|
# Expose API port
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8080:8080"
|
||||||
|
command: /bin/sh -c "while sleep 1000; do :; done"
|
||||||
|
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
freqtrade-vscode-server:
|
||||||
|
freqtrade-bashhistory:
|
@ -13,3 +13,4 @@ CONTRIBUTING.md
|
|||||||
MANIFEST.in
|
MANIFEST.in
|
||||||
README.md
|
README.md
|
||||||
freqtrade.service
|
freqtrade.service
|
||||||
|
user_data
|
||||||
|
13
.github/dependabot.yml
vendored
Normal file
13
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: docker
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
open-pull-requests-limit: 10
|
||||||
|
- package-ecosystem: pip
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
||||||
|
open-pull-requests-limit: 10
|
||||||
|
target-branch: develop
|
151
.github/workflows/ci.yml
vendored
151
.github/workflows/ci.yml
vendored
@ -4,48 +4,132 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- stable
|
||||||
- develop
|
- develop
|
||||||
- github_actions_tests
|
|
||||||
tags:
|
tags:
|
||||||
release:
|
release:
|
||||||
types: [published]
|
types: [published]
|
||||||
pull_request:
|
pull_request:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '0 5 * * 4'
|
- cron: '0 5 * * 4'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build_linux:
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ ubuntu-18.04, macos-latest ]
|
os: [ ubuntu-18.04, ubuntu-20.04 ]
|
||||||
python-version: [3.7, 3.8]
|
python-version: [3.7, 3.8, 3.9]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v2
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
- name: Cache_dependencies
|
- name: Cache_dependencies
|
||||||
uses: actions/cache@v1
|
uses: actions/cache@v2
|
||||||
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@preview
|
uses: actions/cache@v2
|
||||||
if: startsWith(matrix.os, 'ubuntu')
|
if: startsWith(matrix.os, 'ubuntu')
|
||||||
with:
|
with:
|
||||||
path: ~/.cache/pip
|
path: ~/.cache/pip
|
||||||
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip
|
||||||
|
|
||||||
|
- name: TA binary *nix
|
||||||
|
if: steps.cache.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
cd build_helpers && ./install_ta-lib.sh ${HOME}/dependencies/; cd ..
|
||||||
|
|
||||||
|
- name: Installation - *nix
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH
|
||||||
|
export TA_LIBRARY_PATH=${HOME}/dependencies/lib
|
||||||
|
export TA_INCLUDE_PATH=${HOME}/dependencies/include
|
||||||
|
pip install -r requirements-dev.txt
|
||||||
|
pip install -e .
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: |
|
||||||
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
|
||||||
|
- name: Coveralls
|
||||||
|
if: (startsWith(matrix.os, 'ubuntu-20') && matrix.python-version == '3.8')
|
||||||
|
env:
|
||||||
|
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||||
|
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||||
|
run: |
|
||||||
|
# Allow failure for coveralls
|
||||||
|
coveralls -v || true
|
||||||
|
|
||||||
|
- name: Backtesting
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade backtesting --datadir tests/testdata --strategy SampleStrategy
|
||||||
|
|
||||||
|
- name: Hyperopt
|
||||||
|
run: |
|
||||||
|
cp config.json.example config.json
|
||||||
|
freqtrade create-userdir --userdir user_data
|
||||||
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||||
|
|
||||||
|
- name: Flake8
|
||||||
|
run: |
|
||||||
|
flake8
|
||||||
|
|
||||||
|
- name: Sort imports (isort)
|
||||||
|
run: |
|
||||||
|
isort --check .
|
||||||
|
|
||||||
|
- name: Mypy
|
||||||
|
run: |
|
||||||
|
mypy freqtrade scripts
|
||||||
|
|
||||||
|
- name: Slack Notification
|
||||||
|
uses: homoluctus/slatify@v1.8.0
|
||||||
|
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
|
with:
|
||||||
|
type: ${{ job.status }}
|
||||||
|
job_name: '*Freqtrade CI ${{ matrix.os }}*'
|
||||||
|
mention: 'here'
|
||||||
|
mention_if: 'failure'
|
||||||
|
channel: '#notifications'
|
||||||
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
build_macos:
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ macos-latest ]
|
||||||
|
python-version: [3.7, 3.8]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Cache_dependencies
|
||||||
|
uses: actions/cache@v2
|
||||||
|
id: cache
|
||||||
|
with:
|
||||||
|
path: ~/dependencies/
|
||||||
|
key: ${{ runner.os }}-dependencies
|
||||||
|
|
||||||
- name: pip cache (macOS)
|
- name: pip cache (macOS)
|
||||||
uses: actions/cache@preview
|
uses: actions/cache@v2
|
||||||
if: startsWith(matrix.os, 'macOS')
|
if: startsWith(matrix.os, 'macOS')
|
||||||
with:
|
with:
|
||||||
path: ~/Library/Caches/pip
|
path: ~/Library/Caches/pip
|
||||||
@ -70,7 +154,7 @@ jobs:
|
|||||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||||
|
|
||||||
- name: Coveralls
|
- name: Coveralls
|
||||||
if: (startsWith(matrix.os, 'ubuntu') && matrix.python-version == '3.8')
|
if: (startsWith(matrix.os, 'ubuntu-20') && matrix.python-version == '3.8')
|
||||||
env:
|
env:
|
||||||
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||||
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||||
@ -88,12 +172,16 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
cp config.json.example config.json
|
cp config.json.example config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||||
|
|
||||||
- name: Flake8
|
- name: Flake8
|
||||||
run: |
|
run: |
|
||||||
flake8
|
flake8
|
||||||
|
|
||||||
|
- name: Sort imports (isort)
|
||||||
|
run: |
|
||||||
|
isort --check .
|
||||||
|
|
||||||
- name: Mypy
|
- name: Mypy
|
||||||
run: |
|
run: |
|
||||||
mypy freqtrade scripts
|
mypy freqtrade scripts
|
||||||
@ -109,6 +197,7 @@ jobs:
|
|||||||
channel: '#notifications'
|
channel: '#notifications'
|
||||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
|
|
||||||
build_windows:
|
build_windows:
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
@ -121,7 +210,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v2
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
@ -150,7 +239,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
cp config.json.example config.json
|
cp config.json.example config.json
|
||||||
freqtrade create-userdir --userdir user_data
|
freqtrade create-userdir --userdir user_data
|
||||||
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --print-all
|
||||||
|
|
||||||
- name: Flake8
|
- name: Flake8
|
||||||
run: |
|
run: |
|
||||||
@ -172,7 +261,7 @@ jobs:
|
|||||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
docs_check:
|
docs_check:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
@ -180,6 +269,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
./tests/test_docs.sh
|
./tests/test_docs.sh
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: 3.8
|
||||||
|
|
||||||
|
- name: Documentation build
|
||||||
|
run: |
|
||||||
|
pip install -r docs/requirements-docs.txt
|
||||||
|
pip install mkdocs
|
||||||
|
mkdocs build
|
||||||
|
|
||||||
- name: Slack Notification
|
- name: Slack Notification
|
||||||
uses: homoluctus/slatify@v1.8.0
|
uses: homoluctus/slatify@v1.8.0
|
||||||
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)
|
||||||
@ -190,18 +290,18 @@ jobs:
|
|||||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
cleanup-prior-runs:
|
cleanup-prior-runs:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Cleanup previous runs on this branch
|
- name: Cleanup previous runs on this branch
|
||||||
uses: rokroskar/workflow-run-cleanup-action@v0.2.2
|
uses: rokroskar/workflow-run-cleanup-action@v0.2.2
|
||||||
if: "!startsWith(github.ref, 'refs/tags/') && github.ref != 'refs/heads/master' && github.repository == 'freqtrade/freqtrade'"
|
if: "!startsWith(github.ref, 'refs/tags/') && github.ref != 'refs/heads/stable' && github.repository == 'freqtrade/freqtrade'"
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
||||||
|
|
||||||
# Notify on slack only once - when CI completes (and after deploy) in case it's successfull
|
# Notify on slack only once - when CI completes (and after deploy) in case it's successfull
|
||||||
notify-complete:
|
notify-complete:
|
||||||
needs: [ build, build_windows, docs_check ]
|
needs: [ build_linux, build_macos, build_windows, docs_check ]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Slack Notification
|
- name: Slack Notification
|
||||||
uses: homoluctus/slatify@v1.8.0
|
uses: homoluctus/slatify@v1.8.0
|
||||||
@ -213,20 +313,21 @@ jobs:
|
|||||||
url: ${{ secrets.SLACK_WEBHOOK }}
|
url: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
|
|
||||||
deploy:
|
deploy:
|
||||||
needs: [ build, build_windows, docs_check ]
|
needs: [ build_linux, build_macos, build_windows, docs_check ]
|
||||||
runs-on: ubuntu-18.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'
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v2
|
||||||
with:
|
with:
|
||||||
python-version: 3.8
|
python-version: 3.8
|
||||||
|
|
||||||
- name: Extract branch name
|
- name: Extract branch name
|
||||||
shell: bash
|
shell: bash
|
||||||
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
|
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF##*/})"
|
||||||
id: extract_branch
|
id: extract_branch
|
||||||
|
|
||||||
- name: Build distribution
|
- name: Build distribution
|
||||||
@ -236,7 +337,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Publish to PyPI (Test)
|
- name: Publish to PyPI (Test)
|
||||||
uses: pypa/gh-action-pypi-publish@master
|
uses: pypa/gh-action-pypi-publish@master
|
||||||
if: (steps.extract_branch.outputs.branch == 'master' || github.event_name == 'release')
|
if: (github.event_name == 'release')
|
||||||
with:
|
with:
|
||||||
user: __token__
|
user: __token__
|
||||||
password: ${{ secrets.pypi_test_password }}
|
password: ${{ secrets.pypi_test_password }}
|
||||||
@ -244,7 +345,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Publish to PyPI
|
- name: Publish to PyPI
|
||||||
uses: pypa/gh-action-pypi-publish@master
|
uses: pypa/gh-action-pypi-publish@master
|
||||||
if: (steps.extract_branch.outputs.branch == 'master' || github.event_name == 'release')
|
if: (github.event_name == 'release')
|
||||||
with:
|
with:
|
||||||
user: __token__
|
user: __token__
|
||||||
password: ${{ secrets.pypi_password }}
|
password: ${{ secrets.pypi_password }}
|
||||||
|
2
.github/workflows/docker_update_readme.yml
vendored
2
.github/workflows/docker_update_readme.yml
vendored
@ -2,7 +2,7 @@ name: Update Docker Hub Description
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- stable
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
dockerHubDescription:
|
dockerHubDescription:
|
||||||
|
@ -4,5 +4,5 @@ build:
|
|||||||
image: latest
|
image: latest
|
||||||
|
|
||||||
python:
|
python:
|
||||||
version: 3.6
|
version: 3.8
|
||||||
setup_py_install: false
|
setup_py_install: false
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
os:
|
os:
|
||||||
- linux
|
- linux
|
||||||
dist: xenial
|
dist: bionic
|
||||||
language: python
|
language: python
|
||||||
python:
|
python:
|
||||||
- 3.6
|
- 3.8
|
||||||
services:
|
services:
|
||||||
- docker
|
- docker
|
||||||
env:
|
env:
|
||||||
@ -33,7 +33,7 @@ jobs:
|
|||||||
- script:
|
- script:
|
||||||
- cp config.json.example config.json
|
- cp config.json.example config.json
|
||||||
- freqtrade create-userdir --userdir user_data
|
- freqtrade create-userdir --userdir user_data
|
||||||
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt
|
- freqtrade hyperopt --datadir tests/testdata -e 5 --strategy SampleStrategy --hyperopt SampleHyperOpt --hyperopt-loss SharpeHyperOptLossDaily
|
||||||
name: hyperopt
|
name: hyperopt
|
||||||
- script: flake8
|
- script: flake8
|
||||||
name: flake8
|
name: flake8
|
||||||
|
@ -8,17 +8,17 @@ Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/
|
|||||||
|
|
||||||
Few pointers for contributions:
|
Few pointers for contributions:
|
||||||
|
|
||||||
- Create your PR against the `develop` branch, not `master`.
|
- Create your PR against the `develop` branch, not `stable`.
|
||||||
- New features need to contain unit tests and must be PEP8 conformant (max-line-length = 100).
|
- New features need to contain unit tests, must conform to PEP8 (max-line-length = 100) and should be documented with the introduction PR.
|
||||||
|
- PR's can be declared as `[WIP]` - which signify Work in Progress Pull Requests (which are not finished).
|
||||||
|
|
||||||
If you are unsure, discuss the feature on our [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE)
|
If you are unsure, discuss the feature on our [discord server](https://discord.gg/MA9v74M), on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-jaut7r4m-Y17k4x5mcQES9a9swKuxbg) or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
||||||
or in a [issue](https://github.com/freqtrade/freqtrade/issues) before a PR.
|
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
|
|
||||||
Best start by reading the [documentation](https://www.freqtrade.io/) to get a feel for what is possible with the bot, or head straight to the [Developer-documentation](https://www.freqtrade.io/en/latest/developer/) (WIP) which should help you getting started.
|
Best start by reading the [documentation](https://www.freqtrade.io/) to get a feel for what is possible with the bot, or head straight to the [Developer-documentation](https://www.freqtrade.io/en/latest/developer/) (WIP) which should help you getting started.
|
||||||
|
|
||||||
## Before sending the PR:
|
## Before sending the PR
|
||||||
|
|
||||||
### 1. Run unit tests
|
### 1. Run unit tests
|
||||||
|
|
||||||
@ -64,6 +64,14 @@ Guide for installing them is [here](http://flake8.pycqa.org/en/latest/user/using
|
|||||||
mypy freqtrade
|
mypy freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 4. Ensure all imports are correct
|
||||||
|
|
||||||
|
#### Run isort
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
isort .
|
||||||
|
```
|
||||||
|
|
||||||
## (Core)-Committer Guide
|
## (Core)-Committer Guide
|
||||||
|
|
||||||
### Process: Pull Requests
|
### Process: Pull Requests
|
||||||
@ -114,6 +122,6 @@ Contributors may be given commit privileges. Preference will be given to those w
|
|||||||
1. Access to resources for cross-platform development and testing.
|
1. Access to resources for cross-platform development and testing.
|
||||||
1. Time to devote to the project regularly.
|
1. Time to devote to the project regularly.
|
||||||
|
|
||||||
Being a Committer does not grant write permission on `develop` or `master` for security reasons (Users trust Freqtrade with their Exchange API keys).
|
Being a Committer does not grant write permission on `develop` or `stable` for security reasons (Users trust Freqtrade with their Exchange API keys).
|
||||||
|
|
||||||
After being Committer for some time, a Committer may be named Core Committer and given full repository access.
|
After being Committer for some time, a Committer may be named Core Committer and given full repository access.
|
||||||
|
38
Dockerfile
38
Dockerfile
@ -1,28 +1,46 @@
|
|||||||
FROM python:3.8.3-slim-buster
|
FROM python:3.8.6-slim-buster as base
|
||||||
|
|
||||||
RUN apt-get update \
|
# Setup env
|
||||||
&& apt-get -y install curl build-essential libssl-dev \
|
ENV LANG C.UTF-8
|
||||||
&& apt-get clean \
|
ENV LC_ALL C.UTF-8
|
||||||
&& pip install --upgrade pip
|
ENV PYTHONDONTWRITEBYTECODE 1
|
||||||
|
ENV PYTHONFAULTHANDLER 1
|
||||||
|
ENV PATH=/root/.local/bin:$PATH
|
||||||
|
|
||||||
# Prepare environment
|
# Prepare environment
|
||||||
RUN mkdir /freqtrade
|
RUN mkdir /freqtrade
|
||||||
WORKDIR /freqtrade
|
WORKDIR /freqtrade
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
FROM base as python-deps
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get -y install curl build-essential libssl-dev git \
|
||||||
|
&& apt-get clean \
|
||||||
|
&& pip install --upgrade pip
|
||||||
|
|
||||||
# Install TA-lib
|
# Install TA-lib
|
||||||
COPY build_helpers/* /tmp/
|
COPY build_helpers/* /tmp/
|
||||||
RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
||||||
|
|
||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements.txt requirements-common.txt requirements-hyperopt.txt /freqtrade/
|
COPY requirements.txt requirements-hyperopt.txt /freqtrade/
|
||||||
RUN pip install numpy --no-cache-dir \
|
RUN pip install --user --no-cache-dir numpy \
|
||||||
&& pip install -r requirements-hyperopt.txt --no-cache-dir
|
&& pip install --user --no-cache-dir -r requirements-hyperopt.txt
|
||||||
|
|
||||||
|
# Copy dependencies to runtime-image
|
||||||
|
FROM base as runtime-image
|
||||||
|
COPY --from=python-deps /usr/local/lib /usr/local/lib
|
||||||
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
|
COPY --from=python-deps /root/.local /root/.local
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Install and execute
|
# Install and execute
|
||||||
COPY . /freqtrade/
|
COPY . /freqtrade/
|
||||||
RUN pip install -e . --no-cache-dir
|
RUN pip install -e . --no-cache-dir \
|
||||||
|
&& mkdir /freqtrade/user_data/
|
||||||
ENTRYPOINT ["freqtrade"]
|
ENTRYPOINT ["freqtrade"]
|
||||||
# Default to trade mode
|
# Default to trade mode
|
||||||
CMD [ "trade" ]
|
CMD [ "trade" ]
|
||||||
|
@ -1,25 +1,43 @@
|
|||||||
FROM --platform=linux/arm/v7 python:3.7.7-slim-buster
|
FROM --platform=linux/arm/v7 python:3.7.9-slim-buster as base
|
||||||
|
|
||||||
RUN apt-get update \
|
# Setup env
|
||||||
&& apt-get -y install curl build-essential libssl-dev libatlas3-base libgfortran5 \
|
ENV LANG C.UTF-8
|
||||||
&& apt-get clean \
|
ENV LC_ALL C.UTF-8
|
||||||
&& pip install --upgrade pip \
|
ENV PYTHONDONTWRITEBYTECODE 1
|
||||||
&& echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > /etc/pip.conf
|
ENV PYTHONFAULTHANDLER 1
|
||||||
|
ENV PATH=/root/.local/bin:$PATH
|
||||||
|
|
||||||
# Prepare environment
|
# Prepare environment
|
||||||
RUN mkdir /freqtrade
|
RUN mkdir /freqtrade
|
||||||
WORKDIR /freqtrade
|
WORKDIR /freqtrade
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get -y install libatlas3-base curl sqlite3 \
|
||||||
|
&& apt-get clean
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
FROM base as python-deps
|
||||||
|
RUN apt-get -y install build-essential libssl-dev libffi-dev libgfortran5 \
|
||||||
|
&& apt-get clean \
|
||||||
|
&& pip install --upgrade pip \
|
||||||
|
&& echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > /etc/pip.conf
|
||||||
|
|
||||||
# Install TA-lib
|
# Install TA-lib
|
||||||
COPY build_helpers/* /tmp/
|
COPY build_helpers/* /tmp/
|
||||||
RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
RUN cd /tmp && /tmp/install_ta-lib.sh && rm -r /tmp/*ta-lib*
|
||||||
|
|
||||||
ENV LD_LIBRARY_PATH /usr/local/lib
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements.txt requirements-common.txt /freqtrade/
|
COPY requirements.txt /freqtrade/
|
||||||
RUN pip install numpy --no-cache-dir \
|
RUN pip install --user --no-cache-dir numpy \
|
||||||
&& pip install -r requirements.txt --no-cache-dir
|
&& pip install --user --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Copy dependencies to runtime-image
|
||||||
|
FROM base as runtime-image
|
||||||
|
COPY --from=python-deps /usr/local/lib /usr/local/lib
|
||||||
|
ENV LD_LIBRARY_PATH /usr/local/lib
|
||||||
|
|
||||||
|
COPY --from=python-deps /root/.local /root/.local
|
||||||
|
|
||||||
# Install and execute
|
# Install and execute
|
||||||
COPY . /freqtrade/
|
COPY . /freqtrade/
|
||||||
|
52
README.md
52
README.md
@ -37,7 +37,7 @@ Please find the complete documentation on our [website](https://www.freqtrade.io
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- [x] **Based on Python 3.6+**: For botting on any operating system - Windows, macOS and Linux.
|
- [x] **Based on Python 3.7+**: For botting on any operating system - Windows, macOS and Linux.
|
||||||
- [x] **Persistence**: Persistence is achieved through sqlite.
|
- [x] **Persistence**: Persistence is achieved through sqlite.
|
||||||
- [x] **Dry-run**: Run the bot without playing money.
|
- [x] **Dry-run**: Run the bot without playing money.
|
||||||
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
||||||
@ -55,9 +55,8 @@ Please find the complete documentation on our [website](https://www.freqtrade.io
|
|||||||
Freqtrade provides a Linux/macOS script to install all dependencies and help you to configure the bot.
|
Freqtrade provides a Linux/macOS script to install all dependencies and help you to configure the bot.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone git@github.com:freqtrade/freqtrade.git
|
git clone -b develop https://github.com/freqtrade/freqtrade.git
|
||||||
cd freqtrade
|
cd freqtrade
|
||||||
git checkout develop
|
|
||||||
./setup.sh --install
|
./setup.sh --install
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -82,7 +81,8 @@ positional arguments:
|
|||||||
new-hyperopt Create new hyperopt
|
new-hyperopt Create new hyperopt
|
||||||
new-strategy Create new strategy
|
new-strategy Create new strategy
|
||||||
download-data Download backtesting data.
|
download-data Download backtesting data.
|
||||||
convert-data Convert candle (OHLCV) data from one format to another.
|
convert-data Convert candle (OHLCV) data from one format to
|
||||||
|
another.
|
||||||
convert-trade-data Convert trade data from one format to another.
|
convert-trade-data Convert trade data from one format to another.
|
||||||
backtesting Backtesting module.
|
backtesting Backtesting module.
|
||||||
edge Edge module.
|
edge Edge module.
|
||||||
@ -94,7 +94,7 @@ positional arguments:
|
|||||||
list-markets Print markets on exchange.
|
list-markets Print markets on exchange.
|
||||||
list-pairs Print pairs on exchange.
|
list-pairs Print pairs on exchange.
|
||||||
list-strategies Print available strategies.
|
list-strategies Print available strategies.
|
||||||
list-timeframes Print available ticker intervals (timeframes) for the exchange.
|
list-timeframes Print available timeframes for the exchange.
|
||||||
show-trades Show trades.
|
show-trades Show trades.
|
||||||
test-pairlist Test your pairlist configuration.
|
test-pairlist Test your pairlist configuration.
|
||||||
plot-dataframe Plot candles with indicators.
|
plot-dataframe Plot candles with indicators.
|
||||||
@ -110,35 +110,35 @@ optional arguments:
|
|||||||
|
|
||||||
Telegram is not mandatory. However, this is a great way to control your bot. More details and the full command list on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
Telegram is not mandatory. However, this is a great way to control your bot. More details and the full command list on our [documentation](https://www.freqtrade.io/en/latest/telegram-usage/)
|
||||||
|
|
||||||
- `/start`: Starts the trader
|
- `/start`: Starts the trader.
|
||||||
- `/stop`: Stops the trader
|
- `/stop`: Stops the trader.
|
||||||
- `/status [table]`: Lists all open trades
|
- `/stopbuy`: Stop entering new trades.
|
||||||
- `/count`: Displays number of open trades
|
- `/status [table]`: Lists all open trades.
|
||||||
- `/profit`: Lists cumulative profit from all finished trades
|
- `/profit`: Lists cumulative profit from all finished trades
|
||||||
- `/forcesell <trade_id>|all`: Instantly sells the given trade (Ignoring `minimum_roi`).
|
- `/forcesell <trade_id>|all`: Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||||
- `/performance`: Show performance of each finished trade grouped by pair
|
- `/performance`: Show performance of each finished trade grouped by pair
|
||||||
- `/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.
|
||||||
- `/help`: Show help message
|
- `/help`: Show help message.
|
||||||
- `/version`: Show version
|
- `/version`: Show version.
|
||||||
|
|
||||||
|
|
||||||
## Development branches
|
## Development branches
|
||||||
|
|
||||||
The project is currently setup in two main branches:
|
The project is currently setup in two main branches:
|
||||||
|
|
||||||
- `develop` - This branch has often new features, but might also cause breaking changes.
|
- `develop` - This branch has often new features, but might also contain breaking changes. We try hard to keep this branch as stable as possible.
|
||||||
- `master` - This branch contains the latest stable release. The bot 'should' be stable on this branch, and is generally well tested.
|
- `stable` - This branch contains the latest stable release. This branch is generally well tested.
|
||||||
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
- `feat/*` - These are feature branches, which are being worked on heavily. Please don't use these unless you want to test a specific feature.
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
### Help / Slack
|
### Help / Discord / Slack
|
||||||
|
|
||||||
For any questions not covered by the documentation or for further
|
For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join our slack channel.
|
||||||
information about the bot, we encourage you to join our slack channel.
|
|
||||||
|
|
||||||
- [Click here to join Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE).
|
Please check out our [discord server](https://discord.gg/MA9v74M).
|
||||||
|
|
||||||
|
You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-jaut7r4m-Y17k4x5mcQES9a9swKuxbg).
|
||||||
|
|
||||||
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
### [Bugs / Issues](https://github.com/freqtrade/freqtrade/issues?q=is%3Aissue)
|
||||||
|
|
||||||
@ -166,18 +166,18 @@ Please read our
|
|||||||
[Contributing document](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
[Contributing document](https://github.com/freqtrade/freqtrade/blob/develop/CONTRIBUTING.md)
|
||||||
to understand the requirements before sending your pull-requests.
|
to understand the requirements before sending your pull-requests.
|
||||||
|
|
||||||
Coding is not a neccessity to contribute - maybe start with improving our documentation?
|
Coding is not a necessity to contribute - maybe start with improving our documentation?
|
||||||
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
Issues labeled [good first issue](https://github.com/freqtrade/freqtrade/labels/good%20first%20issue) can be good first contributions, and will help get you familiar with the codebase.
|
||||||
|
|
||||||
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it.
|
**Note** before starting any major new feature work, *please open an issue describing what you are planning to do* or talk to us on [discord](https://discord.gg/MA9v74M) or [Slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-jaut7r4m-Y17k4x5mcQES9a9swKuxbg). This will ensure that interested parties can give valuable feedback on the feature, and let others know that you are working on it.
|
||||||
|
|
||||||
**Important:** Always create your PR against the `develop` branch, not `master`.
|
**Important:** Always create your PR against the `develop` branch, not `stable`.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
### Uptodate clock
|
### Up-to-date clock
|
||||||
|
|
||||||
The clock must be accurate, syncronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
The clock must be accurate, synchronized to a NTP server very frequently to avoid problems with communication to the exchanges.
|
||||||
|
|
||||||
### Min hardware required
|
### Min hardware required
|
||||||
|
|
||||||
@ -187,7 +187,7 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
|
|
||||||
### Software requirements
|
### Software requirements
|
||||||
|
|
||||||
- [Python 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
- [Python 3.7.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||||
- [pip](https://pip.pypa.io/en/stable/installing/)
|
- [pip](https://pip.pypa.io/en/stable/installing/)
|
||||||
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||||
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
- [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html)
|
||||||
|
Binary file not shown.
Binary file not shown.
BIN
build_helpers/TA_Lib-0.4.19-cp37-cp37m-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.19-cp37-cp37m-win_amd64.whl
Normal file
Binary file not shown.
BIN
build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
Normal file
BIN
build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
Normal file
Binary file not shown.
@ -7,10 +7,10 @@ python -m pip install --upgrade pip
|
|||||||
$pyv = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
|
$pyv = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
|
||||||
|
|
||||||
if ($pyv -eq '3.7') {
|
if ($pyv -eq '3.7') {
|
||||||
pip install build_helpers\TA_Lib-0.4.18-cp37-cp37m-win_amd64.whl
|
pip install build_helpers\TA_Lib-0.4.19-cp37-cp37m-win_amd64.whl
|
||||||
}
|
}
|
||||||
if ($pyv -eq '3.8') {
|
if ($pyv -eq '3.8') {
|
||||||
pip install build_helpers\TA_Lib-0.4.18-cp38-cp38-win_amd64.whl
|
pip install build_helpers\TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
|
||||||
}
|
}
|
||||||
|
|
||||||
pip install -r requirements-dev.txt
|
pip install -r requirements-dev.txt
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
# Replace / with _ to create a valid tag
|
# Replace / with _ to create a valid tag
|
||||||
TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g")
|
TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g")
|
||||||
|
TAG_PLOT=${TAG}_plot
|
||||||
echo "Running for ${TAG}"
|
echo "Running for ${TAG}"
|
||||||
|
|
||||||
# Add commit and commit_message to docker container
|
# Add commit and commit_message to docker container
|
||||||
@ -16,6 +17,12 @@ else
|
|||||||
docker pull ${IMAGE_NAME}:${TAG}
|
docker pull ${IMAGE_NAME}:${TAG}
|
||||||
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
docker build --cache-from ${IMAGE_NAME}:${TAG} -t freqtrade:${TAG} .
|
||||||
fi
|
fi
|
||||||
|
# Tag image for upload and next build step
|
||||||
|
docker tag freqtrade:$TAG ${IMAGE_NAME}:$TAG
|
||||||
|
|
||||||
|
docker build --cache-from freqtrade:${TAG} --build-arg sourceimage=${TAG} -t freqtrade:${TAG_PLOT} -f docker/Dockerfile.plot .
|
||||||
|
|
||||||
|
docker tag freqtrade:$TAG_PLOT ${IMAGE_NAME}:$TAG_PLOT
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed building image"
|
echo "failed building image"
|
||||||
@ -30,8 +37,6 @@ if [ $? -ne 0 ]; then
|
|||||||
return 1
|
return 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Tag image for upload
|
|
||||||
docker tag freqtrade:$TAG ${IMAGE_NAME}:$TAG
|
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "failed tagging image"
|
echo "failed tagging image"
|
||||||
return 1
|
return 1
|
||||||
|
@ -4,17 +4,16 @@
|
|||||||
"stake_amount": 0.05,
|
"stake_amount": 0.05,
|
||||||
"tradable_balance_ratio": 0.99,
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "USD",
|
"fiat_display_currency": "USD",
|
||||||
"ticker_interval": "5m",
|
"timeframe": "5m",
|
||||||
"dry_run": false,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"trailing_stop": false,
|
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"buy": 10,
|
||||||
"sell": 30
|
"sell": 30
|
||||||
},
|
},
|
||||||
"bid_strategy": {
|
"bid_strategy": {
|
||||||
"ask_last_balance": 0.0,
|
|
||||||
"use_order_book": false,
|
"use_order_book": false,
|
||||||
|
"ask_last_balance": 0.0,
|
||||||
"order_book_top": 1,
|
"order_book_top": 1,
|
||||||
"check_depth_of_market": {
|
"check_depth_of_market": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
@ -82,6 +81,7 @@
|
|||||||
"listen_port": 8080,
|
"listen_port": 8080,
|
||||||
"verbosity": "info",
|
"verbosity": "info",
|
||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": [],
|
||||||
"username": "",
|
"username": "",
|
||||||
"password": ""
|
"password": ""
|
||||||
},
|
},
|
||||||
|
@ -4,10 +4,9 @@
|
|||||||
"stake_amount": 0.05,
|
"stake_amount": 0.05,
|
||||||
"tradable_balance_ratio": 0.99,
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "USD",
|
"fiat_display_currency": "USD",
|
||||||
"ticker_interval": "5m",
|
"timeframe": "5m",
|
||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"trailing_stop": false,
|
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"buy": 10,
|
||||||
"sell": 30
|
"sell": 30
|
||||||
@ -87,6 +86,7 @@
|
|||||||
"listen_port": 8080,
|
"listen_port": 8080,
|
||||||
"verbosity": "info",
|
"verbosity": "info",
|
||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": [],
|
||||||
"username": "",
|
"username": "",
|
||||||
"password": ""
|
"password": ""
|
||||||
},
|
},
|
||||||
|
@ -7,9 +7,9 @@
|
|||||||
"amount_reserve_percent": 0.05,
|
"amount_reserve_percent": 0.05,
|
||||||
"amend_last_stake_amount": false,
|
"amend_last_stake_amount": false,
|
||||||
"last_stake_amount_min_ratio": 0.5,
|
"last_stake_amount_min_ratio": 0.5,
|
||||||
"dry_run": false,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"ticker_interval": "5m",
|
"timeframe": "5m",
|
||||||
"trailing_stop": false,
|
"trailing_stop": false,
|
||||||
"trailing_stop_positive": 0.005,
|
"trailing_stop_positive": 0.005,
|
||||||
"trailing_stop_positive_offset": 0.0051,
|
"trailing_stop_positive_offset": 0.0051,
|
||||||
@ -64,9 +64,43 @@
|
|||||||
"sort_key": "quoteVolume",
|
"sort_key": "quoteVolume",
|
||||||
"refresh_period": 1800
|
"refresh_period": 1800
|
||||||
},
|
},
|
||||||
|
{"method": "AgeFilter", "min_days_listed": 10},
|
||||||
{"method": "PrecisionFilter"},
|
{"method": "PrecisionFilter"},
|
||||||
{"method": "PriceFilter", "low_price_ratio": 0.01},
|
{"method": "PriceFilter", "low_price_ratio": 0.01, "min_price": 0.00000010},
|
||||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005}
|
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
|
||||||
|
{
|
||||||
|
"method": "RangeStabilityFilter",
|
||||||
|
"lookback_days": 10,
|
||||||
|
"min_rate_of_change": 0.01,
|
||||||
|
"refresh_period": 1440
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"protections": [
|
||||||
|
{
|
||||||
|
"method": "StoplossGuard",
|
||||||
|
"lookback_period_candles": 60,
|
||||||
|
"trade_limit": 4,
|
||||||
|
"stop_duration_candles": 60,
|
||||||
|
"only_per_pair": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "CooldownPeriod",
|
||||||
|
"stop_duration_candles": 20
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "MaxDrawdown",
|
||||||
|
"lookback_period_candles": 200,
|
||||||
|
"trade_limit": 20,
|
||||||
|
"stop_duration_candles": 10,
|
||||||
|
"max_allowed_drawdown": 0.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "LowProfitPairs",
|
||||||
|
"lookback_period_candles": 360,
|
||||||
|
"trade_limit": 1,
|
||||||
|
"stop_duration_candles": 2,
|
||||||
|
"required_profit": 0.02
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
@ -115,7 +149,16 @@
|
|||||||
"telegram": {
|
"telegram": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"token": "your_telegram_token",
|
"token": "your_telegram_token",
|
||||||
"chat_id": "your_telegram_chat_id"
|
"chat_id": "your_telegram_chat_id",
|
||||||
|
"notification_settings": {
|
||||||
|
"status": "on",
|
||||||
|
"warning": "on",
|
||||||
|
"startup": "on",
|
||||||
|
"buy": "on",
|
||||||
|
"sell": "on",
|
||||||
|
"buy_cancel": "on",
|
||||||
|
"sell_cancel": "on"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"api_server": {
|
"api_server": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
@ -123,6 +166,7 @@
|
|||||||
"listen_port": 8080,
|
"listen_port": 8080,
|
||||||
"verbosity": "info",
|
"verbosity": "info",
|
||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": [],
|
||||||
"username": "freqtrader",
|
"username": "freqtrader",
|
||||||
"password": "SuperSecurePassword"
|
"password": "SuperSecurePassword"
|
||||||
},
|
},
|
||||||
|
@ -4,10 +4,9 @@
|
|||||||
"stake_amount": 10,
|
"stake_amount": 10,
|
||||||
"tradable_balance_ratio": 0.99,
|
"tradable_balance_ratio": 0.99,
|
||||||
"fiat_display_currency": "EUR",
|
"fiat_display_currency": "EUR",
|
||||||
"ticker_interval": "5m",
|
"timeframe": "5m",
|
||||||
"dry_run": true,
|
"dry_run": true,
|
||||||
"cancel_open_orders_on_exit": false,
|
"cancel_open_orders_on_exit": false,
|
||||||
"trailing_stop": false,
|
|
||||||
"unfilledtimeout": {
|
"unfilledtimeout": {
|
||||||
"buy": 10,
|
"buy": 10,
|
||||||
"sell": 30
|
"sell": 30
|
||||||
@ -28,12 +27,11 @@
|
|||||||
"use_sell_signal": true,
|
"use_sell_signal": true,
|
||||||
"sell_profit_only": false,
|
"sell_profit_only": false,
|
||||||
"ignore_roi_if_buy_signal": false
|
"ignore_roi_if_buy_signal": false
|
||||||
|
|
||||||
},
|
},
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "kraken",
|
"name": "kraken",
|
||||||
"key": "",
|
"key": "your_exchange_key",
|
||||||
"secret": "",
|
"secret": "your_exchange_key",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {"enableRateLimit": true},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {
|
||||||
"enableRateLimit": true,
|
"enableRateLimit": true,
|
||||||
@ -93,6 +91,7 @@
|
|||||||
"listen_port": 8080,
|
"listen_port": 8080,
|
||||||
"verbosity": "info",
|
"verbosity": "info",
|
||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": [],
|
||||||
"username": "",
|
"username": "",
|
||||||
"password": ""
|
"password": ""
|
||||||
},
|
},
|
||||||
|
@ -1,20 +0,0 @@
|
|||||||
---
|
|
||||||
version: '3'
|
|
||||||
services:
|
|
||||||
freqtrade_develop:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: "./Dockerfile.develop"
|
|
||||||
volumes:
|
|
||||||
- ".:/freqtrade"
|
|
||||||
entrypoint:
|
|
||||||
- "freqtrade"
|
|
||||||
|
|
||||||
freqtrade_bash:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: "./Dockerfile.develop"
|
|
||||||
volumes:
|
|
||||||
- ".:/freqtrade"
|
|
||||||
entrypoint:
|
|
||||||
- "/bin/bash"
|
|
@ -2,12 +2,14 @@
|
|||||||
version: '3'
|
version: '3'
|
||||||
services:
|
services:
|
||||||
freqtrade:
|
freqtrade:
|
||||||
image: freqtradeorg/freqtrade:master
|
image: freqtradeorg/freqtrade:stable
|
||||||
# image: freqtradeorg/freqtrade:develop
|
# image: freqtradeorg/freqtrade:develop
|
||||||
|
# Use plotting image
|
||||||
|
# image: freqtradeorg/freqtrade:develop_plot
|
||||||
# Build step - only needed when additional dependencies are needed
|
# Build step - only needed when additional dependencies are needed
|
||||||
# build:
|
# build:
|
||||||
# context: .
|
# context: .
|
||||||
# dockerfile: "./Dockerfile.technical"
|
# dockerfile: "./docker/Dockerfile.technical"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
container_name: freqtrade
|
container_name: freqtrade
|
||||||
volumes:
|
volumes:
|
||||||
|
@ -2,6 +2,7 @@ FROM freqtradeorg/freqtrade:develop
|
|||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY requirements-dev.txt /freqtrade/
|
COPY requirements-dev.txt /freqtrade/
|
||||||
|
|
||||||
RUN pip install numpy --no-cache-dir \
|
RUN pip install numpy --no-cache-dir \
|
||||||
&& pip install -r requirements-dev.txt --no-cache-dir
|
&& pip install -r requirements-dev.txt --no-cache-dir
|
||||||
|
|
7
docker/Dockerfile.jupyter
Normal file
7
docker/Dockerfile.jupyter
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
FROM freqtradeorg/freqtrade:develop_plot
|
||||||
|
|
||||||
|
|
||||||
|
RUN pip install jupyterlab --no-cache-dir
|
||||||
|
|
||||||
|
# Empty the ENTRYPOINT to allow all commands
|
||||||
|
ENTRYPOINT []
|
7
docker/Dockerfile.plot
Normal file
7
docker/Dockerfile.plot
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
ARG sourceimage=develop
|
||||||
|
FROM freqtradeorg/freqtrade:${sourceimage}
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
COPY requirements-plot.txt /freqtrade/
|
||||||
|
|
||||||
|
RUN pip install -r requirements-plot.txt --no-cache-dir
|
16
docker/docker-compose-jupyter.yml
Normal file
16
docker/docker-compose-jupyter.yml
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
ft_jupyterlab:
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: docker/Dockerfile.jupyter
|
||||||
|
restart: unless-stopped
|
||||||
|
container_name: freqtrade
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8888:8888"
|
||||||
|
volumes:
|
||||||
|
- "./user_data:/freqtrade/user_data"
|
||||||
|
# Default command used when running `docker compose up`
|
||||||
|
command: >
|
||||||
|
jupyter lab --port=8888 --ip 0.0.0.0 --allow-root
|
@ -27,9 +27,9 @@ class MyAwesomeHyperOpt2(MyAwesomeHyperOpt):
|
|||||||
and then quickly switch between hyperopt classes, running optimization process with hyperopt class you need in each particular case:
|
and then quickly switch between hyperopt classes, running optimization process with hyperopt class you need in each particular case:
|
||||||
|
|
||||||
```
|
```
|
||||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt ...
|
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...
|
||||||
or
|
or
|
||||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 ...
|
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...
|
||||||
```
|
```
|
||||||
|
|
||||||
## Creating and using a custom loss function
|
## Creating and using a custom loss function
|
||||||
@ -77,7 +77,7 @@ Currently, the arguments are:
|
|||||||
|
|
||||||
* `results`: DataFrame containing the result
|
* `results`: DataFrame containing the result
|
||||||
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
|
||||||
`pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason`
|
`pair, profit_percent, profit_abs, open_date, open_rate, open_fee, close_date, close_rate, close_fee, amount, trade_duration, open_at_end, sell_reason`
|
||||||
* `trade_count`: Amount of trades (identical to `len(results)`)
|
* `trade_count`: Amount of trades (identical to `len(results)`)
|
||||||
* `min_date`: Start date of the hyperopting TimeFrame
|
* `min_date`: Start date of the hyperopting TimeFrame
|
||||||
* `min_date`: End date of the hyperopting TimeFrame
|
* `min_date`: End date of the hyperopting TimeFrame
|
||||||
|
@ -4,6 +4,54 @@ This page explains some advanced tasks and configuration options that can be per
|
|||||||
|
|
||||||
If you do not know what things mentioned here mean, you probably do not need it.
|
If you do not know what things mentioned here mean, you probably do not need it.
|
||||||
|
|
||||||
|
## Running multiple instances of Freqtrade
|
||||||
|
|
||||||
|
This section will show you how to run multiple bots at the same time, on the same machine.
|
||||||
|
|
||||||
|
### Things to consider
|
||||||
|
|
||||||
|
* Use different database files.
|
||||||
|
* Use different Telegram bots (requires multiple different configuration files; applies only when Telegram is enabled).
|
||||||
|
* Use different ports (applies only when Freqtrade REST API webserver is enabled).
|
||||||
|
|
||||||
|
### Different database files
|
||||||
|
|
||||||
|
In order to keep track of your trades, profits, etc., freqtrade is using a SQLite database where it stores various types of information such as the trades you performed in the past and the current position(s) you are holding at any time. This allows you to keep track of your profits, but most importantly, keep track of ongoing activity if the bot process would be restarted or would be terminated unexpectedly.
|
||||||
|
|
||||||
|
Freqtrade will, by default, use separate database files for dry-run and live bots (this assumes no database-url is given in either configuration nor via command line argument).
|
||||||
|
For live trading mode, the default database will be `tradesv3.sqlite` and for dry-run it will be `tradesv3.dryrun.sqlite`.
|
||||||
|
|
||||||
|
The optional argument to the trade command used to specify the path of these files is `--db-url`, which requires a valid SQLAlchemy url.
|
||||||
|
So when you are starting a bot with only the config and strategy arguments in dry-run mode, the following 2 commands would have the same outcome.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade trade -c MyConfig.json -s MyStrategy
|
||||||
|
# is equivalent to
|
||||||
|
freqtrade trade -c MyConfig.json -s MyStrategy --db-url sqlite:///tradesv3.dryrun.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
|
It means that if you are running the trade command in two different terminals, for example to test your strategy both for trades in USDT and in another instance for trades in BTC, you will have to run them with different databases.
|
||||||
|
|
||||||
|
If you specify the URL of a database which does not exist, freqtrade will create one with the name you specified. So to test your custom strategy with BTC and USDT stake currencies, you could use the following commands (in 2 separate terminals):
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
# Terminal 1:
|
||||||
|
freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.dryrun.sqlite
|
||||||
|
# Terminal 2:
|
||||||
|
freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.dryrun.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
|
Conversely, if you wish to do the same thing in production mode, you will also have to create at least one new database (in addition to the default one) and specify the path to the "live" databases, for example:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
# Terminal 1:
|
||||||
|
freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.live.sqlite
|
||||||
|
# Terminal 2:
|
||||||
|
freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.live.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
|
For more information regarding usage of the sqlite databases, for example to manually enter or remove trades, please refer to the [SQL Cheatsheet](sql_cheatsheet.md).
|
||||||
|
|
||||||
## Configure the bot running as a systemd service
|
## Configure the bot running as a systemd service
|
||||||
|
|
||||||
Copy the `freqtrade.service` file to your systemd user directory (usually `~/.config/systemd/user`) and update `WorkingDirectory` and `ExecStart` to match your setup.
|
Copy the `freqtrade.service` file to your systemd user directory (usually `~/.config/systemd/user`) and update `WorkingDirectory` and `ExecStart` to match your setup.
|
||||||
|
@ -12,7 +12,7 @@ real data. This is what we call
|
|||||||
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
[backtesting](https://en.wikipedia.org/wiki/Backtesting).
|
||||||
|
|
||||||
Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHCLV) data from `user_data/data/<exchange>` by default.
|
Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHCLV) data from `user_data/data/<exchange>` by default.
|
||||||
If no data is available for the exchange / pair / timeframe (ticker interval) combination, backtesting will ask you to download them first using `freqtrade download-data`.
|
If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using `freqtrade download-data`.
|
||||||
For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation.
|
For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation.
|
||||||
|
|
||||||
The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
|
The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
|
||||||
@ -35,7 +35,7 @@ freqtrade backtesting
|
|||||||
#### With 1 min candle (OHLCV) data
|
#### With 1 min candle (OHLCV) data
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --ticker-interval 1m
|
freqtrade backtesting --timeframe 1m
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Using a different on-disk historical candle (OHLCV) data source
|
#### Using a different on-disk historical candle (OHLCV) data source
|
||||||
@ -58,7 +58,7 @@ Where `-s SampleStrategy` refers to the class name within the strategy file `sam
|
|||||||
#### Comparing multiple Strategies
|
#### Comparing multiple Strategies
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --ticker-interval 5m
|
freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m
|
||||||
```
|
```
|
||||||
|
|
||||||
Where `SampleStrategy1` and `AwesomeStrategy` refer to class names of strategies.
|
Where `SampleStrategy1` and `AwesomeStrategy` refer to class names of strategies.
|
||||||
@ -66,7 +66,7 @@ Where `SampleStrategy1` and `AwesomeStrategy` refer to class names of strategies
|
|||||||
#### Exporting trades to file
|
#### Exporting trades to file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade backtesting --export trades
|
freqtrade backtesting --export trades --config config.json --strategy SampleStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
The exported trades can be used for [further analysis](#further-backtest-result-analysis), or can be used by the plotting script `plot_dataframe.py` in the scripts directory.
|
The exported trades can be used for [further analysis](#further-backtest-result-analysis), or can be used by the plotting script `plot_dataframe.py` in the scripts directory.
|
||||||
@ -157,17 +157,37 @@ A backtesting result will look like that:
|
|||||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 | 0 |
|
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 | 0 |
|
||||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 | 0 |
|
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 | 0 |
|
||||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 | 0 |
|
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 | 0 |
|
||||||
|
=============== SUMMARY METRICS ===============
|
||||||
|
| Metric | Value |
|
||||||
|
|-----------------------+---------------------|
|
||||||
|
| Backtesting from | 2019-01-01 00:00:00 |
|
||||||
|
| Backtesting to | 2019-05-01 00:00:00 |
|
||||||
|
| Max open trades | 3 |
|
||||||
|
| | |
|
||||||
|
| Total trades | 429 |
|
||||||
|
| Total Profit % | 152.41% |
|
||||||
|
| Trades per day | 3.575 |
|
||||||
|
| | |
|
||||||
|
| Best Pair | LSK/BTC 26.26% |
|
||||||
|
| Worst Pair | ZEC/BTC -10.18% |
|
||||||
|
| Best Trade | LSK/BTC 4.25% |
|
||||||
|
| Worst Trade | ZEC/BTC -10.25% |
|
||||||
|
| Best day | 25.27% |
|
||||||
|
| Worst day | -30.67% |
|
||||||
|
| Avg. Duration Winners | 4:23:00 |
|
||||||
|
| Avg. Duration Loser | 6:55:00 |
|
||||||
|
| | |
|
||||||
|
| Max Drawdown | 50.63% |
|
||||||
|
| Drawdown Start | 2019-02-15 14:10:00 |
|
||||||
|
| Drawdown End | 2019-04-11 18:15:00 |
|
||||||
|
| Market change | -5.88% |
|
||||||
|
===============================================
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Backtesting report table
|
||||||
|
|
||||||
The 1st table contains all trades the bot made, including "left open trades".
|
The 1st table contains all trades the bot made, including "left open trades".
|
||||||
|
|
||||||
The 2nd table contains a recap of sell reasons.
|
|
||||||
This table can tell you which area needs some additional work (i.e. all `sell_signal` trades are losses, so we should disable the sell-signal or work on improving that).
|
|
||||||
|
|
||||||
The 3rd table contains all trades the bot had to `forcesell` at the end of the backtest period to present a full picture.
|
|
||||||
This is necessary to simulate realistic behaviour, 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 extracted separately for clarity.
|
|
||||||
|
|
||||||
The last line will give you the overall performance of your strategy,
|
The last line will give you the overall performance of your strategy,
|
||||||
here:
|
here:
|
||||||
|
|
||||||
@ -196,23 +216,87 @@ 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
|
||||||
|
|
||||||
|
The 2nd table contains a recap of sell 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).
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Summary metrics
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
```
|
||||||
|
=============== SUMMARY METRICS ===============
|
||||||
|
| Metric | Value |
|
||||||
|
|-----------------------+---------------------|
|
||||||
|
| Backtesting from | 2019-01-01 00:00:00 |
|
||||||
|
| Backtesting to | 2019-05-01 00:00:00 |
|
||||||
|
| Max open trades | 3 |
|
||||||
|
| | |
|
||||||
|
| Total trades | 429 |
|
||||||
|
| Total Profit % | 152.41% |
|
||||||
|
| Trades per day | 3.575 |
|
||||||
|
| | |
|
||||||
|
| Best Pair | LSK/BTC 26.26% |
|
||||||
|
| Worst Pair | ZEC/BTC -10.18% |
|
||||||
|
| Best Trade | LSK/BTC 4.25% |
|
||||||
|
| Worst Trade | ZEC/BTC -10.25% |
|
||||||
|
| Best day | 25.27% |
|
||||||
|
| Worst day | -30.67% |
|
||||||
|
| Avg. Duration Winners | 4:23:00 |
|
||||||
|
| Avg. Duration Loser | 6:55:00 |
|
||||||
|
| | |
|
||||||
|
| Max Drawdown | 50.63% |
|
||||||
|
| Drawdown Start | 2019-02-15 14:10:00 |
|
||||||
|
| Drawdown End | 2019-04-11 18:15:00 |
|
||||||
|
| Market change | -5.88% |
|
||||||
|
===============================================
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
- `Backtesting from` / `Backtesting to`: Backtesting range (usually defined with the `--timerange` option).
|
||||||
|
- `Max open trades`: Setting of `max_open_trades` (or `--max-open-trades`) - to clearly see settings for this.
|
||||||
|
- `Total trades`: Identical to the total trades of the backtest output table.
|
||||||
|
- `Total Profit %`: Total profit per stake amount. Aligned to the TOTAL column of the first table.
|
||||||
|
- `Trades per day`: Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy).
|
||||||
|
- `Best Pair` / `Worst Pair`: Best and worst performing pair, and it's corresponding `Cum Profit %`.
|
||||||
|
- `Best Trade` / `Worst Trade`: Biggest winning trade and biggest losing trade
|
||||||
|
- `Best day` / `Worst day`: Best and worst day based on daily profit.
|
||||||
|
- `Avg. Duration Winners` / `Avg. Duration Loser`: Average durations for winning and losing trades.
|
||||||
|
- `Max Drawdown`: Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced).
|
||||||
|
- `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.
|
||||||
|
|
||||||
### Assumptions made by backtesting
|
### Assumptions made by backtesting
|
||||||
|
|
||||||
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
|
||||||
|
|
||||||
- Buys happen at open-price
|
- Buys happen at open-price
|
||||||
- Sell signal sells happen at open-price of the following candle
|
- Sell-signal sells happen at open-price of the consecutive candle
|
||||||
- Low happens before high for stoploss, protecting capital first
|
- Sell-signal is favored over Stoploss, because sell-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%)
|
- sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell 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
|
- 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
|
||||||
- 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)
|
- 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)
|
||||||
- Stoploss sells happen exactly at stoploss price, even if low was lower
|
- 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 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
|
||||||
|
- Low happens before high for stoploss, protecting capital first
|
||||||
- Trailing stoploss
|
- Trailing stoploss
|
||||||
- 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 sells 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
|
||||||
- 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)
|
- 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)
|
||||||
- Stoploss (and trailing stoploss) is evaluated before ROI within one candle. So you can often see more trades with the `stoploss` and/or `trailing_stop` sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes.
|
- Evaluation sequence (if multiple signals happen on the same candle)
|
||||||
|
- ROI (if not stoploss)
|
||||||
|
- Sell-signal
|
||||||
|
- Stoploss
|
||||||
|
|
||||||
Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will **never** replace running a strategy in dry-run mode.
|
Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will **never** replace running a strategy in dry-run mode.
|
||||||
Also, keep in mind that past results don't guarantee future success.
|
Also, keep in mind that past results don't guarantee future success.
|
||||||
@ -228,13 +312,13 @@ You can then load the trades to perform further analysis as shown in our [data a
|
|||||||
|
|
||||||
To compare multiple strategies, a list of Strategies can be provided to backtesting.
|
To compare multiple strategies, a list of Strategies can be provided to backtesting.
|
||||||
|
|
||||||
This is limited to 1 timeframe (ticker interval) value per run. However, data is only loaded once from disk so if you have multiple
|
This is limited to 1 timeframe value per run. However, data is only loaded once from disk so if you have multiple
|
||||||
strategies you'd like to compare, this will give a nice runtime boost.
|
strategies you'd like to compare, this will give a nice runtime boost.
|
||||||
|
|
||||||
All listed Strategies need to be in the same directory.
|
All listed Strategies need to be in the same directory.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades
|
freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades
|
||||||
```
|
```
|
||||||
|
|
||||||
This will save the results to `user_data/backtest_results/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
This will save the results to `user_data/backtest_results/backtest-result-<strategy>.json`, injecting the strategy-name into the target filename.
|
||||||
|
58
docs/bot-basics.md
Normal file
58
docs/bot-basics.md
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
# Freqtrade basics
|
||||||
|
|
||||||
|
This page provides you some basic concepts on how Freqtrade works and operates.
|
||||||
|
|
||||||
|
## Freqtrade terminology
|
||||||
|
|
||||||
|
* Trade: Open position.
|
||||||
|
* Open Order: Order which is currently placed on the exchange, and is not yet complete.
|
||||||
|
* Pair: Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT).
|
||||||
|
* Timeframe: Candle length to use (e.g. `"5m"`, `"1h"`, ...).
|
||||||
|
* Indicators: Technical indicators (SMA, EMA, RSI, ...).
|
||||||
|
* Limit order: Limit orders which execute at the defined limit price or better.
|
||||||
|
* Market order: Guaranteed to fill, may move price depending on the order size.
|
||||||
|
|
||||||
|
## Fee handling
|
||||||
|
|
||||||
|
All profit calculations of Freqtrade include fees. For Backtesting / Hyperopt / Dry-run modes, the exchange default fee is used (lowest tier on the exchange). For live operations, fees are used as applied by the exchange (this includes BNB rebates etc.).
|
||||||
|
|
||||||
|
## Bot execution logic
|
||||||
|
|
||||||
|
Starting freqtrade in dry-run or live mode (using `freqtrade trade`) will start the bot and start the bot iteration loop.
|
||||||
|
By default, loop runs every few seconds (`internals.process_throttle_secs`) and does roughly the following in the following sequence:
|
||||||
|
|
||||||
|
* Fetch open trades from persistence.
|
||||||
|
* Calculate current list of tradable pairs.
|
||||||
|
* Download ohlcv data for the pairlist including all [informative pairs](strategy-customization.md#get-data-for-non-tradeable-pairs)
|
||||||
|
This step is only executed once per Candle to avoid unnecessary network traffic.
|
||||||
|
* Call `bot_loop_start()` strategy callback.
|
||||||
|
* Analyze strategy per pair.
|
||||||
|
* Call `populate_indicators()`
|
||||||
|
* Call `populate_buy_trend()`
|
||||||
|
* Call `populate_sell_trend()`
|
||||||
|
* Check timeouts for open orders.
|
||||||
|
* Calls `check_buy_timeout()` strategy callback for open buy orders.
|
||||||
|
* Calls `check_sell_timeout()` strategy callback for open sell orders.
|
||||||
|
* Verifies existing positions and eventually places sell orders.
|
||||||
|
* Considers stoploss, ROI and sell-signal.
|
||||||
|
* Determine sell-price based on `ask_strategy` configuration setting.
|
||||||
|
* Before a sell order is placed, `confirm_trade_exit()` strategy callback is called.
|
||||||
|
* Check if trade-slots are still available (if `max_open_trades` is reached).
|
||||||
|
* Verifies buy signal trying to enter new positions.
|
||||||
|
* Determine buy-price based on `bid_strategy` configuration setting.
|
||||||
|
* Before a buy order is placed, `confirm_trade_entry()` strategy callback is called.
|
||||||
|
|
||||||
|
This loop will be repeated again and again until the bot is stopped.
|
||||||
|
|
||||||
|
## Backtesting / Hyperopt execution logic
|
||||||
|
|
||||||
|
[backtesting](backtesting.md) or [hyperopt](hyperopt.md) do only part of the above logic, since most of the trading operations are fully simulated.
|
||||||
|
|
||||||
|
* Load historic data for configured pairlist.
|
||||||
|
* Calculate indicators (calls `populate_indicators()`).
|
||||||
|
* Calls `populate_buy_trend()` and `populate_sell_trend()`
|
||||||
|
* Loops per candle simulating entry and exit points.
|
||||||
|
* Generate backtest report output
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Both Backtesting and Hyperopt include exchange default Fees in the calculation. Custom fees can be passed to backtesting / hyperopt by specifying the `--fee` argument.
|
@ -5,26 +5,42 @@ This page explains the different parameters of the bot and how to run it.
|
|||||||
!!! Note
|
!!! Note
|
||||||
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
If you've used `setup.sh`, don't forget to activate your virtual environment (`source .env/bin/activate`) before running freqtrade commands.
|
||||||
|
|
||||||
|
!!! Warning "Up-to-date clock"
|
||||||
|
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
|
||||||
|
|
||||||
## Bot commands
|
## Bot commands
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade [-h] [-V]
|
usage: freqtrade [-h] [-V]
|
||||||
{trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
{trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit}
|
||||||
...
|
...
|
||||||
|
|
||||||
Free, open source crypto trading bot
|
Free, open source crypto trading bot
|
||||||
|
|
||||||
positional arguments:
|
positional arguments:
|
||||||
{trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}
|
{trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit}
|
||||||
trade Trade module.
|
trade Trade module.
|
||||||
|
create-userdir Create user-data directory.
|
||||||
|
new-config Create new config
|
||||||
|
new-hyperopt Create new hyperopt
|
||||||
|
new-strategy Create new strategy
|
||||||
|
download-data Download backtesting data.
|
||||||
|
convert-data Convert candle (OHLCV) data from one format to
|
||||||
|
another.
|
||||||
|
convert-trade-data Convert trade data from one format to another.
|
||||||
backtesting Backtesting module.
|
backtesting Backtesting module.
|
||||||
edge Edge module.
|
edge Edge module.
|
||||||
hyperopt Hyperopt module.
|
hyperopt Hyperopt module.
|
||||||
create-userdir Create user-data directory.
|
hyperopt-list List Hyperopt results
|
||||||
|
hyperopt-show Show details of Hyperopt results
|
||||||
list-exchanges Print available exchanges.
|
list-exchanges Print available exchanges.
|
||||||
list-timeframes Print available ticker intervals (timeframes) for the
|
list-hyperopts Print available hyperopt classes.
|
||||||
exchange.
|
list-markets Print markets on exchange.
|
||||||
download-data Download backtesting data.
|
list-pairs Print pairs on exchange.
|
||||||
|
list-strategies Print available strategies.
|
||||||
|
list-timeframes Print available timeframes for the exchange.
|
||||||
|
show-trades Show trades.
|
||||||
|
test-pairlist Test your pairlist configuration.
|
||||||
plot-dataframe Plot candles with indicators.
|
plot-dataframe Plot candles with indicators.
|
||||||
plot-profit Generate plot showing profits.
|
plot-profit Generate plot showing profits.
|
||||||
|
|
||||||
@ -72,7 +88,6 @@ Strategy arguments:
|
|||||||
Specify strategy class name which will be used by the
|
Specify strategy class name which will be used by the
|
||||||
bot.
|
bot.
|
||||||
--strategy-path PATH Specify additional strategy lookup path.
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -197,20 +212,25 @@ Backtesting also uses the config specified via `-c/--config`.
|
|||||||
```
|
```
|
||||||
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH] [-s NAME]
|
[-d PATH] [--userdir PATH] [-s NAME]
|
||||||
[--strategy-path PATH] [-i TICKER_INTERVAL]
|
[--strategy-path PATH] [-i TIMEFRAME]
|
||||||
[--timerange TIMERANGE] [--max-open-trades INT]
|
[--timerange TIMERANGE]
|
||||||
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
|
[--max-open-trades INT]
|
||||||
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
[--eps] [--dmmp]
|
[--eps] [--dmmp] [--enable-protections]
|
||||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||||
[--export EXPORT] [--export-filename PATH]
|
[--export EXPORT] [--export-filename PATH]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
|
||||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
`1d`).
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
|
(default: `None`).
|
||||||
--max-open-trades INT
|
--max-open-trades INT
|
||||||
Override the value of the `max_open_trades`
|
Override the value of the `max_open_trades`
|
||||||
configuration setting.
|
configuration setting.
|
||||||
@ -226,6 +246,10 @@ optional arguments:
|
|||||||
Disable applying `max_open_trades` during backtest
|
Disable applying `max_open_trades` during backtest
|
||||||
(same as setting `max_open_trades` to a very high
|
(same as setting `max_open_trades` to a very high
|
||||||
number).
|
number).
|
||||||
|
--enable-protections, --enableprotections
|
||||||
|
Enable protections for backtesting.Will slow
|
||||||
|
backtesting down by a considerable amount, but will
|
||||||
|
include configured protections
|
||||||
--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]
|
--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 ticker-interval needs to be
|
backtest. Please note that ticker-interval needs to be
|
||||||
@ -280,23 +304,27 @@ to find optimal parameter values for your strategy.
|
|||||||
```
|
```
|
||||||
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
[-i TIMEFRAME] [--timerange TIMERANGE]
|
||||||
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
[--max-open-trades INT]
|
[--max-open-trades INT]
|
||||||
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||||
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
|
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
|
||||||
[-e INT]
|
[--dmmp] [--enable-protections] [-e INT]
|
||||||
[--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
|
[--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
|
||||||
[--dmmp] [--print-all] [--no-color] [--print-json]
|
[--print-all] [--no-color] [--print-json] [-j JOBS]
|
||||||
[-j JOBS] [--random-state INT] [--min-trades INT]
|
[--random-state INT] [--min-trades INT]
|
||||||
[--continue] [--hyperopt-loss NAME]
|
[--hyperopt-loss NAME]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
|
||||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
`1d`).
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
|
(default: `None`).
|
||||||
--max-open-trades INT
|
--max-open-trades INT
|
||||||
Override the value of the `max_open_trades`
|
Override the value of the `max_open_trades`
|
||||||
configuration setting.
|
configuration setting.
|
||||||
@ -312,18 +340,22 @@ optional arguments:
|
|||||||
--eps, --enable-position-stacking
|
--eps, --enable-position-stacking
|
||||||
Allow buying the same pair multiple times (position
|
Allow buying the same pair multiple times (position
|
||||||
stacking).
|
stacking).
|
||||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
|
||||||
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
|
|
||||||
Specify which parameters to hyperopt. Space-separated
|
|
||||||
list.
|
|
||||||
--dmmp, --disable-max-market-positions
|
--dmmp, --disable-max-market-positions
|
||||||
Disable applying `max_open_trades` during backtest
|
Disable applying `max_open_trades` during backtest
|
||||||
(same as setting `max_open_trades` to a very high
|
(same as setting `max_open_trades` to a very high
|
||||||
number).
|
number).
|
||||||
|
--enable-protections, --enableprotections
|
||||||
|
Enable protections for backtesting.Will slow
|
||||||
|
backtesting down by a considerable amount, but will
|
||||||
|
include configured protections
|
||||||
|
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||||
|
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
|
||||||
|
Specify which parameters to hyperopt. Space-separated
|
||||||
|
list.
|
||||||
--print-all Print all results, not only the best ones.
|
--print-all Print all results, not only the best ones.
|
||||||
--no-color Disable colorization of hyperopt results. May be
|
--no-color Disable colorization of hyperopt results. May be
|
||||||
useful if you are redirecting output to a file.
|
useful if you are redirecting output to a file.
|
||||||
--print-json Print best results in JSON format.
|
--print-json Print output in JSON format.
|
||||||
-j JOBS, --job-workers JOBS
|
-j JOBS, --job-workers JOBS
|
||||||
The number of concurrently running jobs for
|
The number of concurrently running jobs for
|
||||||
hyperoptimization (hyperopt worker processes). If -1
|
hyperoptimization (hyperopt worker processes). If -1
|
||||||
@ -334,18 +366,14 @@ optional arguments:
|
|||||||
reproducible hyperopt results.
|
reproducible hyperopt results.
|
||||||
--min-trades INT Set minimal desired number of trades for evaluations
|
--min-trades INT Set minimal desired number of trades for evaluations
|
||||||
in the hyperopt optimization path (default: 1).
|
in the hyperopt optimization path (default: 1).
|
||||||
--continue Continue hyperopt from previous runs. By default,
|
|
||||||
temporary files will be removed and hyperopt will
|
|
||||||
start from scratch.
|
|
||||||
--hyperopt-loss NAME Specify the class name of the hyperopt loss function
|
--hyperopt-loss NAME Specify the class name of the hyperopt loss function
|
||||||
class (IHyperOptLoss). Different functions can
|
class (IHyperOptLoss). Different functions can
|
||||||
generate completely different results, since the
|
generate completely different results, since the
|
||||||
target for optimization is different. Built-in
|
target for optimization is different. Built-in
|
||||||
Hyperopt-loss-functions are:
|
Hyperopt-loss-functions are:
|
||||||
DefaultHyperOptLoss, OnlyProfitHyperOptLoss,
|
ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss,
|
||||||
SharpeHyperOptLoss, SharpeHyperOptLossDaily,
|
SharpeHyperOptLoss, SharpeHyperOptLossDaily,
|
||||||
SortinoHyperOptLoss, SortinoHyperOptLossDaily.
|
SortinoHyperOptLoss, SortinoHyperOptLossDaily
|
||||||
(default: `DefaultHyperOptLoss`).
|
|
||||||
|
|
||||||
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).
|
||||||
@ -378,13 +406,13 @@ To know your trade expectancy and winrate against historical data, you can use E
|
|||||||
```
|
```
|
||||||
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||||
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
[-i TIMEFRAME] [--timerange TIMERANGE]
|
||||||
[--max-open-trades INT] [--stake-amount STAKE_AMOUNT]
|
[--max-open-trades INT] [--stake-amount STAKE_AMOUNT]
|
||||||
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
|
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
|
||||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
`1d`).
|
`1d`).
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
|
@ -47,7 +47,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `amend_last_stake_amount` | Use reduced last stake amount if necessary. [More information below](#configuring-amount-per-trade). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `amend_last_stake_amount` | Use reduced last stake amount if necessary. [More information below](#configuring-amount-per-trade). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `last_stake_amount_min_ratio` | Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if `amend_last_stake_amount` is set to `true`). [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.5`.* <br> **Datatype:** Float (as ratio)
|
| `last_stake_amount_min_ratio` | Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if `amend_last_stake_amount` is set to `true`). [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.5`.* <br> **Datatype:** Float (as ratio)
|
||||||
| `amount_reserve_percent` | Reserve some amount in min pair stake amount. The bot will reserve `amount_reserve_percent` + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. <br>*Defaults to `0.05` (5%).* <br> **Datatype:** Positive Float as ratio.
|
| `amount_reserve_percent` | Reserve some amount in min pair stake amount. The bot will reserve `amount_reserve_percent` + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. <br>*Defaults to `0.05` (5%).* <br> **Datatype:** Positive Float as ratio.
|
||||||
| `ticker_interval` | The timeframe (ticker interval) to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String
|
| `timeframe` | The timeframe (former ticker interval) to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String
|
||||||
| `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> **Datatype:** String
|
| `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> **Datatype:** String
|
||||||
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||||
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
|
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
|
||||||
@ -55,12 +55,12 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
||||||
| `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). [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). [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). [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
|
||||||
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||||
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||||
| `bid_strategy.price_side` | Select the side of the spread the bot should look at to get the buy rate. [More information below](#buy-price-side).<br> *Defaults to `bid`.* <br> **Datatype:** String (either `ask` or `bid`).
|
| `bid_strategy.price_side` | Select the side of the spread the bot should look at to get the buy rate. [More information below](#buy-price-side).<br> *Defaults to `bid`.* <br> **Datatype:** String (either `ask` or `bid`).
|
||||||
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#buy-price-without-orderbook-enabled).
|
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#buy-price-without-orderbook-enabled).
|
||||||
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
||||||
@ -87,9 +87,11 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `exchange.ccxt_sync_config` | Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
| `exchange.ccxt_sync_config` | Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||||
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||||
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> **Datatype:** Positive Integer
|
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> **Datatype:** Positive Integer
|
||||||
|
| `exchange.skip_pair_validation` | Skip pairlist validation on startup.<br>*Defaults to `false`<br> **Datatype:** Boolean
|
||||||
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||||
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||||
| `pairlists` | Define one or more pairlists to be used. [More information below](#pairlists-and-pairlist-handlers). <br>*Defaults to `StaticPairList`.* <br> **Datatype:** List of Dicts
|
| `pairlists` | Define one or more pairlists to be used. [More information below](#pairlists-and-pairlist-handlers). <br>*Defaults to `StaticPairList`.* <br> **Datatype:** List of Dicts
|
||||||
|
| `protections` | Define one or more protections to be used. [More information below](#protections). <br> **Datatype:** List of Dicts
|
||||||
| `telegram.enabled` | Enable the usage of Telegram. <br> **Datatype:** Boolean
|
| `telegram.enabled` | Enable the usage of Telegram. <br> **Datatype:** Boolean
|
||||||
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||||
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||||
@ -126,7 +128,7 @@ The following parameters can be set in either configuration file or strategy.
|
|||||||
Values set in the configuration file always overwrite values set in the strategy.
|
Values set in the configuration file always overwrite values set in the strategy.
|
||||||
|
|
||||||
* `minimal_roi`
|
* `minimal_roi`
|
||||||
* `ticker_interval`
|
* `timeframe`
|
||||||
* `stoploss`
|
* `stoploss`
|
||||||
* `trailing_stop`
|
* `trailing_stop`
|
||||||
* `trailing_stop_positive`
|
* `trailing_stop_positive`
|
||||||
@ -176,7 +178,7 @@ In the example above this would mean:
|
|||||||
This option only applies with [Static stake amount](#static-stake-amount) - since [Dynamic stake amount](#dynamic-stake-amount) divides the balances evenly.
|
This option only applies with [Static stake amount](#static-stake-amount) - since [Dynamic stake amount](#dynamic-stake-amount) divides the balances evenly.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
The minimum last stake amount can be configured using `amend_last_stake_amount` - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is `stake_amount * 0.5`. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.
|
The minimum last stake amount can be configured using `last_stake_amount_min_ratio` - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is `stake_amount * 0.5`. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.
|
||||||
|
|
||||||
#### Static stake amount
|
#### Static stake amount
|
||||||
|
|
||||||
@ -272,26 +274,19 @@ the static list of pairs) if we should buy.
|
|||||||
|
|
||||||
### Understand order_types
|
### Understand order_types
|
||||||
|
|
||||||
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`, `emergencysell`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
||||||
|
|
||||||
This allows to buy using limit orders, sell using
|
This allows to buy using limit orders, sell using
|
||||||
limit-orders, and create stoplosses using using market orders. It also allows to set the
|
limit-orders, and create stoplosses using market orders. 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.
|
||||||
If `stoploss_on_exchange` and `trailing_stop` are both set, then the bot will use `stoploss_on_exchange_interval` to check and update the stoploss on exchange periodically.
|
|
||||||
`order_types` can be set in the configuration file or in the strategy.
|
|
||||||
`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 (`buy`, `sell`, `stoploss` and
|
||||||
`stoploss_on_exchange`) need to be present, otherwise the bot will fail to start.
|
`stoploss_on_exchange`) need to be present, otherwise the bot will fail to start.
|
||||||
|
|
||||||
`emergencysell` is an optional value, which defaults to `market` and is used when creating stoploss on exchange orders fails.
|
For information on (`emergencysell`,`stoploss_on_exchange`,`stoploss_on_exchange_interval`,`stoploss_on_exchange_limit_ratio`) please see stop loss documentation [stop loss on exchange](stoploss.md)
|
||||||
The below is the default which is used if this is not configured in either strategy or configuration file.
|
|
||||||
|
|
||||||
Since `stoploss_on_exchange` uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price.
|
|
||||||
`stoploss` defines the stop-price - and limit should be slightly below this. This defaults to 0.99 / 1% (configurable via `stoploss_on_exchange_limit_ratio`).
|
|
||||||
Calculation example: we bought the asset at 100$.
|
|
||||||
Stop-price is 95$, then limit would be `95 * 0.99 = 94.05$` - so the stoploss will happen between 95$ and 94.05$.
|
|
||||||
|
|
||||||
Syntax for Strategy:
|
Syntax for Strategy:
|
||||||
|
|
||||||
@ -320,18 +315,20 @@ Configuration:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note "Market order support"
|
||||||
Not all exchanges support "market" orders.
|
Not all exchanges support "market" orders.
|
||||||
The following message will be shown if your exchange does not support market orders:
|
The following message will be shown if your exchange does not support market orders:
|
||||||
`"Exchange <yourexchange> does not support market orders."`
|
`"Exchange <yourexchange> does not support market orders."` and the bot will refuse to start.
|
||||||
|
|
||||||
!!! Note
|
!!! Warning "Using market orders"
|
||||||
Stoploss on exchange interval is not mandatory. Do not change its value if you are
|
Please carefully read the section [Market order pricing](#market-order-pricing) section when using market orders.
|
||||||
|
|
||||||
|
!!! Note "Stoploss on exchange"
|
||||||
|
`stoploss_on_exchange_interval` is not mandatory. Do not change its value if you are
|
||||||
unsure of what you are doing. For more information about how stoploss works please
|
unsure of what you are doing. For more information about how stoploss works please
|
||||||
refer to [the stoploss documentation](stoploss.md).
|
refer to [the stoploss documentation](stoploss.md).
|
||||||
|
|
||||||
!!! Note
|
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 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 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.
|
||||||
@ -379,7 +376,7 @@ Freqtrade is based on [CCXT library](https://github.com/ccxt/ccxt) that supports
|
|||||||
exchange markets and trading APIs. The complete up-to-date list can be found in the
|
exchange markets and trading APIs. The complete up-to-date list can be found in the
|
||||||
[CCXT repo homepage](https://github.com/ccxt/ccxt/tree/master/python).
|
[CCXT repo homepage](https://github.com/ccxt/ccxt/tree/master/python).
|
||||||
However, the bot was tested by the development team with only Bittrex, Binance and Kraken,
|
However, the bot was tested by the development team with only Bittrex, Binance and Kraken,
|
||||||
so the these are the only officially supported exhanges:
|
so the these are the only officially supported exchanges:
|
||||||
|
|
||||||
- [Bittrex](https://bittrex.com/): "bittrex"
|
- [Bittrex](https://bittrex.com/): "bittrex"
|
||||||
- [Binance](https://www.binance.com/): "binance"
|
- [Binance](https://www.binance.com/): "binance"
|
||||||
@ -459,6 +456,9 @@ Prices are always retrieved right before an order is placed, either by querying
|
|||||||
!!! Note
|
!!! Note
|
||||||
Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function `fetch_order_book()`, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's `fetch_ticker()`/`fetch_tickers()` functions. Refer to the ccxt library [documentation](https://github.com/ccxt/ccxt/wiki/Manual#market-data) for more details.
|
Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function `fetch_order_book()`, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's `fetch_ticker()`/`fetch_tickers()` functions. Refer to the ccxt library [documentation](https://github.com/ccxt/ccxt/wiki/Manual#market-data) for more details.
|
||||||
|
|
||||||
|
!!! Warning "Using market orders"
|
||||||
|
Please read the section [Market order pricing](#market-order-pricing) section when using market orders.
|
||||||
|
|
||||||
### Buy price
|
### Buy price
|
||||||
|
|
||||||
#### Check depth of market
|
#### Check depth of market
|
||||||
@ -553,118 +553,30 @@ A fixed slot (mirroring `bid_strategy.order_book_top`) can be defined by setting
|
|||||||
|
|
||||||
When not using orderbook (`ask_strategy.use_order_book=False`), the price at the `ask_strategy.price_side` side (defaults to `"ask"`) from the ticker will be used as the sell price.
|
When not using orderbook (`ask_strategy.use_order_book=False`), the price at the `ask_strategy.price_side` side (defaults to `"ask"`) from the ticker will be used as the sell price.
|
||||||
|
|
||||||
## Pairlists and Pairlist Handlers
|
### Market order pricing
|
||||||
|
|
||||||
Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the `pairlists` section of the configuration settings.
|
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
|
||||||
|
|
||||||
In your configuration, you can use Static Pairlist (defined by the [`StaticPairList`](#static-pair-list) Pairlist Handler) and Dynamic Pairlist (defined by the [`VolumePairList`](#volume-pair-list) Pairlist Handler).
|
``` jsonc
|
||||||
|
"order_types": {
|
||||||
Additionaly, [`PrecisionFilter`](#precisionfilter), [`PriceFilter`](#pricefilter), [`ShuffleFilter`](#shufflefilter) and [`SpreadFilter`](#spreadfilter) act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.
|
"buy": "market",
|
||||||
|
"sell": "market"
|
||||||
If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either `StaticPairList` or `VolumePairList` as the starting Pairlist Handler.
|
// ...
|
||||||
|
},
|
||||||
Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the `pair_blacklist` configuration setting) are also always removed from the resulting pairlist.
|
"bid_strategy": {
|
||||||
|
"price_side": "ask",
|
||||||
### Available Pairlist Handlers
|
// ...
|
||||||
|
},
|
||||||
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
"ask_strategy":{
|
||||||
* [`VolumePairList`](#volume-pair-list)
|
"price_side": "bid",
|
||||||
* [`PrecisionFilter`](#precisionfilter)
|
// ...
|
||||||
* [`PriceFilter`](#pricefilter)
|
},
|
||||||
* [`ShuffleFilter`](#shufflefilter)
|
|
||||||
* [`SpreadFilter`](#spreadfilter)
|
|
||||||
|
|
||||||
!!! Tip "Testing pairlists"
|
|
||||||
Pairlist configurations can be quite tricky to get right. Best use the [`test-pairlist`](utils.md#test-pairlist) utility subcommand to test your configuration quickly.
|
|
||||||
|
|
||||||
#### Static Pair List
|
|
||||||
|
|
||||||
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration.
|
|
||||||
|
|
||||||
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"pairlists": [
|
|
||||||
{"method": "StaticPairList"}
|
|
||||||
],
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Volume Pair List
|
Obviously, if only one side is using limit orders, different pricing combinations can be used.
|
||||||
|
--8<-- "includes/pairlists.md"
|
||||||
`VolumePairList` employs sorting/filtering of pairs by their trading volume. I selects `number_assets` top pairs with sorting based on the `sort_key` (which can only be `quoteVolume`).
|
--8<-- "includes/protections.md"
|
||||||
|
|
||||||
When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), `VolumePairList` considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.
|
|
||||||
|
|
||||||
When used on the leading position of the chain of Pairlist Handlers, it does not consider `pair_whitelist` configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
|
|
||||||
|
|
||||||
The `refresh_period` setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
|
|
||||||
|
|
||||||
`VolumePairList` is based on the ticker data from exchange, as reported by the ccxt library:
|
|
||||||
|
|
||||||
* The `quoteVolume` is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"pairlists": [{
|
|
||||||
"method": "VolumePairList",
|
|
||||||
"number_assets": 20,
|
|
||||||
"sort_key": "quoteVolume",
|
|
||||||
"refresh_period": 1800,
|
|
||||||
],
|
|
||||||
```
|
|
||||||
|
|
||||||
#### PrecisionFilter
|
|
||||||
|
|
||||||
Filters low-value coins which would not allow setting stoplosses.
|
|
||||||
|
|
||||||
#### PriceFilter
|
|
||||||
|
|
||||||
The `PriceFilter` allows filtering of pairs by price.
|
|
||||||
|
|
||||||
Currently, only `low_price_ratio` setting is implemented, where a raise of 1 price unit (pip) is below the `low_price_ratio` ratio.
|
|
||||||
This option is disabled by default, and will only apply if set to <> 0.
|
|
||||||
|
|
||||||
Calculation example:
|
|
||||||
|
|
||||||
Min price precision is 8 decimals. If price is 0.00000011 - one step would be 0.00000012 - which is almost 10% higher than the previous value.
|
|
||||||
|
|
||||||
These pairs are dangerous since it may be impossible to place the desired stoploss - and often result in high losses. Here is what the PriceFilters takes over.
|
|
||||||
|
|
||||||
#### ShuffleFilter
|
|
||||||
|
|
||||||
Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.
|
|
||||||
|
|
||||||
!!! Tip
|
|
||||||
You may set the `seed` value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If `seed` is not set, the pairs are shuffled in the non-repeatable random order.
|
|
||||||
|
|
||||||
#### SpreadFilter
|
|
||||||
|
|
||||||
Removes pairs that have a difference between asks and bids above the specified ratio, `max_spread_ratio` (defaults to `0.005`).
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
If `DOGE/BTC` maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: `1 - bid/ask ~= 0.037` which is `> 0.005` and this pair will be filtered out.
|
|
||||||
|
|
||||||
### Full example of Pairlist Handlers
|
|
||||||
|
|
||||||
The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets, sorting pairs by `quoteVolume` and applies both [`PrecisionFilter`](#precisionfilter) and [`PriceFilter`](#price-filter), filtering all assets where 1 priceunit is > 1%. Then the `SpreadFilter` is applied and pairs are finally shuffled with the random seed set to some predefined value.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"exchange": {
|
|
||||||
"pair_whitelist": [],
|
|
||||||
"pair_blacklist": ["BNB/BTC"]
|
|
||||||
},
|
|
||||||
"pairlists": [
|
|
||||||
{
|
|
||||||
"method": "VolumePairList",
|
|
||||||
"number_assets": 20,
|
|
||||||
"sort_key": "quoteVolume",
|
|
||||||
},
|
|
||||||
{"method": "PrecisionFilter"},
|
|
||||||
{"method": "PriceFilter", "low_price_ratio": 0.01},
|
|
||||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
|
|
||||||
{"method": "ShuffleFilter", "seed": 42}
|
|
||||||
],
|
|
||||||
```
|
|
||||||
|
|
||||||
## Switch to Dry-run mode
|
## Switch to Dry-run mode
|
||||||
|
|
||||||
|
@ -1,12 +1,22 @@
|
|||||||
# Analyzing bot data with Jupyter notebooks
|
# Analyzing bot data with Jupyter notebooks
|
||||||
|
|
||||||
You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at `user_data/notebooks/`.
|
You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at `user_data/notebooks/` after initializing the user directory with `freqtrade create-userdir --userdir user_data`.
|
||||||
|
|
||||||
## Pro tips
|
## Quick start with docker
|
||||||
|
|
||||||
|
Freqtrade provides a docker-compose file which starts up a jupyter lab server.
|
||||||
|
You can run this server using the following command: `docker-compose -f docker/docker-compose-jupyter.yml up`
|
||||||
|
|
||||||
|
This will create a dockercontainer running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`.
|
||||||
|
Please use the link that's printed in the console after startup for simplified login.
|
||||||
|
|
||||||
|
For more information, Please visit the [Data analysis with Docker](docker_quickstart.md#data-analayis-using-docker-compose) section.
|
||||||
|
|
||||||
|
### Pro tips
|
||||||
|
|
||||||
* See [jupyter.org](https://jupyter.org/documentation) for usage instructions.
|
* See [jupyter.org](https://jupyter.org/documentation) for usage instructions.
|
||||||
* Don't forget to start a Jupyter notebook server from within your conda or venv environment or use [nb_conda_kernels](https://github.com/Anaconda-Platform/nb_conda_kernels)*
|
* Don't forget to start a Jupyter notebook server from within your conda or venv environment or use [nb_conda_kernels](https://github.com/Anaconda-Platform/nb_conda_kernels)*
|
||||||
* Copy the example notebook before use so your changes don't get clobbered with the next freqtrade update.
|
* Copy the example notebook before use so your changes don't get overwritten with the next freqtrade update.
|
||||||
|
|
||||||
### Using virtual environment with system-wide Jupyter installation
|
### Using virtual environment with system-wide Jupyter installation
|
||||||
|
|
||||||
@ -28,10 +38,8 @@ ipython kernel install --user --name=freqtrade
|
|||||||
!!! Note
|
!!! Note
|
||||||
This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the [Project Jupyter](https://jupyter.org/) [documentation](https://jupyter.org/documentation) or [help channels](https://jupyter.org/community).
|
This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the [Project Jupyter](https://jupyter.org/) [documentation](https://jupyter.org/documentation) or [help channels](https://jupyter.org/community).
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
## Fine print
|
Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.
|
||||||
|
|
||||||
Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.
|
|
||||||
|
|
||||||
## Recommended workflow
|
## Recommended workflow
|
||||||
|
|
||||||
|
@ -8,82 +8,121 @@ If no additional parameter is specified, freqtrade will download data for `"1m"`
|
|||||||
Exchange and pairs will come from `config.json` (if specified using `-c/--config`).
|
Exchange and pairs will come from `config.json` (if specified using `-c/--config`).
|
||||||
Otherwise `--exchange` becomes mandatory.
|
Otherwise `--exchange` becomes mandatory.
|
||||||
|
|
||||||
|
You can use a relative timerange (`--days 20`) or an absolute starting point (`--timerange 20200101-`). For incremental downloads, the relative approach should be used.
|
||||||
|
|
||||||
!!! Tip "Tip: Updating existing data"
|
!!! Tip "Tip: Updating existing data"
|
||||||
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use `--days xx` with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data.
|
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use `--days xx` with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data.
|
||||||
Be carefull though: If the number is too small (which would result in a few missing days), the whole dataset will be removed and only xx days will be downloaded.
|
Be careful though: If the number is too small (which would result in a few missing days), the whole dataset will be removed and only xx days will be downloaded.
|
||||||
|
|
||||||
### Usage
|
### Usage
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]
|
usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[--pairs-file FILE] [--days INT] [--dl-trades] [--exchange EXCHANGE]
|
[-d PATH] [--userdir PATH]
|
||||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]]
|
[-p PAIRS [PAIRS ...]] [--pairs-file FILE]
|
||||||
[--erase] [--data-format-ohlcv {json,jsongz}] [--data-format-trades {json,jsongz}]
|
[--days INT] [--timerange TIMERANGE]
|
||||||
|
[--dl-trades] [--exchange EXCHANGE]
|
||||||
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} ...]]
|
||||||
-h, --help show this help message and exit
|
[--erase]
|
||||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
Show profits for only these pairs. Pairs are space-separated.
|
[--data-format-trades {json,jsongz,hdf5}]
|
||||||
--pairs-file FILE File containing a list of pairs to download.
|
|
||||||
--days INT Download data for given number of days.
|
|
||||||
--dl-trades Download trades instead of OHLCV data. The bot will resample trades to the desired timeframe as specified as
|
|
||||||
--timeframes/-t.
|
|
||||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no config is provided.
|
|
||||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]
|
|
||||||
Specify which tickers to download. Space-separated list. Default: `1m 5m`.
|
|
||||||
--erase Clean all existing data for the selected exchange/pairs/timeframes.
|
|
||||||
--data-format-ohlcv {json,jsongz}
|
|
||||||
Storage format for downloaded candle (OHLCV) data. (default: `json`).
|
|
||||||
--data-format-trades {json,jsongz}
|
|
||||||
Storage format for downloaded trades data. (default: `jsongz`).
|
|
||||||
|
|
||||||
Common arguments:
|
|
||||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
|
||||||
--logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details.
|
|
||||||
-V, --version show program's version number and exit
|
|
||||||
-c PATH, --config PATH
|
|
||||||
Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`
|
|
||||||
to read config from stdin.
|
|
||||||
-d PATH, --datadir PATH
|
|
||||||
Path to directory with historical backtesting data.
|
|
||||||
--userdir PATH, --user-data-dir PATH
|
|
||||||
Path to userdata directory.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Data format
|
|
||||||
|
|
||||||
Freqtrade currently supports 2 dataformats, `json` (plain "text" json files) and `jsongz` (a gzipped version of json files).
|
|
||||||
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
|
||||||
|
|
||||||
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` parameters respectivly.
|
|
||||||
|
|
||||||
If the default dataformat has been changed during download, then the keys `dataformat_ohlcv` and `dataformat_trades` in the configuration file need to be adjusted to the selected dataformat as well.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
You can convert between data-formats using the [convert-data](#subcommand-convert-data) and [convert-trade-data](#subcommand-convert-trade-data) methods.
|
|
||||||
|
|
||||||
#### Subcommand convert data
|
|
||||||
|
|
||||||
```
|
|
||||||
usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|
||||||
[-d PATH] [--userdir PATH]
|
|
||||||
[-p PAIRS [PAIRS ...]] --format-from
|
|
||||||
{json,jsongz} --format-to {json,jsongz}
|
|
||||||
[--erase]
|
|
||||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]]
|
|
||||||
|
|
||||||
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-
|
Show profits for only these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--format-from {json,jsongz}
|
--pairs-file FILE File containing a list of pairs to download.
|
||||||
|
--days INT Download data for given number of days.
|
||||||
|
--timerange TIMERANGE
|
||||||
|
Specify what timerange of data to use.
|
||||||
|
--dl-trades Download trades instead of OHLCV data. The bot will
|
||||||
|
resample trades to the desired timeframe as specified
|
||||||
|
as --timeframes/-t.
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
-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
|
||||||
|
list. Default: `1m 5m`.
|
||||||
|
--erase Clean all existing data for the selected
|
||||||
|
exchange/pairs/timeframes.
|
||||||
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
|
(default: `json`).
|
||||||
|
--data-format-trades {json,jsongz,hdf5}
|
||||||
|
Storage format for downloaded trades data. (default:
|
||||||
|
`jsongz`).
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified. Special values are:
|
||||||
|
'syslog', 'journald'. See the documentation for more
|
||||||
|
details.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default:
|
||||||
|
`userdir/config.json` or `config.json` whichever
|
||||||
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note "Startup period"
|
||||||
|
`download-data` is a strategy-independent command. The idea is to download a big chunk of data once, and then iteratively increase the amount of data stored.
|
||||||
|
|
||||||
|
For that reason, `download-data` does not care about the "startup-period" defined in a strategy. It's up to the user to download additional days if the backtest should start at a specific point in time (while respecting startup period).
|
||||||
|
|
||||||
|
### Data format
|
||||||
|
|
||||||
|
Freqtrade currently supports 3 data-formats for both OHLCV and trades data:
|
||||||
|
|
||||||
|
* `json` (plain "text" json files)
|
||||||
|
* `jsongz` (a gzip-zipped version of json files)
|
||||||
|
* `hdf5` (a high performance datastore)
|
||||||
|
|
||||||
|
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
||||||
|
|
||||||
|
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
|
||||||
|
To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
||||||
|
|
||||||
|
``` jsonc
|
||||||
|
// ...
|
||||||
|
"dataformat_ohlcv": "hdf5",
|
||||||
|
"dataformat_trades": "hdf5",
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
If the default data-format has been changed during download, then the keys `dataformat_ohlcv` and `dataformat_trades` in the configuration file need to be adjusted to the selected dataformat as well.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
You can convert between data-formats using the [convert-data](#sub-command-convert-data) and [convert-trade-data](#sub-command-convert-trade-data) methods.
|
||||||
|
|
||||||
|
#### Sub-command convert data
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH]
|
||||||
|
[-p PAIRS [PAIRS ...]] --format-from
|
||||||
|
{json,jsongz,hdf5} --format-to
|
||||||
|
{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} ...]]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
|
Show profits for only these pairs. Pairs are space-
|
||||||
|
separated.
|
||||||
|
--format-from {json,jsongz,hdf5}
|
||||||
Source format for data conversion.
|
Source format for data conversion.
|
||||||
--format-to {json,jsongz}
|
--format-to {json,jsongz,hdf5}
|
||||||
Destination format for data conversion.
|
Destination format for data conversion.
|
||||||
--erase Clean all existing data for the selected
|
--erase Clean all existing data for the selected
|
||||||
exchange/pairs/timeframes.
|
exchange/pairs/timeframes.
|
||||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]
|
-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`.
|
||||||
|
|
||||||
@ -94,9 +133,10 @@ Common arguments:
|
|||||||
details.
|
details.
|
||||||
-V, --version show program's version number and exit
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: `config.json`).
|
Specify configuration file (default:
|
||||||
Multiple --config options may be used. Can be set to
|
`userdir/config.json` or `config.json` whichever
|
||||||
`-` to read config from stdin.
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
@ -109,26 +149,26 @@ The following command will convert all candle (OHLCV) data available in `~/.freq
|
|||||||
It'll also remove original json data files (`--erase` parameter).
|
It'll also remove original json data files (`--erase` parameter).
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade convert-data --format-from json --format-to jsongz --data-dir ~/.freqtrade/data/binance -t 5m 15m --erase
|
freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtrade/data/binance -t 5m 15m --erase
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Subcommand convert-trade data
|
#### Sub-command convert trade data
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH]
|
[-d PATH] [--userdir PATH]
|
||||||
[-p PAIRS [PAIRS ...]] --format-from
|
[-p PAIRS [PAIRS ...]] --format-from
|
||||||
{json,jsongz} --format-to {json,jsongz}
|
{json,jsongz,hdf5} --format-to
|
||||||
[--erase]
|
{json,jsongz,hdf5} [--erase]
|
||||||
|
|
||||||
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-
|
Show profits for only these pairs. Pairs are space-
|
||||||
separated.
|
separated.
|
||||||
--format-from {json,jsongz}
|
--format-from {json,jsongz,hdf5}
|
||||||
Source format for data conversion.
|
Source format for data conversion.
|
||||||
--format-to {json,jsongz}
|
--format-to {json,jsongz,hdf5}
|
||||||
Destination format for data conversion.
|
Destination format for data conversion.
|
||||||
--erase Clean all existing data for the selected
|
--erase Clean all existing data for the selected
|
||||||
exchange/pairs/timeframes.
|
exchange/pairs/timeframes.
|
||||||
@ -140,13 +180,15 @@ Common arguments:
|
|||||||
details.
|
details.
|
||||||
-V, --version show program's version number and exit
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: `config.json`).
|
Specify configuration file (default:
|
||||||
Multiple --config options may be used. Can be set to
|
`userdir/config.json` or `config.json` whichever
|
||||||
`-` to read config from stdin.
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
##### Example converting trades
|
##### Example converting trades
|
||||||
@ -155,7 +197,60 @@ The following command will convert all available trade-data in `~/.freqtrade/dat
|
|||||||
It'll also remove original jsongz data files (`--erase` parameter).
|
It'll also remove original jsongz data files (`--erase` parameter).
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade convert-trade-data --format-from jsongz --format-to json --data-dir ~/.freqtrade/data/kraken --erase
|
freqtrade convert-trade-data --format-from jsongz --format-to json --datadir ~/.freqtrade/data/kraken --erase
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sub-command list-data
|
||||||
|
|
||||||
|
You can get a list of downloaded data using the `list-data` sub-command.
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||||
|
[--userdir PATH] [--exchange EXCHANGE]
|
||||||
|
[--data-format-ohlcv {json,jsongz,hdf5}]
|
||||||
|
[-p PAIRS [PAIRS ...]]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||||
|
config is provided.
|
||||||
|
--data-format-ohlcv {json,jsongz,hdf5}
|
||||||
|
Storage format for downloaded candle (OHLCV) data.
|
||||||
|
(default: `json`).
|
||||||
|
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||||
|
Show profits for only these pairs. Pairs are space-
|
||||||
|
separated.
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified. Special values are:
|
||||||
|
'syslog', 'journald'. See the documentation for more
|
||||||
|
details.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default:
|
||||||
|
`userdir/config.json` or `config.json` whichever
|
||||||
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Example list-data
|
||||||
|
|
||||||
|
```bash
|
||||||
|
> freqtrade list-data --userdir ~/.freqtrade/user_data/
|
||||||
|
|
||||||
|
Found 33 pair / timeframe combinations.
|
||||||
|
pairs timeframe
|
||||||
|
---------- -----------------------------------------
|
||||||
|
ADA/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d
|
||||||
|
ADA/ETH 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d
|
||||||
|
ETH/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d
|
||||||
|
ETH/USDT 5m, 15m, 30m, 1h, 2h, 4h
|
||||||
```
|
```
|
||||||
|
|
||||||
### Pairs file
|
### Pairs file
|
||||||
@ -197,15 +292,16 @@ This will download historical candle (OHLCV) data for all the currency pairs you
|
|||||||
### Other Notes
|
### Other Notes
|
||||||
|
|
||||||
- To use a different directory than the exchange specific default, use `--datadir user_data/data/some_directory`.
|
- To use a different directory than the exchange specific default, use `--datadir user_data/data/some_directory`.
|
||||||
- To change the exchange used to download the historical data from, please use a different configuration file (you'll probably need to adjust ratelimits etc.)
|
- To change the exchange used to download the historical data from, please use a different configuration file (you'll probably need to adjust rate limits etc.)
|
||||||
- To use `pairs.json` from some other directory, use `--pairs-file some_other_dir/pairs.json`.
|
- To use `pairs.json` from some other directory, use `--pairs-file some_other_dir/pairs.json`.
|
||||||
- To download historical candle (OHLCV) data for only 10 days, use `--days 10` (defaults to 30 days).
|
- To download historical candle (OHLCV) data for only 10 days, use `--days 10` (defaults to 30 days).
|
||||||
|
- To download historical candle (OHLCV) data from a fixed starting point, use `--timerange 20200101-` - which will download all data from January 1st, 2020. Eventually set end dates are ignored.
|
||||||
- Use `--timeframes` to specify what timeframe download the historical candle (OHLCV) data for. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute data.
|
- Use `--timeframes` to specify what timeframe download the historical candle (OHLCV) data for. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute data.
|
||||||
- To use exchange, timeframe and list of pairs as defined in your configuration file, use the `-c/--config` option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine `-c/--config` with most other options.
|
- To use exchange, timeframe and list of pairs as defined in your configuration file, use the `-c/--config` option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine `-c/--config` with most other options.
|
||||||
|
|
||||||
### Trades (tick) data
|
### Trades (tick) data
|
||||||
|
|
||||||
By default, `download-data` subcommand downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API.
|
By default, `download-data` sub-command downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API.
|
||||||
This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes.
|
This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes.
|
||||||
|
|
||||||
Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of `<pair>-trades.json.gz` (`ETH_BTC-trades.json.gz`). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with `--days 8` will create an incremental data-repository.
|
Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of `<pair>-trades.json.gz` (`ETH_BTC-trades.json.gz`). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with `--days 8` will create an incremental data-repository.
|
||||||
|
@ -9,21 +9,20 @@ and are no longer supported. Please avoid their usage in your configuration.
|
|||||||
### the `--refresh-pairs-cached` command line option
|
### the `--refresh-pairs-cached` command line option
|
||||||
|
|
||||||
`--refresh-pairs-cached` in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting.
|
`--refresh-pairs-cached` in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting.
|
||||||
Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out
|
Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out as a separate freqtrade sub-command `freqtrade download-data`.
|
||||||
as a seperate freqtrade subcommand `freqtrade download-data`.
|
|
||||||
|
|
||||||
This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9 (master branch).
|
This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9.
|
||||||
|
|
||||||
### The **--dynamic-whitelist** command line option
|
### The **--dynamic-whitelist** command line option
|
||||||
|
|
||||||
This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch)
|
This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch)
|
||||||
and in freqtrade 2019.7 (master branch).
|
and in freqtrade 2019.7.
|
||||||
|
|
||||||
### the `--live` command line option
|
### the `--live` command line option
|
||||||
|
|
||||||
`--live` in the context of backtesting allowed to download the latest tick data for backtesting.
|
`--live` in the context of backtesting allowed to download the latest tick data for backtesting.
|
||||||
Did only download the latest 500 candles, so was ineffective in getting good backtest data.
|
Did only download the latest 500 candles, so was ineffective in getting good backtest data.
|
||||||
Removed in 2019-7-dev (develop branch) and in freqtrade 2019-8 (master branch)
|
Removed in 2019-7-dev (develop branch) and in freqtrade 2019.8.
|
||||||
|
|
||||||
### Allow running multiple pairlists in sequence
|
### Allow running multiple pairlists in sequence
|
||||||
|
|
||||||
@ -31,6 +30,6 @@ The former `"pairlist"` section in the configuration has been removed, and is re
|
|||||||
|
|
||||||
The old section of configuration parameters (`"pairlist"`) has been deprecated in 2019.11 and has been removed in 2020.4.
|
The old section of configuration parameters (`"pairlist"`) has been deprecated in 2019.11 and has been removed in 2020.4.
|
||||||
|
|
||||||
### deprecation of bidVolume and askVolume from volumepairlist
|
### deprecation of bidVolume and askVolume from volume-pairlist
|
||||||
|
|
||||||
Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4.
|
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.
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
||||||
|
|
||||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel in [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) where you can ask questions.
|
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel on [discord](https://discord.gg/MA9v74M) or [slack](https://join.slack.com/t/highfrequencybot/shared_invite/zt-jaut7r4m-Y17k4x5mcQES9a9swKuxbg) where you can ask questions.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
@ -10,13 +10,35 @@ Documentation is available at [https://freqtrade.io](https://www.freqtrade.io/)
|
|||||||
|
|
||||||
Special fields for the documentation (like Note boxes, ...) can be found [here](https://squidfunk.github.io/mkdocs-material/extensions/admonition/).
|
Special fields for the documentation (like Note boxes, ...) can be found [here](https://squidfunk.github.io/mkdocs-material/extensions/admonition/).
|
||||||
|
|
||||||
|
To test the documentation locally use the following commands.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
pip install -r docs/requirements-docs.txt
|
||||||
|
mkdocs serve
|
||||||
|
```
|
||||||
|
|
||||||
|
This will spin up a local server (usually on port 8000) so you can see if everything looks as you'd like it to.
|
||||||
|
|
||||||
## Developer setup
|
## Developer setup
|
||||||
|
|
||||||
To configure a development environment, best use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
|
To configure a development environment, you can either use the provided [DevContainer](#devcontainer-setup), or use the `setup.sh` script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ".
|
||||||
Alternatively (if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -e .[all]`.
|
Alternatively (e.g. if your system is not supported by the setup.sh script), follow the manual installation process and run `pip3 install -e .[all]`.
|
||||||
|
|
||||||
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`.
|
||||||
|
|
||||||
|
### Devcontainer setup
|
||||||
|
|
||||||
|
The fastest and easiest way to get started is to use [VSCode](https://code.visualstudio.com/) with the Remote container extension.
|
||||||
|
This gives developers the ability to start the bot with all required dependencies *without* needing to install any freqtrade specific dependencies on your local machine.
|
||||||
|
|
||||||
|
#### Devcontainer dependencies
|
||||||
|
|
||||||
|
* [VSCode](https://code.visualstudio.com/)
|
||||||
|
* [docker](https://docs.docker.com/install/)
|
||||||
|
* [Remote container extension documentation](https://code.visualstudio.com/docs/remote)
|
||||||
|
|
||||||
|
For more information about the [Remote container extension](https://code.visualstudio.com/docs/remote), best consult the documentation.
|
||||||
|
|
||||||
### Tests
|
### Tests
|
||||||
|
|
||||||
New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests.
|
New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests.
|
||||||
@ -41,53 +63,42 @@ def test_method_to_test(caplog):
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Local docker usage
|
## ErrorHandling
|
||||||
|
|
||||||
The fastest and easiest way to start up is to use docker-compose.develop which gives developers the ability to start the bot up with all the required dependencies, *without* needing to install any freqtrade specific dependencies on your local machine.
|
Freqtrade Exceptions all inherit from `FreqtradeException`.
|
||||||
|
This general class of error should however not be used directly. Instead, multiple specialized sub-Exceptions exist.
|
||||||
|
|
||||||
#### Install
|
Below is an outline of exception inheritance hierarchy:
|
||||||
|
|
||||||
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
```
|
||||||
* [docker](https://docs.docker.com/install/)
|
+ FreqtradeException
|
||||||
* [docker-compose](https://docs.docker.com/compose/install/)
|
|
|
||||||
|
+---+ OperationalException
|
||||||
#### Starting the bot
|
|
|
||||||
##### Use the develop dockerfile
|
+---+ DependencyException
|
||||||
|
| |
|
||||||
``` bash
|
| +---+ PricingError
|
||||||
rm docker-compose.yml && mv docker-compose.develop.yml docker-compose.yml
|
| |
|
||||||
|
| +---+ ExchangeError
|
||||||
|
| |
|
||||||
|
| +---+ TemporaryError
|
||||||
|
| |
|
||||||
|
| +---+ DDosProtection
|
||||||
|
| |
|
||||||
|
| +---+ InvalidOrderException
|
||||||
|
| |
|
||||||
|
| +---+ RetryableOrderError
|
||||||
|
| |
|
||||||
|
| +---+ InsufficientFundsError
|
||||||
|
|
|
||||||
|
+---+ StrategyError
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Docker Compose
|
---
|
||||||
|
|
||||||
##### Starting
|
## Plugins
|
||||||
|
|
||||||
``` bash
|
### Pairlists
|
||||||
docker-compose up
|
|
||||||
```
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
##### Rebuilding
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
docker-compose build
|
|
||||||
```
|
|
||||||
|
|
||||||
##### Execing (effectively SSH into the container)
|
|
||||||
|
|
||||||
The `exec` command requires that the container already be running, if you want to start it
|
|
||||||
that can be effected by `docker-compose up` or `docker-compose run freqtrade_develop`
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
docker-compose exec freqtrade_develop /bin/bash
|
|
||||||
```
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Modules
|
|
||||||
|
|
||||||
### Dynamic Pairlist
|
|
||||||
|
|
||||||
You have a great idea for a new pair selection algorithm you would like to try out? Great.
|
You have a great idea for a new pair selection algorithm you would like to try out? Great.
|
||||||
Hopefully you also want to contribute this back upstream.
|
Hopefully you also want to contribute this back upstream.
|
||||||
@ -98,7 +109,7 @@ First of all, have a look at the [VolumePairList](https://github.com/freqtrade/f
|
|||||||
|
|
||||||
This is a simple Handler, which however serves as a good example on how to start developing.
|
This is a simple Handler, which however serves as a good example on how to start developing.
|
||||||
|
|
||||||
Next, modify the classname of the Handler (ideally align this with the module filename).
|
Next, modify the class-name of the Handler (ideally align this with the module filename).
|
||||||
|
|
||||||
The base-class provides an instance of the exchange (`self._exchange`) the pairlist manager (`self._pairlistmanager`), as well as the main configuration (`self._config`), the pairlist dedicated configuration (`self._pairlistconfig`) and the absolute position within the list of pairlists.
|
The base-class provides an instance of the exchange (`self._exchange`) the pairlist manager (`self._pairlistmanager`), as well as the main configuration (`self._config`), the pairlist dedicated configuration (`self._pairlistconfig`) and the absolute position within the list of pairlists.
|
||||||
|
|
||||||
@ -110,6 +121,9 @@ The base-class provides an instance of the exchange (`self._exchange`) the pairl
|
|||||||
self._pairlist_pos = pairlist_pos
|
self._pairlist_pos = pairlist_pos
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
Don't forget to register your pairlist in `constants.py` under the variable `AVAILABLE_PAIRLISTS` - otherwise it will not be selectable.
|
||||||
|
|
||||||
Now, let's step through the methods which require actions:
|
Now, let's step through the methods which require actions:
|
||||||
|
|
||||||
#### Pairlist configuration
|
#### Pairlist configuration
|
||||||
@ -118,7 +132,7 @@ Configuration for the chain of Pairlist Handlers is done in the bot configuratio
|
|||||||
|
|
||||||
By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience.
|
By convention, `"number_assets"` is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience.
|
||||||
|
|
||||||
Additional parameters can be configured as needed. For instance, `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successfull and dynamic.
|
Additional parameters can be configured as needed. For instance, `VolumePairList` uses `"sort_key"` to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successful and dynamic.
|
||||||
|
|
||||||
#### short_desc
|
#### short_desc
|
||||||
|
|
||||||
@ -134,7 +148,7 @@ This is called with each iteration of the bot (only if the Pairlist Handler is a
|
|||||||
|
|
||||||
It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers).
|
It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers).
|
||||||
|
|
||||||
Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filtering. Use this if you limit your result to a certain number of pairs - so the endresult is not shorter than expected.
|
Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filtering. Use this if you limit your result to a certain number of pairs - so the end-result is not shorter than expected.
|
||||||
|
|
||||||
#### filter_pairlist
|
#### filter_pairlist
|
||||||
|
|
||||||
@ -142,13 +156,13 @@ This method is called for each Pairlist Handler in the chain by the pairlist man
|
|||||||
|
|
||||||
This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
|
This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
|
||||||
|
|
||||||
It get's passed a pairlist (which can be the result of previous pairlists) as well as `tickers`, a pre-fetched version of `get_tickers()`.
|
It gets passed a pairlist (which can be the result of previous pairlists) as well as `tickers`, a pre-fetched version of `get_tickers()`.
|
||||||
|
|
||||||
The default implementation in the base class simply calls the `_validate_pair()` method for each pair in the pairlist, but you may override it. So you should either implement the `_validate_pair()` in your Pairlist Handler or override `filter_pairlist()` to do something else.
|
The default implementation in the base class simply calls the `_validate_pair()` method for each pair in the pairlist, but you may override it. So you should either implement the `_validate_pair()` in your Pairlist Handler or override `filter_pairlist()` to do something else.
|
||||||
|
|
||||||
If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain).
|
If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain).
|
||||||
|
|
||||||
Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filters. Use this if you limit your result to a certain number of pairs - so the endresult is not shorter than expected.
|
Validations are optional, the parent class exposes a `_verify_blacklist(pairlist)` and `_whitelist_for_active_markets(pairlist)` to do default filters. Use this if you limit your result to a certain number of pairs - so the end result is not shorter than expected.
|
||||||
|
|
||||||
In `VolumePairList`, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.
|
In `VolumePairList`, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.
|
||||||
|
|
||||||
@ -161,6 +175,66 @@ In `VolumePairList`, this implements different methods of sorting, does early va
|
|||||||
return pairs
|
return pairs
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Protections
|
||||||
|
|
||||||
|
Best read the [Protection documentation](configuration.md#protections) to understand protections.
|
||||||
|
This Guide is directed towards Developers who want to develop a new protection.
|
||||||
|
|
||||||
|
No protection should use datetime directly, but use the provided `date_now` variable for date calculations. This preserves the ability to backtest protections.
|
||||||
|
|
||||||
|
!!! Tip "Writing a new Protection"
|
||||||
|
Best copy one of the existing Protections to have a good example.
|
||||||
|
Don't forget to register your protection in `constants.py` under the variable `AVAILABLE_PROTECTIONS` - otherwise it will not be selectable.
|
||||||
|
|
||||||
|
#### Implementation of a new protection
|
||||||
|
|
||||||
|
All Protection implementations must have `IProtection` as parent class.
|
||||||
|
For that reason, they must implement the following methods:
|
||||||
|
|
||||||
|
* `short_desc()`
|
||||||
|
* `global_stop()`
|
||||||
|
* `stop_per_pair()`.
|
||||||
|
|
||||||
|
`global_stop()` and `stop_per_pair()` must return a ProtectionReturn tuple, which consists of:
|
||||||
|
|
||||||
|
* lock pair - boolean
|
||||||
|
* lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle)
|
||||||
|
* reason - string, used for logging and storage in the database
|
||||||
|
|
||||||
|
The `until` portion should be calculated using the provided `calculate_lock_end()` method.
|
||||||
|
|
||||||
|
All Protections should use `"stop_duration"` / `"stop_duration_candles"` to define how long a a pair (or all pairs) should be locked.
|
||||||
|
The content of this is made available as `self._stop_duration` to the each Protection.
|
||||||
|
|
||||||
|
If your protection requires a look-back period, please use `"lookback_period"` / `"lockback_period_candles"` to keep all protections aligned.
|
||||||
|
|
||||||
|
#### Global vs. local stops
|
||||||
|
|
||||||
|
Protections can have 2 different ways to stop trading for a limited :
|
||||||
|
|
||||||
|
* Per pair (local)
|
||||||
|
* For all Pairs (globally)
|
||||||
|
|
||||||
|
##### Protections - per pair
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
##### 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).
|
||||||
|
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).
|
||||||
|
|
||||||
|
##### Protections - calculating lock end time
|
||||||
|
|
||||||
|
Protections should calculate the lock end time based on the last trade it considers.
|
||||||
|
This avoids re-locking should the lookback-period be longer than the actual lock period.
|
||||||
|
|
||||||
|
The `IProtection` parent class provides a helper method for this in `calculate_lock_end()`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Implement a new Exchange (WIP)
|
## Implement a new Exchange (WIP)
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
@ -172,7 +246,7 @@ Most exchanges supported by CCXT should work out of the box.
|
|||||||
|
|
||||||
Check if the new exchange supports Stoploss on Exchange orders through their API.
|
Check if the new exchange supports Stoploss on Exchange orders through their API.
|
||||||
|
|
||||||
Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselfs. Best look at `binance.py` for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. [CCXT Issues](https://github.com/ccxt/ccxt/issues) may also provide great help, since others may have implemented something similar for their projects.
|
Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselves. Best look at `binance.py` for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. [CCXT Issues](https://github.com/ccxt/ccxt/issues) may also provide great help, since others may have implemented something similar for their projects.
|
||||||
|
|
||||||
### Incomplete candles
|
### Incomplete candles
|
||||||
|
|
||||||
@ -222,13 +296,14 @@ jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade
|
|||||||
This documents some decisions taken for the CI Pipeline.
|
This documents some decisions taken for the CI Pipeline.
|
||||||
|
|
||||||
* CI runs on all OS variants, Linux (ubuntu), macOS and Windows.
|
* CI runs on all OS variants, Linux (ubuntu), macOS and Windows.
|
||||||
* Docker images are build for the branches `master` and `develop`.
|
* Docker images are build for the branches `stable` and `develop`.
|
||||||
* Raspberry PI Docker images are postfixed with `_pi` - so tags will be `:master_pi` and `develop_pi`.
|
* Docker images containing Plot dependencies are also available as `stable_plot` and `develop_plot`.
|
||||||
|
* Raspberry PI Docker images are postfixed with `_pi` - so tags will be `:stable_pi` and `develop_pi`.
|
||||||
* Docker images contain a file, `/freqtrade/freqtrade_commit` containing the commit this image is based of.
|
* Docker images contain a file, `/freqtrade/freqtrade_commit` containing the commit this image is based of.
|
||||||
* Full docker image rebuilds are run once a week via schedule.
|
* Full docker image rebuilds are run once a week via schedule.
|
||||||
* Deployments run on ubuntu.
|
* Deployments run on ubuntu.
|
||||||
* ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.
|
* ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.
|
||||||
* All tests must pass for a PR to be merged to `master` or `develop`.
|
* All tests must pass for a PR to be merged to `stable` or `develop`.
|
||||||
|
|
||||||
## Creating a release
|
## Creating a release
|
||||||
|
|
||||||
@ -245,21 +320,22 @@ git checkout -b new_release <commitid>
|
|||||||
|
|
||||||
Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.
|
Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.
|
||||||
|
|
||||||
|
* Merge the release branch (stable) into this branch.
|
||||||
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
|
||||||
* Commit this part
|
* Commit this part
|
||||||
* push that branch to the remote and create a PR against the master branch
|
* push that branch to the remote and create a PR against the stable branch
|
||||||
|
|
||||||
### Create changelog from git commits
|
### Create changelog from git commits
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Make sure that the master branch is uptodate!
|
Make sure that the `stable` branch is up-to-date!
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
# Needs to be done before merging / pulling that branch.
|
# Needs to be done before merging / pulling that branch.
|
||||||
git log --oneline --no-decorate --no-merges master..new_release
|
git log --oneline --no-decorate --no-merges stable..new_release
|
||||||
```
|
```
|
||||||
|
|
||||||
To keep the release-log short, best wrap the full git changelog into a collapsible details secction.
|
To keep the release-log short, best wrap the full git changelog into a collapsible details section.
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
<details>
|
<details>
|
||||||
@ -272,17 +348,20 @@ To keep the release-log short, best wrap the full git changelog into a collapsib
|
|||||||
|
|
||||||
### Create github release / tag
|
### Create github release / tag
|
||||||
|
|
||||||
Once the PR against master is merged (best right after merging):
|
Once the PR against stable is merged (best right after merging):
|
||||||
|
|
||||||
* Use the button "Draft a new release" in the Github UI (subsection releases).
|
* Use the button "Draft a new release" in the Github UI (subsection releases).
|
||||||
* Use the version-number specified as tag.
|
* Use the version-number specified as tag.
|
||||||
* Use "master" as reference (this step comes after the above PR is merged).
|
* Use "stable" as reference (this step comes after the above PR is merged).
|
||||||
* Use the above changelog as release comment (as codeblock)
|
* Use the above changelog as release comment (as codeblock)
|
||||||
|
|
||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
### pypi
|
### pypi
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This process is now automated as part of Github Actions.
|
||||||
|
|
||||||
To create a pypi release, please run the following commands:
|
To create a pypi release, please run the following commands:
|
||||||
|
|
||||||
Additional requirement: `wheel`, `twine` (for uploading), account on pypi with proper permissions.
|
Additional requirement: `wheel`, `twine` (for uploading), account on pypi with proper permissions.
|
||||||
|
216
docs/docker.md
216
docs/docker.md
@ -1,145 +1,7 @@
|
|||||||
# Using Freqtrade with Docker
|
|
||||||
|
|
||||||
## Install Docker
|
|
||||||
|
|
||||||
Start by downloading and installing Docker CE for your platform:
|
|
||||||
|
|
||||||
* [Mac](https://docs.docker.com/docker-for-mac/install/)
|
|
||||||
* [Windows](https://docs.docker.com/docker-for-windows/install/)
|
|
||||||
* [Linux](https://docs.docker.com/install/)
|
|
||||||
|
|
||||||
Optionally, [docker-compose](https://docs.docker.com/compose/install/) should be installed and available to follow the [docker quick start guide](#docker-quick-start).
|
|
||||||
|
|
||||||
Once you have Docker installed, simply prepare the config file (e.g. `config.json`) and run the image for `freqtrade` as explained below.
|
|
||||||
|
|
||||||
## Freqtrade with docker-compose
|
|
||||||
|
|
||||||
Freqtrade provides an official Docker image on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/), as well as a [docker-compose file](https://github.com/freqtrade/freqtrade/blob/develop/docker-compose.yml) ready for usage.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
The following section assumes that docker and docker-compose is installed and available to the logged in user.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
All below comands use relative directories and will have to be executed from the directory containing the `docker-compose.yml` file.
|
|
||||||
|
|
||||||
!!! Note "Docker on Raspberry"
|
|
||||||
If you're running freqtrade on a Raspberry PI, you must change the image from `freqtradeorg/freqtrade:master` to `freqtradeorg/freqtrade:master_pi` or `freqtradeorg/freqtrade:develop_pi`, otherwise the image will not work.
|
|
||||||
|
|
||||||
### Docker quick start
|
|
||||||
|
|
||||||
Create a new directory and place the [docker-compose file](https://github.com/freqtrade/freqtrade/blob/develop/docker-compose.yml) in this directory.
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
mkdir ft_userdata
|
|
||||||
cd ft_userdata/
|
|
||||||
# Download the docker-compose file from the repository
|
|
||||||
curl https://raw.githubusercontent.com/freqtrade/freqtrade/develop/docker-compose.yml -o docker-compose.yml
|
|
||||||
|
|
||||||
# Pull the freqtrade image
|
|
||||||
docker-compose pull
|
|
||||||
|
|
||||||
# Create user directory structure
|
|
||||||
docker-compose run --rm freqtrade create-userdir --userdir user_data
|
|
||||||
|
|
||||||
# Create configuration - Requires answering interactive questions
|
|
||||||
docker-compose run --rm freqtrade new-config --config user_data/config.json
|
|
||||||
```
|
|
||||||
|
|
||||||
The above snippet creates a new directory called "ft_userdata", downloads the latest compose file and pulls the freqtrade image.
|
|
||||||
The last 2 steps in the snippet create the directory with user-data, as well as (interactively) the default configuration based on your selections.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
You can edit the configuration at any time, which is available as `user_data/config.json` (within the directory `ft_userdata`) when using the above configuration.
|
|
||||||
|
|
||||||
#### Adding your strategy
|
|
||||||
|
|
||||||
The configuration is now available as `user_data/config.json`.
|
|
||||||
You should now copy your strategy to `user_data/strategies/` - and add the Strategy class name to the `docker-compose.yml` file, replacing `SampleStrategy`. If you wish to run the bot with the SampleStrategy, just leave it as it is.
|
|
||||||
|
|
||||||
!!! Warning
|
|
||||||
The `SampleStrategy` is there for your reference and give you ideas for your own strategy.
|
|
||||||
Please always backtest the strategy and use dry-run for some time before risking real money!
|
|
||||||
|
|
||||||
Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above).
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Docker-compose logs
|
|
||||||
|
|
||||||
Logs will be written to `user_data/logs/freqtrade.log`.
|
|
||||||
Alternatively, you can check the latest logs using `docker-compose logs -f`.
|
|
||||||
|
|
||||||
#### Database
|
|
||||||
|
|
||||||
The database will be in the user_data directory as well, and will be called `user_data/tradesv3.sqlite`.
|
|
||||||
|
|
||||||
#### Updating freqtrade with docker-compose
|
|
||||||
|
|
||||||
To update freqtrade when using docker-compose is as simple as running the following 2 commands:
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
# Download the latest image
|
|
||||||
docker-compose pull
|
|
||||||
# Restart the image
|
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
This will first pull the latest image, and will then restart the container with the just pulled version.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.
|
|
||||||
|
|
||||||
#### Going from here
|
|
||||||
|
|
||||||
Advanced users may edit the docker-compose file further to include all possible options or arguments.
|
|
||||||
|
|
||||||
All possible freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`.
|
|
||||||
|
|
||||||
!!! Note "`docker-compose run --rm`"
|
|
||||||
Including `--rm` will clean up the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command).
|
|
||||||
|
|
||||||
##### Example: Download data with docker-compose
|
|
||||||
|
|
||||||
Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory `user_data/data/` on the host.
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h
|
|
||||||
```
|
|
||||||
|
|
||||||
Head over to the [Data Downloading Documentation](data-download.md) for more details on downloading data.
|
|
||||||
|
|
||||||
##### Example: Backtest with docker-compose
|
|
||||||
|
|
||||||
Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe:
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m
|
|
||||||
```
|
|
||||||
|
|
||||||
Head over to the [Backtesting Documentation](backtesting.md) to learn more.
|
|
||||||
|
|
||||||
#### Additional dependencies with docker-compose
|
|
||||||
|
|
||||||
If your strategy requires dependencies not included in the default image (like [technical](https://github.com/freqtrade/technical)) - it will be necessary to build the image on your host.
|
|
||||||
For this, please create a Dockerfile containing installation steps for the additional dependencies (have a look at [Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/Dockerfile.technical) for an example).
|
|
||||||
|
|
||||||
You'll then also need to modify the `docker-compose.yml` file and uncomment the build step, as well as rename the image to avoid naming collisions.
|
|
||||||
|
|
||||||
``` yaml
|
|
||||||
image: freqtrade_custom
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: "./Dockerfile.<yourextension>"
|
|
||||||
```
|
|
||||||
|
|
||||||
You can then run `docker-compose build` to build the docker image, and run it using the commands described above.
|
|
||||||
|
|
||||||
## Freqtrade with docker without docker-compose
|
## Freqtrade with docker without docker-compose
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
The below documentation is provided for completeness and assumes that you are somewhat familiar with running docker containers. If you're just starting out with docker, we recommend to follow the [Freqtrade with docker-compose](#freqtrade-with-docker-compose) instructions.
|
The below documentation is provided for completeness and assumes that you are familiar with running docker containers. If you're just starting out with Docker, we recommend to follow the [Quickstart](docker.md) instructions.
|
||||||
|
|
||||||
### Download the official Freqtrade docker image
|
### Download the official Freqtrade docker image
|
||||||
|
|
||||||
@ -148,9 +10,9 @@ Pull the image from docker hub.
|
|||||||
Branches / tags available can be checked out on [Dockerhub tags page](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
Branches / tags available can be checked out on [Dockerhub tags page](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker pull freqtradeorg/freqtrade:develop
|
docker pull freqtradeorg/freqtrade:stable
|
||||||
# Optionally tag the repository so the run-commands remain shorter
|
# Optionally tag the repository so the run-commands remain shorter
|
||||||
docker tag freqtradeorg/freqtrade:develop freqtrade
|
docker tag freqtradeorg/freqtrade:stable freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
To update the image, simply run the above commands again and restart your running container.
|
To update the image, simply run the above commands again and restart your running container.
|
||||||
@ -158,7 +20,7 @@ To update the image, simply run the above commands again and restart your runnin
|
|||||||
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
Should you require additional libraries, please [build the image yourself](#build-your-own-docker-image).
|
||||||
|
|
||||||
!!! Note "Docker image update frequency"
|
!!! Note "Docker image update frequency"
|
||||||
The official docker images with tags `master`, `develop` and `latest` are automatically rebuild once a week to keep the base image uptodate.
|
The official docker images with tags `stable`, `develop` and `latest` are automatically rebuild once a week to keep the base image up-to-date.
|
||||||
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
|
In addition to that, every merge to `develop` will trigger a rebuild for `develop` and `latest`.
|
||||||
|
|
||||||
### Prepare the configuration files
|
### Prepare the configuration files
|
||||||
@ -190,39 +52,38 @@ cp -n config.json.example config.json
|
|||||||
|
|
||||||
#### Create your database file
|
#### Create your database file
|
||||||
|
|
||||||
Production
|
=== "Dry-Run"
|
||||||
|
``` bash
|
||||||
|
touch tradesv3.dryrun.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
```bash
|
=== "Production"
|
||||||
touch tradesv3.sqlite
|
``` bash
|
||||||
````
|
touch tradesv3.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
Dry-Run
|
|
||||||
|
|
||||||
```bash
|
!!! Warning "Database File Path"
|
||||||
touch tradesv3.dryrun.sqlite
|
Make sure to use the path to the correct database file when starting the bot in Docker.
|
||||||
```
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Make sure to use the path to this file when starting the bot in docker.
|
|
||||||
|
|
||||||
### Build your own Docker image
|
### Build your own Docker image
|
||||||
|
|
||||||
Best start by pulling the official docker image from dockerhub as explained [here](#download-the-official-docker-image) to speed up building.
|
Best start by pulling the official docker image from dockerhub as explained [here](#download-the-official-docker-image) to speed up building.
|
||||||
|
|
||||||
To add additional libraries to your docker image, best check out [Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/Dockerfile.technical) which adds the [technical](https://github.com/freqtrade/technical) module to the image.
|
To add additional libraries to your docker image, best check out [Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/docker/Dockerfile.technical) which adds the [technical](https://github.com/freqtrade/technical) module to the image.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker build -t freqtrade -f Dockerfile.technical .
|
docker build -t freqtrade -f docker/Dockerfile.technical .
|
||||||
```
|
```
|
||||||
|
|
||||||
If you are developing using Docker, use `Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
|
If you are developing using Docker, use `docker/Dockerfile.develop` to build a dev Docker image, which will also set up develop dependencies:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker build -f Dockerfile.develop -t freqtrade-dev .
|
docker build -f docker/Dockerfile.develop -t freqtrade-dev .
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Warning "Include your config file manually"
|
||||||
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see the "5. Run a restartable docker image" section) to keep it between updates.
|
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see [5. Run a restartable docker image](#run-a-restartable-docker-image)") to keep it between updates.
|
||||||
|
|
||||||
#### Verify the Docker image
|
#### Verify the Docker image
|
||||||
|
|
||||||
@ -243,37 +104,36 @@ docker run --rm -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
In this example, the database will be created inside the docker instance and will be lost when you will refresh your image.
|
In this example, the database will be created inside the docker instance and will be lost when you refresh your image.
|
||||||
|
|
||||||
#### Adjust timezone
|
#### Adjust timezone
|
||||||
|
|
||||||
By default, the container will use UTC timezone.
|
By default, the container will use UTC timezone.
|
||||||
Should you find this irritating please add the following to your docker commands:
|
If you would like to change the timezone use the following commands:
|
||||||
|
|
||||||
##### Linux
|
=== "Linux"
|
||||||
|
``` bash
|
||||||
|
-v /etc/timezone:/etc/timezone:ro
|
||||||
|
|
||||||
``` bash
|
# Complete command:
|
||||||
-v /etc/timezone:/etc/timezone:ro
|
docker run --rm -v /etc/timezone:/etc/timezone:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
# Complete command:
|
=== "MacOS"
|
||||||
docker run --rm -v /etc/timezone:/etc/timezone:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
```bash
|
||||||
```
|
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
##### MacOS
|
!!! Note "MacOS Issues"
|
||||||
|
The OSX Docker versions after 17.09.1 have a known issue whereby `/etc/localtime` cannot be shared causing Docker to not start.<br>
|
||||||
There is known issue in OSX Docker versions after 17.09.1, whereby `/etc/localtime` cannot be shared causing Docker to not start. A work-around for this is to start with the following cmd.
|
A work-around for this is to start with the MacOS command above
|
||||||
|
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
||||||
```bash
|
|
||||||
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
More information on this docker issue and work-around can be read [here](https://github.com/docker/for-mac/issues/2396).
|
|
||||||
|
|
||||||
### Run a restartable docker image
|
### Run a restartable docker image
|
||||||
|
|
||||||
To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
|
To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
|
||||||
|
|
||||||
#### Move your config file and database
|
#### 1. Move your config file and database
|
||||||
|
|
||||||
The following will assume that you place your configuration / database files to `~/.freqtrade`, which is a hidden directory in your home directory. Feel free to use a different directory and replace the directory in the upcomming commands.
|
The following will assume that you place your configuration / database files to `~/.freqtrade`, which is a hidden directory in your home directory. Feel free to use a different directory and replace the directory in the upcomming commands.
|
||||||
|
|
||||||
@ -283,7 +143,7 @@ mv config.json ~/.freqtrade
|
|||||||
mv tradesv3.sqlite ~/.freqtrade
|
mv tradesv3.sqlite ~/.freqtrade
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Run the docker image
|
#### 2. Run the docker image
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run -d \
|
docker run -d \
|
||||||
|
191
docs/docker_quickstart.md
Normal file
191
docs/docker_quickstart.md
Normal file
@ -0,0 +1,191 @@
|
|||||||
|
# Using Freqtrade with Docker
|
||||||
|
|
||||||
|
## Install Docker
|
||||||
|
|
||||||
|
Start by downloading and installing Docker CE for your platform:
|
||||||
|
|
||||||
|
* [Mac](https://docs.docker.com/docker-for-mac/install/)
|
||||||
|
* [Windows](https://docs.docker.com/docker-for-windows/install/)
|
||||||
|
* [Linux](https://docs.docker.com/install/)
|
||||||
|
|
||||||
|
Optionally, [`docker-compose`](https://docs.docker.com/compose/install/) should be installed and available to follow the [docker quick start guide](#docker-quick-start).
|
||||||
|
|
||||||
|
Once you have Docker installed, simply prepare the config file (e.g. `config.json`) and run the image for `freqtrade` as explained below.
|
||||||
|
|
||||||
|
## Freqtrade with docker-compose
|
||||||
|
|
||||||
|
Freqtrade provides an official Docker image on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/), as well as a [docker-compose file](https://github.com/freqtrade/freqtrade/blob/develop/docker-compose.yml) ready for usage.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
- The following section assumes that `docker` and `docker-compose` are installed and available to the logged in user.
|
||||||
|
- All below commands use relative directories and will have to be executed from the directory containing the `docker-compose.yml` file.
|
||||||
|
|
||||||
|
### Docker quick start
|
||||||
|
|
||||||
|
Create a new directory and place the [docker-compose file](https://github.com/freqtrade/freqtrade/blob/develop/docker-compose.yml) in this directory.
|
||||||
|
|
||||||
|
=== "PC/MAC/Linux"
|
||||||
|
``` bash
|
||||||
|
mkdir ft_userdata
|
||||||
|
cd ft_userdata/
|
||||||
|
# Download the docker-compose file from the repository
|
||||||
|
curl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml
|
||||||
|
|
||||||
|
# Pull the freqtrade image
|
||||||
|
docker-compose pull
|
||||||
|
|
||||||
|
# Create user directory structure
|
||||||
|
docker-compose run --rm freqtrade create-userdir --userdir user_data
|
||||||
|
|
||||||
|
# Create configuration - Requires answering interactive questions
|
||||||
|
docker-compose run --rm freqtrade new-config --config user_data/config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "RaspberryPi"
|
||||||
|
``` bash
|
||||||
|
mkdir ft_userdata
|
||||||
|
cd ft_userdata/
|
||||||
|
# Download the docker-compose file from the repository
|
||||||
|
curl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml
|
||||||
|
|
||||||
|
# Pull the freqtrade image
|
||||||
|
docker-compose pull
|
||||||
|
|
||||||
|
# Create user directory structure
|
||||||
|
docker-compose run --rm freqtrade create-userdir --userdir user_data
|
||||||
|
|
||||||
|
# Create configuration - Requires answering interactive questions
|
||||||
|
docker-compose run --rm freqtrade new-config --config user_data/config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note "Change your docker Image"
|
||||||
|
You have to change the docker image in the docker-compose file for your Raspberry build to work properly.
|
||||||
|
``` yml
|
||||||
|
image: freqtradeorg/freqtrade:stable_pi
|
||||||
|
# image: freqtradeorg/freqtrade:develop_pi
|
||||||
|
```
|
||||||
|
|
||||||
|
The above snippet creates a new directory called `ft_userdata`, downloads the latest compose file and pulls the freqtrade image.
|
||||||
|
The last 2 steps in the snippet create the directory with `user_data`, as well as (interactively) the default configuration based on your selections.
|
||||||
|
|
||||||
|
!!! Question "How to edit the bot configuration?"
|
||||||
|
You can edit the configuration at any time, which is available as `user_data/config.json` (within the directory `ft_userdata`) when using the above configuration.
|
||||||
|
|
||||||
|
You can also change the both Strategy and commands by editing the `docker-compose.yml` file.
|
||||||
|
|
||||||
|
#### Adding a custom strategy
|
||||||
|
|
||||||
|
1. The configuration is now available as `user_data/config.json`
|
||||||
|
2. Copy a custom strategy to the directory `user_data/strategies/`
|
||||||
|
3. add the Strategy' class name to the `docker-compose.yml` file
|
||||||
|
|
||||||
|
The `SampleStrategy` is run by default.
|
||||||
|
|
||||||
|
!!! Warning "`SampleStrategy` is just a demo!"
|
||||||
|
The `SampleStrategy` is there for your reference and give you ideas for your own strategy.
|
||||||
|
Please always backtest the strategy and use dry-run for some time before risking real money!
|
||||||
|
|
||||||
|
Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above).
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Docker-compose logs
|
||||||
|
|
||||||
|
Logs will be located at: `user_data/logs/freqtrade.log`.
|
||||||
|
You can check the latest log with the command `docker-compose logs -f`.
|
||||||
|
|
||||||
|
#### Database
|
||||||
|
|
||||||
|
The database will be at: `user_data/tradesv3.sqlite`
|
||||||
|
|
||||||
|
#### Updating freqtrade with docker-compose
|
||||||
|
|
||||||
|
To update freqtrade when using `docker-compose` is as simple as running the following 2 commands:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
# Download the latest image
|
||||||
|
docker-compose pull
|
||||||
|
# Restart the image
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
This will first pull the latest image, and will then restart the container with the just pulled version.
|
||||||
|
|
||||||
|
!!! Warning "Check the Changelog"
|
||||||
|
You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.
|
||||||
|
|
||||||
|
### Editing the docker-compose file
|
||||||
|
|
||||||
|
Advanced users may edit the docker-compose file further to include all possible options or arguments.
|
||||||
|
|
||||||
|
All possible freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`.
|
||||||
|
|
||||||
|
!!! Note "`docker-compose run --rm`"
|
||||||
|
Including `--rm` will clean up the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command).
|
||||||
|
|
||||||
|
#### Example: Download data with docker-compose
|
||||||
|
|
||||||
|
Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory `user_data/data/` on the host.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h
|
||||||
|
```
|
||||||
|
|
||||||
|
Head over to the [Data Downloading Documentation](data-download.md) for more details on downloading data.
|
||||||
|
|
||||||
|
#### Example: Backtest with docker-compose
|
||||||
|
|
||||||
|
Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m
|
||||||
|
```
|
||||||
|
|
||||||
|
Head over to the [Backtesting Documentation](backtesting.md) to learn more.
|
||||||
|
|
||||||
|
### Additional dependencies with docker-compose
|
||||||
|
|
||||||
|
If your strategy requires dependencies not included in the default image (like [technical](https://github.com/freqtrade/technical)) - it will be necessary to build the image on your host.
|
||||||
|
For this, please create a Dockerfile containing installation steps for the additional dependencies (have a look at [docker/Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/docker/Dockerfile.technical) for an example).
|
||||||
|
|
||||||
|
You'll then also need to modify the `docker-compose.yml` file and uncomment the build step, as well as rename the image to avoid naming collisions.
|
||||||
|
|
||||||
|
``` yaml
|
||||||
|
image: freqtrade_custom
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: "./Dockerfile.<yourextension>"
|
||||||
|
```
|
||||||
|
|
||||||
|
You can then run `docker-compose build` to build the docker image, and run it using the commands described above.
|
||||||
|
|
||||||
|
## Plotting with docker-compose
|
||||||
|
|
||||||
|
Commands `freqtrade plot-profit` and `freqtrade plot-dataframe` ([Documentation](plotting.md)) are available by changing the image to `*_plot` in your docker-compose.yml file.
|
||||||
|
You can then use these commands as follows:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805
|
||||||
|
```
|
||||||
|
|
||||||
|
The output will be stored in the `user_data/plot` directory, and can be opened with any modern browser.
|
||||||
|
|
||||||
|
## Data analayis using docker compose
|
||||||
|
|
||||||
|
Freqtrade provides a docker-compose file which starts up a jupyter lab server.
|
||||||
|
You can run this server using the following command:
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose --rm -f docker/docker-compose-jupyter.yml up
|
||||||
|
```
|
||||||
|
|
||||||
|
This will create a dockercontainer running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`.
|
||||||
|
Please use the link that's printed in the console after startup for simplified login.
|
||||||
|
|
||||||
|
Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) uptodate.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose -f docker/docker-compose-jupyter.yml build --no-cache
|
||||||
|
```
|
230
docs/edge.md
230
docs/edge.md
@ -1,95 +1,160 @@
|
|||||||
# Edge positioning
|
# Edge positioning
|
||||||
|
|
||||||
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
|
The `Edge Positioning` module uses probability to calculate your win rate and risk reward ration. It will use these statistics to control your strategy trade entry points, position side and, stoploss.
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
Edge positioning is not compatible with dynamic (volume-based) whitelist.
|
`Edge positioning` is not compatible with dynamic (volume-based) whitelist.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Edge does not consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else are ignored in its calculation.
|
`Edge Positioning` only considers *its own* buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file.
|
||||||
|
`Edge Positioning` improves the performance of some trading strategies and *decreases* the performance of others.
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
|
|
||||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.
|
Trading strategies are not perfect. They are frameworks that are susceptible to the market and its indicators. Because the market is not at all predictable, sometimes a strategy will win and sometimes the same strategy will lose.
|
||||||
|
|
||||||
But it doesn't mean there is no rule, it only means rules should work "most of the time". Let's play a game: we toss a coin, heads: I give you 10$, tails: you give me 10$. Is it an interesting game? No, it's quite boring, isn't it?
|
To obtain an edge in the market, a strategy has to make more money than it loses. Making money in trading is not only about *how often* the strategy makes or loses money.
|
||||||
|
|
||||||
But let's say the probability that we have heads is 80% (because our coin has the displaced distribution of mass or other defect), and the probability that we have tails is 20%. Now it is becoming interesting...
|
!!! tip "It doesn't matter how often, but how much!"
|
||||||
|
A bad strategy might make 1 penny in *ten* transactions but lose 1 dollar in *one* transaction. If one only checks the number of winning trades, it would be misleading to think that the strategy is actually making a profit.
|
||||||
|
|
||||||
That means 10$ X 80% versus 10$ X 20%. 8$ versus 2$. That means over time you will win 8$ risking only 2$ on each toss of coin.
|
The Edge Positioning module seeks to improve a strategy's winning probability and the money that the strategy will make *on the long run*.
|
||||||
|
|
||||||
Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the time but 8$. The calculation is: 80% X 2$ versus 20% X 8$. It is becoming boring again because overtime you win $1.6$ (80% X 2$) and me $1.6 (20% X 8$) too.
|
We raise the following question[^1]:
|
||||||
|
|
||||||
The question is: How do you calculate that? How do you know if you wanna play?
|
!!! Question "Which trade is a better option?"
|
||||||
|
a) A trade with 80% of chance of losing 100\$ and 20% chance of winning 200\$<br/>
|
||||||
|
b) A trade with 100% of chance of losing 30\$
|
||||||
|
|
||||||
The answer comes to two factors:
|
???+ Info "Answer"
|
||||||
|
The expected value of *a)* is smaller than the expected value of *b)*.<br/>
|
||||||
|
Hence, *b*) represents a smaller loss in the long run.<br/>
|
||||||
|
However, the answer is: *it depends*
|
||||||
|
|
||||||
- Win Rate
|
Another way to look at it is to ask a similar question:
|
||||||
- Risk Reward Ratio
|
|
||||||
|
|
||||||
### Win Rate
|
!!! Question "Which trade is a better option?"
|
||||||
|
a) A trade with 80% of chance of winning 100\$ and 20% chance of losing 200\$<br/>
|
||||||
|
b) A trade with 100% of chance of winning 30\$
|
||||||
|
|
||||||
Win Rate (*W*) is is the mean over some amount of trades (*N*) what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only if you won or not).
|
Edge positioning tries to answer the hard questions about risk/reward and position size automatically, seeking to minimizes the chances of losing of a given strategy.
|
||||||
|
|
||||||
```
|
### Trading, winning and losing
|
||||||
W = (Number of winning trades) / (Total number of trades) = (Number of winning trades) / N
|
|
||||||
```
|
|
||||||
|
|
||||||
Complementary Loss Rate (*L*) is defined as
|
Let's call $o$ the return of a single transaction $o$ where $o \in \mathbb{R}$. The collection $O = \{o_1, o_2, ..., o_N\}$ is the set of all returns of transactions made during a trading session. We say that $N$ is the cardinality of $O$, or, in lay terms, it is the number of transactions made in a trading session.
|
||||||
|
|
||||||
```
|
!!! Example
|
||||||
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N
|
In a session where a strategy made three transactions we can say that $O = \{3.5, -1, 15\}$. That means that $N = 3$ and $o_1 = 3.5$, $o_2 = -1$, $o_3 = 15$.
|
||||||
```
|
|
||||||
|
|
||||||
or, which is the same, as
|
A winning trade is a trade where a strategy *made* money. Making money means that the strategy closed the position in a value that returned a profit, after all deducted fees. Formally, a winning trade will have a return $o_i > 0$. Similarly, a losing trade will have a return $o_j \leq 0$. With that, we can discover the set of all winning trades, $T_{win}$, as follows:
|
||||||
|
|
||||||
```
|
$$ T_{win} = \{ o \in O | o > 0 \} $$
|
||||||
L = 1 – W
|
|
||||||
```
|
Similarly, we can discover the set of losing trades $T_{lose}$ as follows:
|
||||||
|
|
||||||
|
$$ T_{lose} = \{o \in O | o \leq 0\} $$
|
||||||
|
|
||||||
|
!!! Example
|
||||||
|
In a section where a strategy made three transactions $O = \{3.5, -1, 15, 0\}$:<br>
|
||||||
|
$T_{win} = \{3.5, 15\}$<br>
|
||||||
|
$T_{lose} = \{-1, 0\}$<br>
|
||||||
|
|
||||||
|
### Win Rate and Lose Rate
|
||||||
|
|
||||||
|
The win rate $W$ is the proportion of winning trades with respect to all the trades made by a strategy. We use the following function to compute the win rate:
|
||||||
|
|
||||||
|
$$W = \frac{|T_{win}|}{N}$$
|
||||||
|
|
||||||
|
Where $W$ is the win rate, $N$ is the number of trades and, $T_{win}$ is the set of all trades where the strategy made money.
|
||||||
|
|
||||||
|
Similarly, we can compute the rate of losing trades:
|
||||||
|
|
||||||
|
$$
|
||||||
|
L = \frac{|T_{lose}|}{N}
|
||||||
|
$$
|
||||||
|
|
||||||
|
Where $L$ is the lose rate, $N$ is the amount of trades made and, $T_{lose}$ is the set of all trades where the strategy lost money. Note that the above formula is the same as calculating $L = 1 – W$ or $W = 1 – L$
|
||||||
|
|
||||||
### Risk Reward Ratio
|
### Risk Reward Ratio
|
||||||
|
|
||||||
Risk Reward Ratio (*R*) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
Risk Reward Ratio ($R$) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose. Formally:
|
||||||
|
|
||||||
```
|
$$ R = \frac{\text{potential_profit}}{\text{potential_loss}} $$
|
||||||
R = Profit / Loss
|
|
||||||
```
|
|
||||||
|
|
||||||
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
???+ Example "Worked example of $R$ calculation"
|
||||||
|
Let's say that you think that the price of *stonecoin* today is 10.0\$. You believe that, because they will start mining stonecoin, it will go up to 15.0\$ tomorrow. There is the risk that the stone is too hard, and the GPUs can't mine it, so the price might go to 0\$ tomorrow. You are planning to invest 100\$, which will give you 10 shares (100 / 10).
|
||||||
|
|
||||||
```
|
Your potential profit is calculated as:
|
||||||
Average profit = (Sum of profits) / (Number of winning trades)
|
|
||||||
|
|
||||||
Average loss = (Sum of losses) / (Number of losing trades)
|
$\begin{aligned}
|
||||||
|
\text{potential_profit} &= (\text{potential_price} - \text{entry_price}) * \frac{\text{investment}}{\text{entry_price}} \\
|
||||||
|
&= (15 - 10) * (100 / 10) \\
|
||||||
|
&= 50
|
||||||
|
\end{aligned}$
|
||||||
|
|
||||||
R = (Average profit) / (Average loss)
|
Since the price might go to 0\$, the 100\$ dollars invested could turn into 0.
|
||||||
```
|
|
||||||
|
We do however use a stoploss of 15% - so in the worst case, we'll sell 15% below entry price (or at 8.5$\).
|
||||||
|
|
||||||
|
$\begin{aligned}
|
||||||
|
\text{potential_loss} &= (\text{entry_price} - \text{stoploss}) * \frac{\text{investment}}{\text{entry_price}} \\
|
||||||
|
&= (10 - 8.5) * (100 / 10)\\
|
||||||
|
&= 15
|
||||||
|
\end{aligned}$
|
||||||
|
|
||||||
|
We can compute the Risk Reward Ratio as follows:
|
||||||
|
|
||||||
|
$\begin{aligned}
|
||||||
|
R &= \frac{\text{potential_profit}}{\text{potential_loss}}\\
|
||||||
|
&= \frac{50}{15}\\
|
||||||
|
&= 3.33
|
||||||
|
\end{aligned}$<br>
|
||||||
|
What it effectively means is that the strategy have the potential to make 3.33\$ for each 1\$ invested.
|
||||||
|
|
||||||
|
On a long horizon, that is, on many trades, we can calculate the risk reward by dividing the strategy' average profit on winning trades by the strategy' average loss on losing trades. We can calculate the average profit, $\mu_{win}$, as follows:
|
||||||
|
|
||||||
|
$$ \text{average_profit} = \mu_{win} = \frac{\text{sum_of_profits}}{\text{count_winning_trades}} = \frac{\sum^{o \in T_{win}} o}{|T_{win}|} $$
|
||||||
|
|
||||||
|
Similarly, we can calculate the average loss, $\mu_{lose}$, as follows:
|
||||||
|
|
||||||
|
$$ \text{average_loss} = \mu_{lose} = \frac{\text{sum_of_losses}}{\text{count_losing_trades}} = \frac{\sum^{o \in T_{lose}} o}{|T_{lose}|} $$
|
||||||
|
|
||||||
|
Finally, we can calculate the Risk Reward ratio, $R$, as follows:
|
||||||
|
|
||||||
|
$$ R = \frac{\text{average_profit}}{\text{average_loss}} = \frac{\mu_{win}}{\mu_{lose}}\\ $$
|
||||||
|
|
||||||
|
|
||||||
|
???+ Example "Worked example of $R$ calculation using mean profit/loss"
|
||||||
|
Let's say the strategy that we are using makes an average win $\mu_{win} = 2.06$ and an average loss $\mu_{loss} = 4.11$.<br>
|
||||||
|
We calculate the risk reward ratio as follows:<br>
|
||||||
|
$R = \frac{\mu_{win}}{\mu_{loss}} = \frac{2.06}{4.11} = 0.5012...$
|
||||||
|
|
||||||
|
|
||||||
### Expectancy
|
### Expectancy
|
||||||
|
|
||||||
At this point we can combine *W* and *R* to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades and subtracting the percentage of losing trades, which is calculated as follows:
|
By combining the Win Rate $W$ and and the Risk Reward ratio $R$ to create an expectancy ratio $E$. A expectance ratio is the expected return of the investment made in a trade. We can compute the value of $E$ as follows:
|
||||||
|
|
||||||
```
|
$$E = R * W - L$$
|
||||||
Expectancy Ratio = (Risk Reward Ratio X Win Rate) – Loss Rate = (R X W) – L
|
|
||||||
```
|
|
||||||
|
|
||||||
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
!!! Example "Calculating $E$"
|
||||||
|
Let's say that a strategy has a win rate $W = 0.28$ and a risk reward ratio $R = 5$. What this means is that the strategy is expected to make 5 times the investment around on 28% of the trades it makes. Working out the example:<br>
|
||||||
|
$E = R * W - L = 5 * 0.28 - 0.72 = 0.68$
|
||||||
|
<br>
|
||||||
|
|
||||||
```
|
The expectancy worked out in the example above means that, on average, this strategy' trades will return 1.68 times the size of its losses. Said another way, the strategy makes 1.68\$ for every 1\$ it loses, on average.
|
||||||
Expectancy = (5 X 0.28) – 0.72 = 0.68
|
|
||||||
```
|
|
||||||
|
|
||||||
Superficially, this means that on average you expect this strategy’s trades to return 1.68 times the size of your loses. Said another way, you can expect to win $1.68 for every $1 you lose. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
||||||
|
|
||||||
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
|
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
|
||||||
|
|
||||||
You can also use this value to evaluate the effectiveness of modifications to this system.
|
You can also use this value to evaluate the effectiveness of modifications to this system.
|
||||||
|
|
||||||
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
!!! Note
|
||||||
|
It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
||||||
|
|
||||||
## How does it work?
|
## How does it work?
|
||||||
|
|
||||||
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over *N* trades for each stoploss. Here is an example:
|
Edge combines dynamic stoploss, dynamic positions, and whitelist generation into one isolated module which is then applied to the trading strategy. If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over *N* trades for each stoploss. Here is an example:
|
||||||
|
|
||||||
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
||||||
|----------|:-------------:|-------------:|------------------:|-----------:|
|
|----------|:-------------:|-------------:|------------------:|-----------:|
|
||||||
@ -98,13 +163,13 @@ If enabled in config, Edge will go through historical data with a range of stopl
|
|||||||
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
| XZC/ETH | -0.03 | 0.52 |1.359670 | 0.228 |
|
||||||
| XZC/ETH | -0.04 | 0.51 |1.234539 | 0.117 |
|
| XZC/ETH | -0.04 | 0.51 |1.234539 | 0.117 |
|
||||||
|
|
||||||
The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at 3% leads to the maximum expectancy according to historical data.
|
The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at $3%$ leads to the maximum expectancy according to historical data.
|
||||||
|
|
||||||
Edge module then forces stoploss value it evaluated to your strategy dynamically.
|
Edge module then forces stoploss value it evaluated to your strategy dynamically.
|
||||||
|
|
||||||
### Position size
|
### Position size
|
||||||
|
|
||||||
Edge also dictates the stake amount for each trade to the bot according to the following factors:
|
Edge dictates the amount at stake for each trade to the bot according to the following factors:
|
||||||
|
|
||||||
- Allowed capital at risk
|
- Allowed capital at risk
|
||||||
- Stoploss
|
- Stoploss
|
||||||
@ -115,9 +180,9 @@ Allowed capital at risk is calculated as follows:
|
|||||||
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
||||||
```
|
```
|
||||||
|
|
||||||
Stoploss is calculated as described above against historical data.
|
Stoploss is calculated as described above with respect to historical data.
|
||||||
|
|
||||||
Your position size then will be:
|
The position size is calculated as follows:
|
||||||
|
|
||||||
```
|
```
|
||||||
Position size = (Allowed capital at risk) / Stoploss
|
Position size = (Allowed capital at risk) / Stoploss
|
||||||
@ -125,19 +190,23 @@ Position size = (Allowed capital at risk) / Stoploss
|
|||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your capital available percentage is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is **10 x 0.5 = 5 ETH** and allowed capital at risk would be **5 x 0.01 = 0.05 ETH**.
|
Let's say the stake currency is **ETH** and there is $10$ **ETH** on the wallet. The capital available percentage is $50%$ and the allowed risk per trade is $1\%$. Thus, the available capital for trading is $10 * 0.5 = 5$ **ETH** and the allowed capital at risk would be $5 * 0.01 = 0.05$ **ETH**.
|
||||||
|
|
||||||
Let's assume Edge has calculated that for **XLM/ETH** market your stoploss should be at 2%. So your position size will be **0.05 / 0.02 = 2.5 ETH**.
|
- **Trade 1:** The strategy detects a new buy signal in the **XLM/ETH** market. `Edge Positioning` calculates a stoploss of $2\%$ and a position of $0.05 / 0.02 = 2.5$ **ETH**. The bot takes a position of $2.5$ **ETH** in the **XLM/ETH** market.
|
||||||
|
|
||||||
Bot takes a position of 2.5 ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on **BTC/ETH** market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25 ETH (call it trade 2).
|
- **Trade 2:** The strategy detects a buy signal on the **BTC/ETH** market while **Trade 1** is still open. `Edge Positioning` calculates the stoploss of $4\%$ on this market. Thus, **Trade 2** position size is $0.05 / 0.04 = 1.25$ **ETH**.
|
||||||
|
|
||||||
Note that available capital for trading didn’t change for trade 2 even if you had already trade 1. The available capital doesn’t mean the free amount on your wallet.
|
!!! Tip "Available Capital $\neq$ Available in wallet"
|
||||||
|
The available capital for trading didn't change in **Trade 2** even with **Trade 1** still open. The available capital **is not** the free amount in the wallet.
|
||||||
|
|
||||||
Now you have two trades open. The bot receives yet another buy signal for another market: **ADA/ETH**. This time the stoploss is calculated at 1%. So your position size is **0.05 / 0.01 = 5 ETH**. But there are already 3.75 ETH blocked in two previous trades. So the position size for this third trade would be **5 – 3.75 = 1.25 ETH**.
|
- **Trade 3:** The strategy detects a buy signal in the **ADA/ETH** market. `Edge Positioning` calculates a stoploss of $1\%$ and a position of $0.05 / 0.01 = 5$ **ETH**. Since **Trade 1** has $2.5$ **ETH** blocked and **Trade 2** has $1.25$ **ETH** blocked, there is only $5 - 1.25 - 2.5 = 1.25$ **ETH** available. Hence, the position size of **Trade 3** is $1.25$ **ETH**.
|
||||||
|
|
||||||
Available capital doesn’t change before a position is sold. Let’s assume that trade 1 receives a sell signal and it is sold with a profit of 1 ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5 ETH.
|
!!! Tip "Available Capital Updates"
|
||||||
|
The available capital does not change before a position is sold. After a trade is closed the Available Capital goes up if the trade was profitable or goes down if the trade was a loss.
|
||||||
|
|
||||||
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be **0.055 / 0.02 = 2.75 ETH**.
|
- The strategy detects a sell signal in the **XLM/ETH** market. The bot exits **Trade 1** for a profit of $1$ **ETH**. The total capital in the wallet becomes $11$ **ETH** and the available capital for trading becomes $5.5$ **ETH**.
|
||||||
|
|
||||||
|
- **Trade 4** The strategy detects a new buy signal int the **XLM/ETH** market. `Edge Positioning` calculates the stoploss of $2%$, and the position size of $0.055 / 0.02 = 2.75$ **ETH**.
|
||||||
|
|
||||||
## Configurations
|
## Configurations
|
||||||
|
|
||||||
@ -153,9 +222,9 @@ Edge module has following configuration options:
|
|||||||
| `stoploss_range_max` | Maximum stoploss. <br>*Defaults to `-0.10`.* <br> **Datatype:** Float
|
| `stoploss_range_max` | Maximum stoploss. <br>*Defaults to `-0.10`.* <br> **Datatype:** Float
|
||||||
| `stoploss_range_step` | As an example if this is set to -0.01 then Edge will test the strategy for `[-0.01, -0,02, -0,03 ..., -0.09, -0.10]` ranges. <br> **Note** than having a smaller step means having a bigger range which could lead to slow calculation. <br> If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br>*Defaults to `-0.001`.* <br> **Datatype:** Float
|
| `stoploss_range_step` | As an example if this is set to -0.01 then Edge will test the strategy for `[-0.01, -0,02, -0,03 ..., -0.09, -0.10]` ranges. <br> **Note** than having a smaller step means having a bigger range which could lead to slow calculation. <br> If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br>*Defaults to `-0.001`.* <br> **Datatype:** Float
|
||||||
| `minimum_winrate` | It filters out pairs which don't have at least minimum_winrate. <br>This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. <br>*Defaults to `0.60`.* <br> **Datatype:** Float
|
| `minimum_winrate` | It filters out pairs which don't have at least minimum_winrate. <br>This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. <br>*Defaults to `0.60`.* <br> **Datatype:** Float
|
||||||
| `minimum_expectancy` | It filters out pairs which have the expectancy lower than this number. <br>Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return. <br>*Defaults to `0.20`.* <br> **Datatype:** Float
|
| `minimum_expectancy` | It filters out pairs which have the expectancy lower than this number. <br>Having an expectancy of 0.20 means if you put 10\$ on a trade you expect a 12\$ return. <br>*Defaults to `0.20`.* <br> **Datatype:** Float
|
||||||
| `min_trade_number` | When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. <br>Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. <br>*Defaults to `10` (it is highly recommended not to decrease this number).* <br> **Datatype:** Integer
|
| `min_trade_number` | When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. <br>Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. <br>*Defaults to `10` (it is highly recommended not to decrease this number).* <br> **Datatype:** Integer
|
||||||
| `max_trade_duration_minute` | Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.<br>**NOTICE:** While configuring this value, you should take into consideration your timeframe (ticker interval). As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).<br>*Defaults to `1440` (one day).* <br> **Datatype:** Integer
|
| `max_trade_duration_minute` | Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.<br>**NOTICE:** While configuring this value, you should take into consideration your timeframe. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).<br>*Defaults to `1440` (one day).* <br> **Datatype:** Integer
|
||||||
| `remove_pumps` | Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.<br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `remove_pumps` | Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.<br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
|
|
||||||
## Running Edge independently
|
## Running Edge independently
|
||||||
@ -168,23 +237,29 @@ freqtrade edge
|
|||||||
|
|
||||||
An example of its output:
|
An example of its output:
|
||||||
|
|
||||||
| pair | stoploss | win rate | risk reward ratio | required risk reward | expectancy | total number of trades | average duration (min) |
|
| **pair** | **stoploss** | **win rate** | **risk reward ratio** | **required risk reward** | **expectancy** | **total number of trades** | **average duration (min)** |
|
||||||
|:----------|-----------:|-----------:|--------------------:|-----------------------:|-------------:|-------------------------:|-------------------------:|
|
|:----------|-----------:|-----------:|--------------------:|-----------------------:|-------------:|-----------------:|---------------:|
|
||||||
| AGI/BTC | -0.02 | 0.64 | 5.86 | 0.56 | 3.41 | 14 | 54 |
|
| **AGI/BTC** | -0.02 | 0.64 | 5.86 | 0.56 | 3.41 | 14 | 54 |
|
||||||
| NXS/BTC | -0.03 | 0.64 | 2.99 | 0.57 | 1.54 | 11 | 26 |
|
| **NXS/BTC** | -0.03 | 0.64 | 2.99 | 0.57 | 1.54 | 11 | 26 |
|
||||||
| LEND/BTC | -0.02 | 0.82 | 2.05 | 0.22 | 1.50 | 11 | 36 |
|
| **LEND/BTC** | -0.02 | 0.82 | 2.05 | 0.22 | 1.50 | 11 | 36 |
|
||||||
| VIA/BTC | -0.01 | 0.55 | 3.01 | 0.83 | 1.19 | 11 | 48 |
|
| **VIA/BTC** | -0.01 | 0.55 | 3.01 | 0.83 | 1.19 | 11 | 48 |
|
||||||
| MTH/BTC | -0.09 | 0.56 | 2.82 | 0.80 | 1.12 | 18 | 52 |
|
| **MTH/BTC** | -0.09 | 0.56 | 2.82 | 0.80 | 1.12 | 18 | 52 |
|
||||||
| ARDR/BTC | -0.04 | 0.42 | 3.14 | 1.40 | 0.73 | 12 | 42 |
|
| **ARDR/BTC** | -0.04 | 0.42 | 3.14 | 1.40 | 0.73 | 12 | 42 |
|
||||||
| BCPT/BTC | -0.01 | 0.71 | 1.34 | 0.40 | 0.67 | 14 | 30 |
|
| **BCPT/BTC** | -0.01 | 0.71 | 1.34 | 0.40 | 0.67 | 14 | 30 |
|
||||||
| WINGS/BTC | -0.02 | 0.56 | 1.97 | 0.80 | 0.65 | 27 | 42 |
|
| **WINGS/BTC** | -0.02 | 0.56 | 1.97 | 0.80 | 0.65 | 27 | 42 |
|
||||||
| VIBE/BTC | -0.02 | 0.83 | 0.91 | 0.20 | 0.59 | 12 | 35 |
|
| **VIBE/BTC** | -0.02 | 0.83 | 0.91 | 0.20 | 0.59 | 12 | 35 |
|
||||||
| MCO/BTC | -0.02 | 0.79 | 0.97 | 0.27 | 0.55 | 14 | 31 |
|
| **MCO/BTC** | -0.02 | 0.79 | 0.97 | 0.27 | 0.55 | 14 | 31 |
|
||||||
| GNT/BTC | -0.02 | 0.50 | 2.06 | 1.00 | 0.53 | 18 | 24 |
|
| **GNT/BTC** | -0.02 | 0.50 | 2.06 | 1.00 | 0.53 | 18 | 24 |
|
||||||
| HOT/BTC | -0.01 | 0.17 | 7.72 | 4.81 | 0.50 | 209 | 7 |
|
| **HOT/BTC** | -0.01 | 0.17 | 7.72 | 4.81 | 0.50 | 209 | 7 |
|
||||||
| SNM/BTC | -0.03 | 0.71 | 1.06 | 0.42 | 0.45 | 17 | 38 |
|
| **SNM/BTC** | -0.03 | 0.71 | 1.06 | 0.42 | 0.45 | 17 | 38 |
|
||||||
| APPC/BTC | -0.02 | 0.44 | 2.28 | 1.27 | 0.44 | 25 | 43 |
|
| **APPC/BTC** | -0.02 | 0.44 | 2.28 | 1.27 | 0.44 | 25 | 43 |
|
||||||
| NEBL/BTC | -0.03 | 0.63 | 1.29 | 0.58 | 0.44 | 19 | 59 |
|
| **NEBL/BTC** | -0.03 | 0.63 | 1.29 | 0.58 | 0.44 | 19 | 59 |
|
||||||
|
|
||||||
|
Edge produced the above table by comparing `calculate_since_number_of_days` to `minimum_expectancy` to find `min_trade_number` historical information based on the config file. The timerange Edge uses for its comparisons can be further limited by using the `--timerange` switch.
|
||||||
|
|
||||||
|
In live and dry-run modes, after the `process_throttle_secs` has passed, Edge will again process `calculate_since_number_of_days` against `minimum_expectancy` to find `min_trade_number`. If no `min_trade_number` is found, the bot will return "whitelist empty". Depending on the trade strategy being deployed, "whitelist empty" may be return much of the time - or *all* of the time. The use of Edge may also cause trading to occur in bursts, though this is rare.
|
||||||
|
|
||||||
|
If you encounter "whitelist empty" a lot, condsider tuning `calculate_since_number_of_days`, `minimum_expectancy` and `min_trade_number` to align to the trading frequency of your strategy.
|
||||||
|
|
||||||
### Update cached pairs with the latest data
|
### Update cached pairs with the latest data
|
||||||
|
|
||||||
@ -211,3 +286,6 @@ The full timerange specification:
|
|||||||
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
* Use tickframes since 2018/01/31: `--timerange=20180131-`
|
||||||
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
* Use tickframes since 2018/01/31 till 2018/03/01 : `--timerange=20180131-20180301`
|
||||||
* Use tickframes between POSIX timestamps 1527595200 1527618600: `--timerange=1527595200-1527618600`
|
* Use tickframes between POSIX timestamps 1527595200 1527618600: `--timerange=1527595200-1527618600`
|
||||||
|
|
||||||
|
|
||||||
|
[^1]: Question extracted from MIT Opencourseware S096 - Mathematics with applications in Finance: https://ocw.mit.edu/courses/mathematics/18-s096-topics-in-mathematics-with-applications-in-finance-fall-2013/
|
||||||
|
@ -23,7 +23,8 @@ Binance has been split into 3, and users must use the correct ccxt exchange ID f
|
|||||||
## Kraken
|
## Kraken
|
||||||
|
|
||||||
!!! Tip "Stoploss on Exchange"
|
!!! Tip "Stoploss on Exchange"
|
||||||
Kraken supports `stoploss_on_exchange` and uses stop-loss-market orders. It provides great advantages, so we recommend to benefit from it, however since the resulting order is a stoploss-market order, sell-rates are not guaranteed, which makes this feature less secure than on other exchanges. This limitation is based on kraken's policy [source](https://blog.kraken.com/post/1234/announcement-delisting-pairs-and-temporary-suspension-of-advanced-order-types/) and [source2](https://blog.kraken.com/post/1494/kraken-enables-advanced-orders-and-adds-10-currency-pairs/) - which has stoploss-limit orders disabled.
|
Kraken supports `stoploss_on_exchange` and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
|
||||||
|
You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type to use.
|
||||||
|
|
||||||
### Historic Kraken data
|
### Historic Kraken data
|
||||||
|
|
||||||
@ -73,6 +74,10 @@ print(res)
|
|||||||
|
|
||||||
## FTX
|
## FTX
|
||||||
|
|
||||||
|
!!! Tip "Stoploss on Exchange"
|
||||||
|
FTX supports `stoploss_on_exchange` and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
|
||||||
|
You can use either `"limit"` or `"market"` in the `order_types.stoploss` configuration setting to decide which type of stoploss shall be used.
|
||||||
|
|
||||||
### Using subaccounts
|
### Using subaccounts
|
||||||
|
|
||||||
To use subaccounts with FTX, you need to edit the configuration and add the following:
|
To use subaccounts with FTX, you need to edit the configuration and add the following:
|
||||||
@ -94,10 +99,10 @@ To use subaccounts with FTX, you need to edit the configuration and add the foll
|
|||||||
|
|
||||||
Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.
|
Should you experience constant errors with Nonce (like `InvalidNonce`), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.
|
||||||
|
|
||||||
|
|
||||||
## Random notes for other exchanges
|
## Random notes for other exchanges
|
||||||
|
|
||||||
* The Ocean (exchange id: `theocean`) exchange uses Web3 functionality and requires `web3` python package to be installed:
|
* The Ocean (exchange id: `theocean`) exchange uses Web3 functionality and requires `web3` python package to be installed:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ pip3 install web3
|
$ pip3 install web3
|
||||||
```
|
```
|
||||||
|
97
docs/faq.md
97
docs/faq.md
@ -1,25 +1,31 @@
|
|||||||
# Freqtrade FAQ
|
# Freqtrade FAQ
|
||||||
|
|
||||||
|
## Beginner Tips & Tricks
|
||||||
|
|
||||||
|
* When you work with your strategy & hyperopt file you should use a proper code editor like VSCode or PyCharm. A good code editor will provide syntax highlighting as well as line numbers, making it easy to find syntax errors (most likely pointed out by Freqtrade during startup).
|
||||||
|
|
||||||
## Freqtrade common issues
|
## Freqtrade common issues
|
||||||
|
|
||||||
### The bot does not start
|
### The bot does not start
|
||||||
|
|
||||||
Running the bot with `freqtrade trade --config config.json` does show the output `freqtrade: command not found`.
|
Running the bot with `freqtrade trade --config config.json` shows the output `freqtrade: command not found`.
|
||||||
|
|
||||||
This could have the following reasons:
|
This could be caused by the following reasons:
|
||||||
|
|
||||||
* The virtual environment is not active
|
* The virtual environment is not active.
|
||||||
* run `source .env/bin/activate` to activate the virtual environment
|
* Run `source .env/bin/activate` to activate the virtual environment.
|
||||||
* The installation did not work correctly.
|
* The installation did not work correctly.
|
||||||
* Please check the [Installation documentation](installation.md).
|
* Please check the [Installation documentation](installation.md).
|
||||||
|
|
||||||
### I have waited 5 minutes, why hasn't the bot made any trades yet?!
|
### I have waited 5 minutes, why hasn't the bot made any trades yet?
|
||||||
|
|
||||||
Depending on the buy strategy, the amount of whitelisted coins, the
|
* Depending on the buy strategy, the amount of whitelisted coins, the
|
||||||
situation of the market etc, it can take up to hours to find good entry
|
situation of the market etc, it can take up to hours to find a good entry
|
||||||
position for a trade. Be patient!
|
position for a trade. Be patient!
|
||||||
|
|
||||||
### I have made 12 trades already, why is my total profit negative?!
|
* It may be because of a configuration error. It's best to check the logs, they usually tell you if the bot is simply not getting buy signals (only heartbeat messages), or if there is something wrong (errors / exceptions in the log).
|
||||||
|
|
||||||
|
### I have made 12 trades already, why is my total profit negative?
|
||||||
|
|
||||||
I understand your disappointment but unfortunately 12 trades is just
|
I understand your disappointment but unfortunately 12 trades is just
|
||||||
not enough to say anything. If you run backtesting, you can see that our
|
not enough to say anything. If you run backtesting, you can see that our
|
||||||
@ -30,11 +36,9 @@ of course constantly aim to improve the bot but it will _always_ be a
|
|||||||
gamble, which should leave you with modest wins on monthly basis but
|
gamble, which should leave you with modest wins on monthly basis but
|
||||||
you can't say much from few trades.
|
you can't say much from few trades.
|
||||||
|
|
||||||
### I’d like to change the stake amount. Can I just stop the bot with /stop and then change the config.json and run it again?
|
### I’d like to make changes to the config. Can I do that without having to kill the bot?
|
||||||
|
|
||||||
Not quite. Trades are persisted to a database but the configuration is
|
Yes. You can edit your config, use the `/stop` command in Telegram, followed by `/reload_config` and the bot will run with the new config.
|
||||||
currently only read when the bot is killed and restarted. `/stop` more
|
|
||||||
like pauses. You can stop your bot, adjust settings and start it again.
|
|
||||||
|
|
||||||
### I want to improve the bot with a new strategy
|
### I want to improve the bot with a new strategy
|
||||||
|
|
||||||
@ -43,7 +47,21 @@ the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-c
|
|||||||
|
|
||||||
### 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 `/forcesell all` command from Telegram.
|
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forcesell all` (sell all open trades).
|
||||||
|
|
||||||
|
### I want to run multiple bots on the same machine
|
||||||
|
|
||||||
|
Please look at the [advanced setup documentation Page](advanced-setup.md#running-multiple-instances-of-freqtrade).
|
||||||
|
|
||||||
|
### I'm getting "Missing data fillup" messages in the log
|
||||||
|
|
||||||
|
This message is just a warning that the latest candles had missing candles in them.
|
||||||
|
Depending on the exchange, this can indicate that the pair didn't have a trade for the timeframe you are using - and the exchange does only return candles with volume.
|
||||||
|
On low volume pairs, this is a rather common occurrence.
|
||||||
|
|
||||||
|
If this happens for all pairs in the pairlist, this might indicate a recent exchange downtime. Please check your exchange's public channels for details.
|
||||||
|
|
||||||
|
Irrespectively of the reason, Freqtrade will fill up these candles with "empty" candles, where open, high, low and close are set to the previous candle close - and volume is empty. In a chart, this will look like a `_` - and is aligned with how exchanges usually represent 0 volume candles.
|
||||||
|
|
||||||
### I'm getting the "RESTRICTED_MARKET" message in the log
|
### I'm getting the "RESTRICTED_MARKET" message in the log
|
||||||
|
|
||||||
@ -53,7 +71,7 @@ Read [the Bittrex section about restricted markets](exchanges.md#restricted-mark
|
|||||||
|
|
||||||
### I'm getting the "Exchange Bittrex does not support market orders." message and cannot run my strategy
|
### I'm getting the "Exchange Bittrex does not support market orders." message and cannot run my strategy
|
||||||
|
|
||||||
As the message says, Bittrex does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Probably your strategy was written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).
|
As the message says, Bittrex does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Your strategy was probably written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).
|
||||||
|
|
||||||
To fix it for Bittrex, redefine order types in the strategy to use "limit" instead of "market":
|
To fix it for Bittrex, redefine order types in the strategy to use "limit" instead of "market":
|
||||||
|
|
||||||
@ -65,11 +83,11 @@ To fix it for Bittrex, redefine order types in the strategy to use "limit" inste
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Same fix should be done in the configuration file, if order types are defined in your custom config rather than in the strategy.
|
The same fix should be applied in the configuration file, if order types are defined in your custom config rather than in the strategy.
|
||||||
|
|
||||||
### How do I search the bot logs for something?
|
### How do I search the bot logs for something?
|
||||||
|
|
||||||
By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility subcommands, as well as from the output of your custom `print()`'s you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout.
|
By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility sub-commands, as well as from the output of your custom `print()`'s you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout.
|
||||||
|
|
||||||
* In unix shells, this normally can be done as simple as:
|
* In unix shells, this normally can be done as simple as:
|
||||||
```shell
|
```shell
|
||||||
@ -94,7 +112,7 @@ and then grep it as:
|
|||||||
```shell
|
```shell
|
||||||
$ cat /path/to/mylogfile.log | grep 'something'
|
$ cat /path/to/mylogfile.log | grep 'something'
|
||||||
```
|
```
|
||||||
or even on the fly, as the bot works and the logfile grows:
|
or even on the fly, as the bot works and the log file grows:
|
||||||
```shell
|
```shell
|
||||||
$ tail -f /path/to/mylogfile.log | grep 'something'
|
$ tail -f /path/to/mylogfile.log | grep 'something'
|
||||||
```
|
```
|
||||||
@ -107,43 +125,46 @@ On Windows, the `--logfile` option is also supported by Freqtrade and you can us
|
|||||||
|
|
||||||
## Hyperopt module
|
## Hyperopt module
|
||||||
|
|
||||||
### How many epoch do I need to get a good Hyperopt result?
|
### How many epochs do I need to get a good Hyperopt result?
|
||||||
|
|
||||||
Per default Hyperopt called without the `-e`/`--epochs` command line option will only
|
Per default Hyperopt called without the `-e`/`--epochs` command line option will only
|
||||||
run 100 epochs, means 100 evals of your triggers, guards, ... Too few
|
run 100 epochs, means 100 evaluations of your triggers, guards, ... Too few
|
||||||
to find a great result (unless if you are very lucky), so you probably
|
to find a great result (unless if you are very lucky), so you probably
|
||||||
have to run it for 10.000 or more. But it will take an eternity to
|
have to run it for 10.000 or more. But it will take an eternity to
|
||||||
compute.
|
compute.
|
||||||
|
|
||||||
We recommend you to run it at least 10.000 epochs:
|
Since hyperopt uses Bayesian search, running for too many epochs may not produce greater results.
|
||||||
|
|
||||||
|
It's therefore recommended to run between 500-1000 epochs over and over until you hit at least 10.000 epochs in total (or are satisfied with the result). You can best judge by looking at the results - if the bot keeps discovering better strategies, it's best to keep on going.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade hyperopt -e 10000
|
freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy SampleStrategy -e 1000
|
||||||
```
|
```
|
||||||
|
|
||||||
or if you want intermediate result to see
|
### Why does it take a long time to run hyperopt?
|
||||||
|
|
||||||
```bash
|
* Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/zt-jaut7r4m-Y17k4x5mcQES9a9swKuxbg) - or the Freqtrade [discord community](https://discord.gg/X89cVG). While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you.
|
||||||
for i in {1..100}; do freqtrade hyperopt -e 100; done
|
|
||||||
```
|
|
||||||
|
|
||||||
### Why it is so long to run hyperopt?
|
* If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers:
|
||||||
|
|
||||||
Finding a great Hyperopt results takes time.
|
This answer was written during the release 0.15.1, when we had:
|
||||||
|
|
||||||
If you wonder why it takes a while to find great hyperopt results
|
* 8 triggers
|
||||||
|
* 9 guards: let's say we evaluate even 10 values from each
|
||||||
This answer was written during the under the release 0.15.1, when we had:
|
* 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
|
||||||
|
|
||||||
- 8 triggers
|
|
||||||
- 9 guards: let's say we evaluate even 10 values from each
|
|
||||||
- 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
|
|
||||||
|
|
||||||
The following calculation is still very rough and not very precise
|
The following calculation is still very rough and not very precise
|
||||||
but it will give the idea. With only these triggers and guards there is
|
but it will give the idea. With only these triggers and guards there is
|
||||||
already 8\*10^9\*10 evaluations. A roughly total of 80 billion evals.
|
already 8\*10^9\*10 evaluations. A roughly total of 80 billion evaluations.
|
||||||
Did you run 100 000 evals? Congrats, you've done roughly 1 / 100 000 th
|
Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th
|
||||||
of the search space.
|
of the search space, assuming that the bot never tests the same parameters more than once.
|
||||||
|
|
||||||
|
* The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 10.0000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
|
||||||
|
|
||||||
|
Example: 4% profit 650 times vs 0,3% profit a trade 10.000 times in a year. If we assume you set the --timerange to 365 days.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
`freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601`
|
||||||
|
|
||||||
## Edge module
|
## Edge module
|
||||||
|
|
||||||
@ -151,7 +172,7 @@ of the search space.
|
|||||||
|
|
||||||
The Edge module is mostly a result of brainstorming of [@mishaker](https://github.com/mishaker) and [@creslinux](https://github.com/creslinux) freqtrade team members.
|
The Edge module is mostly a result of brainstorming of [@mishaker](https://github.com/mishaker) and [@creslinux](https://github.com/creslinux) freqtrade team members.
|
||||||
|
|
||||||
You can find further info on expectancy, winrate, risk management and position size in the following sources:
|
You can find further info on expectancy, win rate, risk management and position size in the following sources:
|
||||||
|
|
||||||
- https://www.tradeciety.com/ultimate-math-guide-for-traders/
|
- https://www.tradeciety.com/ultimate-math-guide-for-traders/
|
||||||
- http://www.vantharp.com/tharp-concepts/expectancy.asp
|
- http://www.vantharp.com/tharp-concepts/expectancy.asp
|
||||||
|
150
docs/hyperopt.md
150
docs/hyperopt.md
@ -37,12 +37,20 @@ pip install -r requirements-hyperopt.txt
|
|||||||
Before we start digging into Hyperopt, we recommend you to take a look at
|
Before we start digging into Hyperopt, we recommend you to take a look at
|
||||||
the sample hyperopt file located in [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt.py).
|
the sample hyperopt file located in [user_data/hyperopts/](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt.py).
|
||||||
|
|
||||||
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
|
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar.
|
||||||
|
|
||||||
The simplest way to get started is to use `freqtrade new-hyperopt --hyperopt AwesomeHyperopt`.
|
!!! Tip "About this page"
|
||||||
This will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
|
For this page, we will be using a fictional strategy called `AwesomeStrategy` - which will be optimized using the `AwesomeHyperopt` class.
|
||||||
|
|
||||||
### Checklist on all tasks / possibilities in hyperopt
|
The simplest way to get started is to use the following, command, which will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
freqtrade new-hyperopt --hyperopt AwesomeHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
|
### Hyperopt checklist
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
@ -54,17 +62,15 @@ Depending on the space you want to optimize, only some of the below are required
|
|||||||
!!! Note
|
!!! Note
|
||||||
`populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
|
`populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
|
||||||
|
|
||||||
Optional - can also be loaded from a strategy:
|
Optional in hyperopt - can also be loaded from a strategy (recommended):
|
||||||
|
|
||||||
* copy `populate_indicators` from your strategy - otherwise default-strategy will be used
|
* `populate_indicators` - fallback to create indicators
|
||||||
* copy `populate_buy_trend` from your strategy - otherwise default-strategy will be used
|
* `populate_buy_trend` - fallback if not optimizing for buy space. should come from strategy
|
||||||
* copy `populate_sell_trend` from your strategy - otherwise default-strategy will be used
|
* `populate_sell_trend` - fallback if not optimizing for sell space. should come from strategy
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
|
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods.
|
You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods.
|
||||||
|
Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
|
||||||
|
|
||||||
Rarely you may also need to override:
|
Rarely you may also need to override:
|
||||||
|
|
||||||
@ -80,36 +86,41 @@ Rarely you may also need to override:
|
|||||||
# Have a working strategy at hand.
|
# Have a working strategy at hand.
|
||||||
freqtrade new-hyperopt --hyperopt EmptyHyperopt
|
freqtrade new-hyperopt --hyperopt EmptyHyperopt
|
||||||
|
|
||||||
freqtrade hyperopt --hyperopt EmptyHyperopt --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
|
freqtrade hyperopt --hyperopt EmptyHyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
|
||||||
```
|
```
|
||||||
|
|
||||||
### 1. Install a Custom Hyperopt File
|
### Create a Custom Hyperopt File
|
||||||
|
|
||||||
Put your hyperopt file into the directory `user_data/hyperopts`.
|
Let assume you want a hyperopt file `AwesomeHyperopt.py`:
|
||||||
|
|
||||||
Let assume you want a hyperopt file `awesome_hyperopt.py`:
|
``` bash
|
||||||
Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts/awesome_hyperopt.py`
|
freqtrade new-hyperopt --hyperopt AwesomeHyperopt
|
||||||
|
```
|
||||||
|
|
||||||
### 2. Configure your Guards and Triggers
|
This command will create a new hyperopt file from a template, allowing you to get started quickly.
|
||||||
|
|
||||||
|
### Configure your Guards and Triggers
|
||||||
|
|
||||||
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
|
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
|
||||||
|
|
||||||
* Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
* Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||||
* Inside `populate_buy_trend()` - applying the parameters.
|
* Within `buy_strategy_generator()` - populate the nested `populate_buy_trend()` to apply the parameters.
|
||||||
|
|
||||||
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`.
|
||||||
|
|
||||||
1. Guards are conditions like "never buy if ADX < 10", or never buy if current price is over EMA10.
|
1. Guards are conditions like "never buy if ADX < 10", or never buy if current price is over EMA10.
|
||||||
2. Triggers are ones that actually trigger buy in specific moment, like "buy when EMA5 crosses over EMA10" or "buy when close price touches lower Bollinger band".
|
2. Triggers are ones that actually trigger buy in specific moment, like "buy when EMA5 crosses over EMA10" or "buy when close price touches lower Bollinger band".
|
||||||
|
|
||||||
Hyperoptimization will, for each eval round, pick one trigger and possibly
|
!!! Hint "Guards and Triggers"
|
||||||
multiple guards. The constructed strategy will be something like
|
Technically, there is no difference between Guards and Triggers.
|
||||||
"*buy exactly when close price touches lower Bollinger band, BUT only if
|
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).
|
||||||
|
|
||||||
|
Hyper-optimization will, for each epoch round, pick one trigger and possibly
|
||||||
|
multiple guards. The constructed strategy will be something like "*buy exactly when close price touches lower Bollinger band, BUT only if
|
||||||
ADX > 10*".
|
ADX > 10*".
|
||||||
|
|
||||||
If you have updated the buy strategy, i.e. changed the contents of
|
If you have updated the buy strategy, i.e. changed the contents of `populate_buy_trend()` method, you have to update the `guards` and `triggers` your hyperopt must use correspondingly.
|
||||||
`populate_buy_trend()` method, you have to update the `guards` and
|
|
||||||
`triggers` your hyperopt must use correspondingly.
|
|
||||||
|
|
||||||
#### Sell optimization
|
#### Sell optimization
|
||||||
|
|
||||||
@ -117,16 +128,16 @@ Similar to the buy-signal above, sell-signals can also be optimized.
|
|||||||
Place the corresponding settings into the following methods
|
Place the corresponding settings into the following methods
|
||||||
|
|
||||||
* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
|
* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||||
* Inside `populate_sell_trend()` - applying the parameters.
|
* Within `sell_strategy_generator()` - populate the nested method `populate_sell_trend()` to apply the parameters.
|
||||||
|
|
||||||
The configuration and rules are the same than for buy signals.
|
The configuration and rules are the same than for buy signals.
|
||||||
To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
|
To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
|
||||||
|
|
||||||
#### Using timeframe as a part of the Strategy
|
#### Using timeframe as a part of the Strategy
|
||||||
|
|
||||||
The Strategy class exposes the timeframe (ticker interval) value as the `self.ticker_interval` attribute.
|
The Strategy class exposes the timeframe value as the `self.timeframe` attribute.
|
||||||
The same value is available as class-attribute `HyperoptName.ticker_interval`.
|
The same value is available as class-attribute `HyperoptName.timeframe`.
|
||||||
In the case of the linked sample-value this would be `SampleHyperOpt.ticker_interval`.
|
In the case of the linked sample-value this would be `AwesomeHyperopt.timeframe`.
|
||||||
|
|
||||||
## Solving a Mystery
|
## Solving a Mystery
|
||||||
|
|
||||||
@ -154,7 +165,7 @@ We will start by defining a search space:
|
|||||||
|
|
||||||
Above definition says: I have five parameters I want you to randomly combine
|
Above definition says: I have five parameters I want you to randomly combine
|
||||||
to find the best combination. Two of them are integer values (`adx-value`
|
to find the best combination. Two of them are integer values (`adx-value`
|
||||||
and `rsi-value`) and I want you test in the range of values 20 to 40.
|
and `rsi-value`) and I want you test in the range of values 20 to 40.
|
||||||
Then we have three category variables. First two are either `True` or `False`.
|
Then we have three category variables. First two are either `True` or `False`.
|
||||||
We use these to either enable or disable the ADX and RSI guards. The last
|
We use these to either enable or disable the ADX and RSI guards. The last
|
||||||
one we call `trigger` and use it to decide which buy trigger we want to use.
|
one we call `trigger` and use it to decide which buy trigger we want to use.
|
||||||
@ -162,6 +173,11 @@ one we call `trigger` and use it to decide which buy trigger we want to use.
|
|||||||
So let's write the buy strategy using these values:
|
So let's write the buy strategy using these values:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
@staticmethod
|
||||||
|
def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
|
||||||
|
"""
|
||||||
|
Define the buy strategy parameters to be used by Hyperopt.
|
||||||
|
"""
|
||||||
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
def populate_buy_trend(dataframe: DataFrame) -> DataFrame:
|
||||||
conditions = []
|
conditions = []
|
||||||
# GUARDS AND TRENDS
|
# GUARDS AND TRENDS
|
||||||
@ -192,27 +208,25 @@ So let's write the buy strategy using these values:
|
|||||||
return populate_buy_trend
|
return populate_buy_trend
|
||||||
```
|
```
|
||||||
|
|
||||||
Hyperopting will now call this `populate_buy_trend` as many times you ask it (`epochs`)
|
Hyperopt will now call `populate_buy_trend()` many times (`epochs`) with different value combinations.
|
||||||
with different value combinations. It will then use the given historical data and make
|
It will use the given historical data and make buys based on the buy signals generated with the above function.
|
||||||
buys based on the buy signals generated with the above function and based on the results
|
Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured [loss function](#loss-functions)).
|
||||||
it will end with telling you which parameter combination produced the best profits.
|
|
||||||
|
|
||||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
!!! Note
|
||||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||||
add it to the `populate_indicators()` method in your custom hyperopt file.
|
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||||
|
add it to the `populate_indicators()` method in your strategy or hyperopt file.
|
||||||
|
|
||||||
## Loss-functions
|
## Loss-functions
|
||||||
|
|
||||||
Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results.
|
Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results.
|
||||||
|
|
||||||
By default, Freqtrade uses a loss function, which has been with freqtrade since the beginning and optimizes mostly for short trade duration and avoiding losses.
|
A loss function must be specified via the `--hyperopt-loss <Class-name>` argument (or optionally via the configuration under the `"hyperopt_loss"` key).
|
||||||
|
|
||||||
A different loss function can be specified by using the `--hyperopt-loss <Class-name>` argument.
|
|
||||||
This class should be in its own file within the `user_data/hyperopts/` directory.
|
This class should be in its own file within the `user_data/hyperopts/` directory.
|
||||||
|
|
||||||
Currently, the following loss functions are builtin:
|
Currently, the following loss functions are builtin:
|
||||||
|
|
||||||
* `DefaultHyperOptLoss` (default legacy Freqtrade hyperoptimization loss function)
|
* `ShortTradeDurHyperOptLoss` (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses.
|
||||||
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
||||||
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation)
|
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation)
|
||||||
* `SharpeHyperOptLossDaily` (optimizes Sharpe Ratio calculated on **daily** trade returns relative to standard deviation)
|
* `SharpeHyperOptLossDaily` (optimizes Sharpe Ratio calculated on **daily** trade returns relative to standard deviation)
|
||||||
@ -229,21 +243,20 @@ Because hyperopt tries a lot of combinations to find the best parameters it will
|
|||||||
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> -e 5000 --spaces all
|
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
Use `<hyperoptname>` as the name of the custom hyperopt used.
|
||||||
|
|
||||||
The `-e` option will set how many evaluations hyperopt will do. We recommend
|
The `-e` option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs.
|
||||||
running at least several thousand evaluations.
|
Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results.
|
||||||
|
|
||||||
The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
|
The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using `--continue`.
|
Hyperopt will store hyperopt results with the timestamp of the hyperopt start time.
|
||||||
|
Reading commands (`hyperopt-list`, `hyperopt-show`) can use `--hyperopt-filename <filename>` to read and display older hyperopt results.
|
||||||
!!! Warning
|
You can find a list of filenames with `ls -l user_data/hyperopt_results/`.
|
||||||
When switching parameters or changing configuration options, make sure to not use the argument `--continue` so temporary results can be removed.
|
|
||||||
|
|
||||||
### Execute Hyperopt with different historical data source
|
### Execute Hyperopt with different historical data source
|
||||||
|
|
||||||
@ -251,13 +264,13 @@ If you would like to hyperopt parameters using an alternate historical data set
|
|||||||
you have on-disk, use the `--datadir PATH` option. By default, hyperopt
|
you have on-disk, use the `--datadir PATH` option. By default, hyperopt
|
||||||
uses data from directory `user_data/data`.
|
uses data from directory `user_data/data`.
|
||||||
|
|
||||||
### Running Hyperopt with Smaller Testset
|
### Running Hyperopt with a smaller test-set
|
||||||
|
|
||||||
Use the `--timerange` argument to change how much of the testset you want to use.
|
Use the `--timerange` argument to change how much of the test-set you want to use.
|
||||||
For example, to use one month of data, pass the following parameter to the hyperopt call:
|
For example, to use one month of data, pass the following parameter to the hyperopt call:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade hyperopt --timerange 20180401-20180501
|
freqtrade hyperopt --hyperopt <hyperoptname> --strategy <strategyname> --timerange 20180401-20180501
|
||||||
```
|
```
|
||||||
|
|
||||||
### Running Hyperopt using methods from a strategy
|
### Running Hyperopt using methods from a strategy
|
||||||
@ -265,16 +278,15 @@ freqtrade hyperopt --timerange 20180401-20180501
|
|||||||
Hyperopt can reuse `populate_indicators`, `populate_buy_trend`, `populate_sell_trend` from your strategy, assuming these methods are **not** in your custom hyperopt file, and a strategy is provided.
|
Hyperopt can reuse `populate_indicators`, `populate_buy_trend`, `populate_sell_trend` from your strategy, assuming these methods are **not** in your custom hyperopt file, and a strategy is provided.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade hyperopt --strategy SampleStrategy --customhyperopt SampleHyperopt
|
freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy
|
||||||
```
|
```
|
||||||
|
|
||||||
### Running Hyperopt with Smaller Search Space
|
### Running Hyperopt with Smaller Search Space
|
||||||
|
|
||||||
Use the `--spaces` option to limit the search space used by hyperopt.
|
Use the `--spaces` option to limit the search space used by hyperopt.
|
||||||
Letting Hyperopt optimize everything is a huuuuge search space. Often it
|
Letting Hyperopt optimize everything is a huuuuge search space.
|
||||||
might make more sense to start by just searching for initial buy algorithm.
|
Often it might make more sense to start by just searching for initial buy algorithm.
|
||||||
Or maybe you just want to optimize your stoploss or roi table for that awesome
|
Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have.
|
||||||
new buy strategy you have.
|
|
||||||
|
|
||||||
Legal values are:
|
Legal values are:
|
||||||
|
|
||||||
@ -318,7 +330,7 @@ The initial state for generation of these random values (random state) is contro
|
|||||||
|
|
||||||
If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the `--random-state` command line option to repeat the set of the initial random epochs used.
|
If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the `--random-state` command line option to repeat the set of the initial random epochs used.
|
||||||
|
|
||||||
If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyperoptimization results with same random state value used.
|
If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyper-optimization results with same random state value used.
|
||||||
|
|
||||||
## Understand the Hyperopt Result
|
## Understand the Hyperopt Result
|
||||||
|
|
||||||
@ -370,6 +382,9 @@ By default, hyperopt prints colorized results -- epochs with positive profit are
|
|||||||
|
|
||||||
You can use the `--print-all` command line option if you would like to see all results in the hyperopt output, not only the best ones. When `--print-all` is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the `--no-color` command line option.
|
You can use the `--print-all` command line option if you would like to see all results in the hyperopt output, not only the best ones. When `--print-all` is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the `--no-color` command line option.
|
||||||
|
|
||||||
|
!!! Note "Windows and color output"
|
||||||
|
Windows does not support color-output natively, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL.
|
||||||
|
|
||||||
### Understand Hyperopt ROI results
|
### Understand Hyperopt ROI results
|
||||||
|
|
||||||
If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table:
|
If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table:
|
||||||
@ -403,7 +418,7 @@ As stated in the comment, you can also use it as the value of the `minimal_roi`
|
|||||||
|
|
||||||
#### Default ROI Search Space
|
#### Default ROI Search Space
|
||||||
|
|
||||||
If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the ticker_interval used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 5 digits after the decimal point):
|
If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the timeframe used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 5 digits after the decimal point):
|
||||||
|
|
||||||
| # step | 1m | | 5m | | 1h | | 1d | |
|
| # step | 1m | | 5m | | 1h | | 1d | |
|
||||||
| ------ | ------ | ----------------- | -------- | ----------- | ---------- | ----------------- | ------------ | ----------------- |
|
| ------ | ------ | ----------------- | -------- | ----------- | ---------- | ----------------- | ------------ | ----------------- |
|
||||||
@ -412,11 +427,13 @@ If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace f
|
|||||||
| 3 | 4...20 | 0.00387...0.01547 | 20...100 | 0.01...0.04 | 240...1200 | 0.02294...0.09177 | 5760...28800 | 0.04059...0.16237 |
|
| 3 | 4...20 | 0.00387...0.01547 | 20...100 | 0.01...0.04 | 240...1200 | 0.02294...0.09177 | 5760...28800 | 0.04059...0.16237 |
|
||||||
| 4 | 6...44 | 0.0 | 30...220 | 0.0 | 360...2640 | 0.0 | 8640...63360 | 0.0 |
|
| 4 | 6...44 | 0.0 | 30...220 | 0.0 | 360...2640 | 0.0 | 8640...63360 | 0.0 |
|
||||||
|
|
||||||
These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe (ticker interval) used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used.
|
These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used.
|
||||||
|
|
||||||
If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
|
If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
|
||||||
|
|
||||||
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
|
Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps).
|
||||||
|
|
||||||
|
A sample for these methods can be found in [sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
|
||||||
|
|
||||||
### Understand Hyperopt Stoploss results
|
### Understand Hyperopt Stoploss results
|
||||||
|
|
||||||
@ -438,7 +455,7 @@ Stoploss: -0.27996
|
|||||||
|
|
||||||
In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the `stoploss` attribute of your custom strategy:
|
In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the `stoploss` attribute of your custom strategy:
|
||||||
|
|
||||||
```
|
``` python
|
||||||
# Optimal stoploss designed for the strategy
|
# Optimal stoploss designed for the strategy
|
||||||
# This attribute will be overridden if the config file contains "stoploss"
|
# This attribute will be overridden if the config file contains "stoploss"
|
||||||
stoploss = -0.27996
|
stoploss = -0.27996
|
||||||
@ -472,7 +489,7 @@ Trailing stop:
|
|||||||
|
|
||||||
In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:
|
In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:
|
||||||
|
|
||||||
```
|
``` python
|
||||||
# Trailing stop
|
# Trailing stop
|
||||||
# These attributes will be overridden if the config file contains corresponding values.
|
# These attributes will be overridden if the config file contains corresponding values.
|
||||||
trailing_stop = True
|
trailing_stop = True
|
||||||
@ -491,15 +508,14 @@ Override the `trailing_space()` method and define the desired range in it if you
|
|||||||
|
|
||||||
## Show details of Hyperopt results
|
## Show details of Hyperopt results
|
||||||
|
|
||||||
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` subcommands. The usage of these subcommands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
|
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` sub-commands. The usage of these sub-commands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
|
||||||
|
|
||||||
## Validate backtesting results
|
## Validate backtesting results
|
||||||
|
|
||||||
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
|
||||||
|
|
||||||
To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same set of arguments `--dmmp`/`--disable-max-market-positions` and `--eps`/`--enable-position-stacking` for Backtesting.
|
To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt `--dmmp`/`--disable-max-market-positions` and `--eps`/`--enable-position-stacking` for Backtesting.
|
||||||
|
|
||||||
## Next Step
|
Should results don't match, please double-check to make sure you transferred all conditions correctly.
|
||||||
|
Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy.
|
||||||
Now you have a perfect bot and want to control it from Telegram. Your
|
You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like `stoploss` or `trailing_stop`).
|
||||||
next step is to learn the [Telegram usage](telegram-usage.md).
|
|
||||||
|
186
docs/includes/pairlists.md
Normal file
186
docs/includes/pairlists.md
Normal file
@ -0,0 +1,186 @@
|
|||||||
|
## Pairlists and Pairlist Handlers
|
||||||
|
|
||||||
|
Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the `pairlists` section of the configuration settings.
|
||||||
|
|
||||||
|
In your configuration, you can use Static Pairlist (defined by the [`StaticPairList`](#static-pair-list) Pairlist Handler) and Dynamic Pairlist (defined by the [`VolumePairList`](#volume-pair-list) Pairlist Handler).
|
||||||
|
|
||||||
|
Additionally, [`AgeFilter`](#agefilter), [`PrecisionFilter`](#precisionfilter), [`PriceFilter`](#pricefilter), [`ShuffleFilter`](#shufflefilter) and [`SpreadFilter`](#spreadfilter) act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.
|
||||||
|
|
||||||
|
If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either `StaticPairList` or `VolumePairList` as the starting Pairlist Handler.
|
||||||
|
|
||||||
|
Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the `pair_blacklist` configuration setting) are also always removed from the resulting pairlist.
|
||||||
|
|
||||||
|
### Available Pairlist Handlers
|
||||||
|
|
||||||
|
* [`StaticPairList`](#static-pair-list) (default, if not configured differently)
|
||||||
|
* [`VolumePairList`](#volume-pair-list)
|
||||||
|
* [`AgeFilter`](#agefilter)
|
||||||
|
* [`PerformanceFilter`](#performancefilter)
|
||||||
|
* [`PrecisionFilter`](#precisionfilter)
|
||||||
|
* [`PriceFilter`](#pricefilter)
|
||||||
|
* [`ShuffleFilter`](#shufflefilter)
|
||||||
|
* [`SpreadFilter`](#spreadfilter)
|
||||||
|
* [`RangeStabilityFilter`](#rangestabilityfilter)
|
||||||
|
|
||||||
|
!!! Tip "Testing pairlists"
|
||||||
|
Pairlist configurations can be quite tricky to get right. Best use the [`test-pairlist`](utils.md#test-pairlist) utility sub-command to test your configuration quickly.
|
||||||
|
|
||||||
|
#### Static Pair List
|
||||||
|
|
||||||
|
By default, the `StaticPairList` method is used, which uses a statically defined pair whitelist from the configuration.
|
||||||
|
|
||||||
|
It uses configuration from `exchange.pair_whitelist` and `exchange.pair_blacklist`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [
|
||||||
|
{"method": "StaticPairList"}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, only currently enabled pairs are allowed.
|
||||||
|
To skip pair validation against active markets, set `"allow_inactive": true` within the `StaticPairList` configuration.
|
||||||
|
This can be useful for backtesting expired pairs (like quarterly spot-markets).
|
||||||
|
This option must be configured along with `exchange.skip_pair_validation` in the exchange configuration.
|
||||||
|
|
||||||
|
#### Volume Pair List
|
||||||
|
|
||||||
|
`VolumePairList` employs sorting/filtering of pairs by their trading volume. It selects `number_assets` top pairs with sorting based on the `sort_key` (which can only be `quoteVolume`).
|
||||||
|
|
||||||
|
When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), `VolumePairList` considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.
|
||||||
|
|
||||||
|
When used on the leading position of the chain of Pairlist Handlers, it does not consider `pair_whitelist` configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
|
||||||
|
|
||||||
|
The `refresh_period` setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
|
||||||
|
|
||||||
|
`VolumePairList` is based on the ticker data from exchange, as reported by the ccxt library:
|
||||||
|
|
||||||
|
* The `quoteVolume` is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [{
|
||||||
|
"method": "VolumePairList",
|
||||||
|
"number_assets": 20,
|
||||||
|
"sort_key": "quoteVolume",
|
||||||
|
"refresh_period": 1800
|
||||||
|
}],
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
`VolumePairList` does not support backtesting mode.
|
||||||
|
|
||||||
|
#### AgeFilter
|
||||||
|
|
||||||
|
Removes pairs that have been listed on the exchange for less than `min_days_listed` days (defaults to `10`).
|
||||||
|
|
||||||
|
When pairs are first listed on an exchange they can suffer huge price drops and volatility
|
||||||
|
in the first few days while the pair goes through its price-discovery period. Bots can often
|
||||||
|
be caught out buying before the pair has finished dropping in price.
|
||||||
|
|
||||||
|
This filter allows freqtrade to ignore pairs until they have been listed for at least `min_days_listed` days.
|
||||||
|
|
||||||
|
#### PerformanceFilter
|
||||||
|
|
||||||
|
Sorts pairs by past trade performance, as follows:
|
||||||
|
1. Positive performance.
|
||||||
|
2. No closed trades yet.
|
||||||
|
3. Negative performance.
|
||||||
|
|
||||||
|
Trade count is used as a tie breaker.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
`PerformanceFilter` does not support backtesting mode.
|
||||||
|
|
||||||
|
#### PrecisionFilter
|
||||||
|
|
||||||
|
Filters low-value coins which would not allow setting stoplosses.
|
||||||
|
|
||||||
|
#### PriceFilter
|
||||||
|
|
||||||
|
The `PriceFilter` allows filtering of pairs by price. Currently the following price filters are supported:
|
||||||
|
|
||||||
|
* `min_price`
|
||||||
|
* `max_price`
|
||||||
|
* `low_price_ratio`
|
||||||
|
|
||||||
|
The `min_price` setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs.
|
||||||
|
This option is disabled by default, and will only apply if set to > 0.
|
||||||
|
|
||||||
|
The `max_price` setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs.
|
||||||
|
This option is disabled by default, and will only apply if set to > 0.
|
||||||
|
|
||||||
|
The `low_price_ratio` setting removes pairs where a raise of 1 price unit (pip) is above the `low_price_ratio` ratio.
|
||||||
|
This option is disabled by default, and will only apply if set to > 0.
|
||||||
|
|
||||||
|
For `PriceFiler` at least one of its `min_price`, `max_price` or `low_price_ratio` settings must be applied.
|
||||||
|
|
||||||
|
Calculation example:
|
||||||
|
|
||||||
|
Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with `low_price_ratio` set to 0.09 (9%) or with `min_price` set to 0.00000011, correspondingly.
|
||||||
|
|
||||||
|
!!! Warning "Low priced pairs"
|
||||||
|
Low priced pairs with high "1 pip movements" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.
|
||||||
|
|
||||||
|
#### ShuffleFilter
|
||||||
|
|
||||||
|
Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
You may set the `seed` value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If `seed` is not set, the pairs are shuffled in the non-repeatable random order.
|
||||||
|
|
||||||
|
#### SpreadFilter
|
||||||
|
|
||||||
|
Removes pairs that have a difference between asks and bids above the specified ratio, `max_spread_ratio` (defaults to `0.005`).
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
If `DOGE/BTC` maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: `1 - bid/ask ~= 0.037` which is `> 0.005` and this pair will be filtered out.
|
||||||
|
|
||||||
|
#### RangeStabilityFilter
|
||||||
|
|
||||||
|
Removes pairs where the difference between lowest low and highest high over `lookback_days` days is below `min_rate_of_change`. Since this is a filter that requires additional data, the results are cached for `refresh_period`.
|
||||||
|
|
||||||
|
In the below example:
|
||||||
|
If the trading range over the last 10 days is <1%, remove the pair from the whitelist.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"pairlists": [
|
||||||
|
{
|
||||||
|
"method": "RangeStabilityFilter",
|
||||||
|
"lookback_days": 10,
|
||||||
|
"min_rate_of_change": 0.01,
|
||||||
|
"refresh_period": 1440
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit.
|
||||||
|
|
||||||
|
### Full example of Pairlist Handlers
|
||||||
|
|
||||||
|
The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets, sorting pairs by `quoteVolume` and applies both [`PrecisionFilter`](#precisionfilter) and [`PriceFilter`](#price-filter), filtering all assets where 1 price unit is > 1%. Then the `SpreadFilter` is applied and pairs are finally shuffled with the random seed set to some predefined value.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"exchange": {
|
||||||
|
"pair_whitelist": [],
|
||||||
|
"pair_blacklist": ["BNB/BTC"]
|
||||||
|
},
|
||||||
|
"pairlists": [
|
||||||
|
{
|
||||||
|
"method": "VolumePairList",
|
||||||
|
"number_assets": 20,
|
||||||
|
"sort_key": "quoteVolume",
|
||||||
|
},
|
||||||
|
{"method": "AgeFilter", "min_days_listed": 10},
|
||||||
|
{"method": "PrecisionFilter"},
|
||||||
|
{"method": "PriceFilter", "low_price_ratio": 0.01},
|
||||||
|
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
|
||||||
|
{
|
||||||
|
"method": "RangeStabilityFilter",
|
||||||
|
"lookback_days": 10,
|
||||||
|
"min_rate_of_change": 0.01,
|
||||||
|
"refresh_period": 1440
|
||||||
|
},
|
||||||
|
{"method": "ShuffleFilter", "seed": 42}
|
||||||
|
],
|
||||||
|
```
|
169
docs/includes/protections.md
Normal file
169
docs/includes/protections.md
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
## Protections
|
||||||
|
|
||||||
|
!!! 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, Slack or via Github Issue.
|
||||||
|
|
||||||
|
Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs.
|
||||||
|
All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance.
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).
|
||||||
|
|
||||||
|
!!! Note "Backtesting"
|
||||||
|
Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the `--enable-protections` flag.
|
||||||
|
|
||||||
|
### Available Protections
|
||||||
|
|
||||||
|
* [`StoplossGuard`](#stoploss-guard) Stop trading if a certain amount of stoploss occurred within a certain time window.
|
||||||
|
* [`MaxDrawdown`](#maxdrawdown) Stop trading if max-drawdown is reached.
|
||||||
|
* [`LowProfitPairs`](#low-profit-pairs) Lock pairs with low profits
|
||||||
|
* [`CooldownPeriod`](#cooldown-period) Don't enter a trade right after selling a trade.
|
||||||
|
|
||||||
|
### Common settings to all Protections
|
||||||
|
|
||||||
|
| Parameter| Description |
|
||||||
|
|------------|-------------|
|
||||||
|
| `method` | Protection name to use. <br> **Datatype:** String, selected from [available Protections](#available-protections)
|
||||||
|
| `stop_duration_candles` | For how many candles should the lock be set? <br> **Datatype:** Positive integer (in candles)
|
||||||
|
| `stop_duration` | how many minutes should protections be locked. <br>Cannot be used together with `stop_duration_candles`. <br> **Datatype:** Float (in minutes)
|
||||||
|
| `lookback_period_candles` | Only trades that completed within the last `lookback_period_candles` candles will be considered. This setting may be ignored by some Protections. <br> **Datatype:** Positive integer (in candles).
|
||||||
|
| `lookback_period` | Only trades that completed after `current_time - lookback_period` will be considered. <br>Cannot be used together with `lookback_period_candles`. <br>This setting may be ignored by some Protections. <br> **Datatype:** Float (in minutes)
|
||||||
|
| `trade_limit` | Number of trades required at minimum (not used by all Protections). <br> **Datatype:** Positive integer
|
||||||
|
|
||||||
|
!!! Note "Durations"
|
||||||
|
Durations (`stop_duration*` and `lookback_period*` can be defined in either minutes or candles).
|
||||||
|
For more flexibility when testing different timeframes, all below examples will use the "candle" definition.
|
||||||
|
|
||||||
|
#### Stoploss Guard
|
||||||
|
|
||||||
|
`StoplossGuard` selects all trades within `lookback_period`, and determines if the amount of trades that resulted in stoploss are above `trade_limit` - in which case trading will stop for `stop_duration`.
|
||||||
|
This applies across all pairs, unless `only_per_pair` is set to true, which will then only look at one pair at a time.
|
||||||
|
|
||||||
|
The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"protections": [
|
||||||
|
{
|
||||||
|
"method": "StoplossGuard",
|
||||||
|
"lookback_period_candles": 24,
|
||||||
|
"trade_limit": 4,
|
||||||
|
"stop_duration_candles": 4,
|
||||||
|
"only_per_pair": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
`StoplossGuard` considers all trades with the results `"stop_loss"` and `"trailing_stop_loss"` if the resulting profit was negative.
|
||||||
|
`trade_limit` and `lookback_period` will need to be tuned for your strategy.
|
||||||
|
|
||||||
|
#### MaxDrawdown
|
||||||
|
|
||||||
|
`MaxDrawdown` uses all trades within `lookback_period` (in minutes) to determine the maximum drawdown. If the drawdown is below `max_allowed_drawdown`, trading will stop for `stop_duration` (in minutes) after the last trade - assuming that the bot needs some time to let markets recover.
|
||||||
|
|
||||||
|
The below sample stops trading for 12 candles if max-drawdown is > 20% considering all trades within the last 48 candles.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"protections": [
|
||||||
|
{
|
||||||
|
"method": "MaxDrawdown",
|
||||||
|
"lookback_period_candles": 48,
|
||||||
|
"trade_limit": 20,
|
||||||
|
"stop_duration_candles": 12,
|
||||||
|
"max_allowed_drawdown": 0.2
|
||||||
|
},
|
||||||
|
],
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Low Profit Pairs
|
||||||
|
|
||||||
|
`LowProfitPairs` uses all trades for a pair within `lookback_period` (in minutes) to determine the overall profit ratio.
|
||||||
|
If that ratio is below `required_profit`, that pair will be locked for `stop_duration` (in minutes).
|
||||||
|
|
||||||
|
The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"protections": [
|
||||||
|
{
|
||||||
|
"method": "LowProfitPairs",
|
||||||
|
"lookback_period_candles": 6,
|
||||||
|
"trade_limit": 2,
|
||||||
|
"stop_duration": 60,
|
||||||
|
"required_profit": 0.02
|
||||||
|
}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Cooldown Period
|
||||||
|
|
||||||
|
`CooldownPeriod` locks a pair for `stop_duration` (in minutes) after selling, avoiding a re-entry for this pair for `stop_duration` minutes.
|
||||||
|
|
||||||
|
The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to "cool down".
|
||||||
|
|
||||||
|
```json
|
||||||
|
"protections": [
|
||||||
|
{
|
||||||
|
"method": "CooldownPeriod",
|
||||||
|
"stop_duration_candles": 2
|
||||||
|
}
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This Protection applies only at pair-level, and will never lock all pairs globally.
|
||||||
|
This Protection does not consider `lookback_period` as it only looks at the latest trade.
|
||||||
|
|
||||||
|
### Full example of Protections
|
||||||
|
|
||||||
|
All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs.
|
||||||
|
All protections are evaluated in the sequence they are defined.
|
||||||
|
|
||||||
|
The below example assumes a timeframe of 1 hour:
|
||||||
|
|
||||||
|
* Locks each pair after selling for an additional 5 candles (`CooldownPeriod`), giving other pairs a chance to get filled.
|
||||||
|
* Stops trading for 4 hours (`4 * 1h candles`) if the last 2 days (`48 * 1h candles`) had 20 trades, which caused a max-drawdown of more than 20%. (`MaxDrawdown`).
|
||||||
|
* Stops trading if more than 4 stoploss occur for all pairs within a 1 day (`24 * 1h candles`) limit (`StoplossGuard`).
|
||||||
|
* Locks all pairs that had 4 Trades within the last 6 hours (`6 * 1h candles`) with a combined profit ratio of below 0.02 (<2%) (`LowProfitPairs`).
|
||||||
|
* Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (`24 * 1h candles`), a minimum of 4 trades.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"timeframe": "1h",
|
||||||
|
"protections": [
|
||||||
|
{
|
||||||
|
"method": "CooldownPeriod",
|
||||||
|
"stop_duration_candles": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "MaxDrawdown",
|
||||||
|
"lookback_period_candles": 48,
|
||||||
|
"trade_limit": 20,
|
||||||
|
"stop_duration_candles": 4,
|
||||||
|
"max_allowed_drawdown": 0.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "StoplossGuard",
|
||||||
|
"lookback_period_candles": 24,
|
||||||
|
"trade_limit": 4,
|
||||||
|
"stop_duration_candles": 2,
|
||||||
|
"only_per_pair": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "LowProfitPairs",
|
||||||
|
"lookback_period_candles": 6,
|
||||||
|
"trade_limit": 2,
|
||||||
|
"stop_duration_candles": 60,
|
||||||
|
"required_profit": 0.02
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "LowProfitPairs",
|
||||||
|
"lookback_period_candles": 24,
|
||||||
|
"trade_limit": 4,
|
||||||
|
"stop_duration_candles": 2,
|
||||||
|
"required_profit": 0.01
|
||||||
|
}
|
||||||
|
],
|
||||||
|
```
|
@ -8,13 +8,13 @@
|
|||||||
<!-- Place this tag where you want the button to render. -->
|
<!-- Place this tag where you want the button to render. -->
|
||||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork freqtrade/freqtrade on GitHub">Fork</a>
|
<a class="github-button" href="https://github.com/freqtrade/freqtrade/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork freqtrade/freqtrade on GitHub">Fork</a>
|
||||||
<!-- Place this tag where you want the button to render. -->
|
<!-- Place this tag where you want the button to render. -->
|
||||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/master.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a>
|
<a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/stable.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a>
|
||||||
<!-- Place this tag where you want the button to render. -->
|
<!-- Place this tag where you want the button to render. -->
|
||||||
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
|
|
||||||
Freqtrade is a crypto-currency algorithmic trading software developed in python (3.6+) and supported on Windows, macOS and Linux.
|
Freqtrade is a crypto-currency algorithmic trading software developed in python (3.7+) and supported on Windows, macOS and Linux.
|
||||||
|
|
||||||
!!! Danger "DISCLAIMER"
|
!!! Danger "DISCLAIMER"
|
||||||
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
||||||
@ -37,13 +37,9 @@ Freqtrade is a crypto-currency algorithmic trading software developed in python
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
### Up to date clock
|
|
||||||
|
|
||||||
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
|
|
||||||
|
|
||||||
### Hardware requirements
|
### Hardware requirements
|
||||||
|
|
||||||
To run this bot we recommend you a cloud instance with a minimum of:
|
To run this bot we recommend you a linux cloud instance with a minimum of:
|
||||||
|
|
||||||
- 2GB RAM
|
- 2GB RAM
|
||||||
- 1GB disk space
|
- 1GB disk space
|
||||||
@ -55,7 +51,7 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
|
|
||||||
Alternatively
|
Alternatively
|
||||||
|
|
||||||
- Python 3.6.x
|
- Python 3.7+
|
||||||
- pip (pip3)
|
- pip (pip3)
|
||||||
- git
|
- git
|
||||||
- TA-Lib
|
- TA-Lib
|
||||||
@ -63,11 +59,14 @@ Alternatively
|
|||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
### Help / Slack
|
### Help / Discord / Slack
|
||||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our passionate Slack community.
|
|
||||||
|
|
||||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) to join the Freqtrade Slack channel.
|
For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join our slack channel.
|
||||||
|
|
||||||
|
Please check out our [discord server](https://discord.gg/MA9v74M).
|
||||||
|
|
||||||
|
You can also join our [Slack channel](https://join.slack.com/t/highfrequencybot/shared_invite/zt-jaut7r4m-Y17k4x5mcQES9a9swKuxbg).
|
||||||
|
|
||||||
## Ready to try?
|
## Ready to try?
|
||||||
|
|
||||||
Begin by reading our installation guide [for docker](docker.md), or for [installation without docker](installation.md).
|
Begin by reading our installation guide [for docker](docker_quickstart.md) (recommended), or for [installation without docker](installation.md).
|
||||||
|
@ -10,7 +10,7 @@ Please consider using the prebuilt [docker images](docker.md) to get started qui
|
|||||||
|
|
||||||
Click each one for install guide:
|
Click each one for install guide:
|
||||||
|
|
||||||
* [Python >= 3.6.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
* [Python >= 3.7.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
||||||
* [pip](https://pip.pypa.io/en/stable/installing/)
|
* [pip](https://pip.pypa.io/en/stable/installing/)
|
||||||
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
* [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||||
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended)
|
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended)
|
||||||
@ -18,6 +18,9 @@ Click each one for install guide:
|
|||||||
|
|
||||||
We also recommend a [Telegram bot](telegram-usage.md#setup-your-telegram-bot), which is optional but recommended.
|
We also recommend a [Telegram bot](telegram-usage.md#setup-your-telegram-bot), which is optional but recommended.
|
||||||
|
|
||||||
|
!!! Warning "Up-to-date clock"
|
||||||
|
The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
Freqtrade provides the Linux/MacOS Easy Installation script to install all dependencies and help you configure the bot.
|
Freqtrade provides the Linux/MacOS Easy Installation script to install all dependencies and help you configure the bot.
|
||||||
@ -28,21 +31,21 @@ Freqtrade provides the Linux/MacOS Easy Installation script to install all depen
|
|||||||
The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the Easy Installation script, if it's available for your platform.
|
The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the Easy Installation script, if it's available for your platform.
|
||||||
|
|
||||||
!!! Note "Version considerations"
|
!!! Note "Version considerations"
|
||||||
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The `master` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
|
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The `stable` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Python3.6 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
Python3.7 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
||||||
|
|
||||||
This can be achieved with the following commands:
|
This can be achieved with the following commands:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/freqtrade/freqtrade.git
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
cd freqtrade
|
cd freqtrade
|
||||||
git checkout master # Optional, see (1)
|
# git checkout stable # Optional, see (1)
|
||||||
./setup.sh --install
|
./setup.sh --install
|
||||||
```
|
```
|
||||||
|
|
||||||
(1) This command switches the cloned repository to the use of the `master` branch. It's not needed if you wish to stay on the `develop` branch. You may later switch between branches at any time with the `git checkout master`/`git checkout develop` commands.
|
(1) This command switches the cloned repository to the use of the `stable` branch. It's not needed if you wish to stay on the `develop` branch. You may later switch between branches at any time with the `git checkout stable`/`git checkout develop` commands.
|
||||||
|
|
||||||
## Easy Installation Script (Linux/MacOS)
|
## Easy Installation Script (Linux/MacOS)
|
||||||
|
|
||||||
@ -53,14 +56,14 @@ $ ./setup.sh
|
|||||||
usage:
|
usage:
|
||||||
-i,--install Install freqtrade from scratch
|
-i,--install Install freqtrade from scratch
|
||||||
-u,--update Command git pull to update.
|
-u,--update Command git pull to update.
|
||||||
-r,--reset Hard reset your develop/master branch.
|
-r,--reset Hard reset your develop/stable branch.
|
||||||
-c,--config Easy config generator (Will override your existing file).
|
-c,--config Easy config generator (Will override your existing file).
|
||||||
```
|
```
|
||||||
|
|
||||||
** --install **
|
** --install **
|
||||||
|
|
||||||
With this option, the script will install the bot and most dependencies:
|
With this option, the script will install the bot and most dependencies:
|
||||||
You will need to have git and python3.6+ installed beforehand for this to work.
|
You will need to have git and python3.7+ installed beforehand for this to work.
|
||||||
|
|
||||||
* Mandatory software as: `ta-lib`
|
* Mandatory software as: `ta-lib`
|
||||||
* Setup your virtualenv under `.env/`
|
* Setup your virtualenv under `.env/`
|
||||||
@ -73,52 +76,59 @@ This option will pull the last version of your current branch and update your vi
|
|||||||
|
|
||||||
** --reset **
|
** --reset **
|
||||||
|
|
||||||
This option will hard reset your branch (only if you are on either `master` or `develop`) and recreate your virtualenv.
|
This option will hard reset your branch (only if you are on either `stable` or `develop`) and recreate your virtualenv.
|
||||||
|
|
||||||
** --config **
|
** --config **
|
||||||
|
|
||||||
DEPRECATED - use `freqtrade new-config -c config.json` instead.
|
DEPRECATED - use `freqtrade new-config -c config.json` instead.
|
||||||
|
|
||||||
|
### Activate your virtual environment
|
||||||
|
|
||||||
|
Each time you open a new terminal, you must run `source .env/bin/activate`.
|
||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
## Custom Installation
|
## Custom Installation
|
||||||
|
|
||||||
We've included/collected install instructions for Ubuntu 16.04, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros.
|
||||||
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
OS Specific steps are listed first, the [Common](#common) section below is necessary for all systems.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Python3.6 or higher and the corresponding pip are assumed to be available.
|
Python3.7 or higher and the corresponding pip are assumed to be available.
|
||||||
|
|
||||||
### Linux - Ubuntu 16.04
|
=== "Ubuntu/Debian"
|
||||||
|
#### Install necessary dependencies
|
||||||
|
|
||||||
#### Install necessary dependencies
|
```bash
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install build-essential git
|
||||||
|
```
|
||||||
|
|
||||||
```bash
|
=== "RaspberryPi/Raspbian"
|
||||||
sudo apt-get update
|
The following assumes the latest [Raspbian Buster lite image](https://www.raspberrypi.org/downloads/raspbian/).
|
||||||
sudo apt-get install build-essential git
|
This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.
|
||||||
```
|
|
||||||
|
|
||||||
### Raspberry Pi / Raspbian
|
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
|
||||||
|
|
||||||
|
|
||||||
The following assumes the latest [Raspbian Buster lite image](https://www.raspberrypi.org/downloads/raspbian/) from at least September 2019.
|
``` bash
|
||||||
This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.
|
sudo apt-get install python3-venv libatlas-base-dev cmake
|
||||||
|
# Use pywheels.org to speed up installation
|
||||||
|
sudo echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > tee /etc/pip.conf
|
||||||
|
|
||||||
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
|
cd freqtrade
|
||||||
|
|
||||||
``` bash
|
bash setup.sh -i
|
||||||
sudo apt-get install python3-venv libatlas-base-dev
|
```
|
||||||
git clone https://github.com/freqtrade/freqtrade.git
|
|
||||||
cd freqtrade
|
|
||||||
|
|
||||||
bash setup.sh -i
|
!!! Note "Installation duration"
|
||||||
```
|
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
|
||||||
|
Due to this, we recommend to use the prebuild docker-image for Raspberry, by following the [Docker quickstart documentation](docker_quickstart.md)
|
||||||
|
|
||||||
!!! Note "Installation duration"
|
!!! Note
|
||||||
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
|
The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
||||||
|
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
|
||||||
!!! Note
|
|
||||||
The above does not install hyperopt dependencies. To install these, please use `python3 -m pip install -e .[hyperopt]`.
|
|
||||||
We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
|
|
||||||
|
|
||||||
### Common
|
### Common
|
||||||
|
|
||||||
@ -169,12 +179,7 @@ Clone the git repository:
|
|||||||
```bash
|
```bash
|
||||||
git clone https://github.com/freqtrade/freqtrade.git
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
cd freqtrade
|
cd freqtrade
|
||||||
```
|
git checkout stable
|
||||||
|
|
||||||
Optionally checkout the master branch to get the latest stable release:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git checkout master
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 4. Install python dependencies
|
#### 4. Install python dependencies
|
||||||
@ -212,73 +217,19 @@ On Linux, as an optional post-installation task, you may wish to setup the bot t
|
|||||||
|
|
||||||
------
|
------
|
||||||
|
|
||||||
## Using Conda
|
### Anaconda
|
||||||
|
|
||||||
Freqtrade can also be installed using Anaconda (or Miniconda).
|
Freqtrade can also be installed using Anaconda (or Miniconda).
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
This requires the [ta-lib](#1-install-ta-lib) C-library to be installed first. See below.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
conda env create -f environment.yml
|
conda env create -f environment.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
-----
|
||||||
This requires the [ta-lib](#1-install-ta-lib) C-library to be installed first.
|
## Troubleshooting
|
||||||
|
|
||||||
## Windows
|
|
||||||
|
|
||||||
We recommend that Windows users use [Docker](docker.md) as this will work much easier and smoother (also more secure).
|
|
||||||
|
|
||||||
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work.
|
|
||||||
If that is not available on your system, feel free to try the instructions below, which led to success for some.
|
|
||||||
|
|
||||||
### Install freqtrade manually
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
|
|
||||||
|
|
||||||
!!! Hint
|
|
||||||
Using the [Anaconda Distribution](https://www.anaconda.com/distribution/) under Windows can greatly help with installation problems. Check out the [Conda section](#using-conda) in this document for more information.
|
|
||||||
|
|
||||||
#### Clone the git repository
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone https://github.com/freqtrade/freqtrade.git
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Install ta-lib
|
|
||||||
|
|
||||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
|
||||||
|
|
||||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.18‑cp38‑cp38‑win_amd64.whl` (make sure to use the version matching your python version)
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
>cd \path\freqtrade-develop
|
|
||||||
>python -m venv .env
|
|
||||||
>.env\Scripts\activate.bat
|
|
||||||
REM optionally install ta-lib from wheel
|
|
||||||
REM >pip install TA_Lib‑0.4.18‑cp38‑cp38‑win_amd64.whl
|
|
||||||
>pip install -r requirements.txt
|
|
||||||
>pip install -e .
|
|
||||||
>freqtrade
|
|
||||||
```
|
|
||||||
|
|
||||||
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
|
||||||
|
|
||||||
#### Error during installation under Windows
|
|
||||||
|
|
||||||
``` bash
|
|
||||||
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
|
|
||||||
```
|
|
||||||
|
|
||||||
Unfortunately, many packages requiring compilation don't provide a pre-build wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
|
|
||||||
|
|
||||||
The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building c code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or [docker](docker.md) first.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
Now you have an environment ready, the next step is
|
|
||||||
[Bot Configuration](configuration.md).
|
|
||||||
|
|
||||||
## Troubleshooting
|
|
||||||
|
|
||||||
### MacOS installation error
|
### MacOS installation error
|
||||||
|
|
||||||
@ -291,4 +242,9 @@ For MacOS 10.14, this can be accomplished with the below command.
|
|||||||
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
|
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
|
||||||
```
|
```
|
||||||
|
|
||||||
If this file is inexistant, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.
|
If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
Now you have an environment ready, the next step is
|
||||||
|
[Bot Configuration](configuration.md).
|
||||||
|
12
docs/javascripts/config.js
Normal file
12
docs/javascripts/config.js
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
window.MathJax = {
|
||||||
|
tex: {
|
||||||
|
inlineMath: [["\\(", "\\)"]],
|
||||||
|
displayMath: [["\\[", "\\]"]],
|
||||||
|
processEscapes: true,
|
||||||
|
processEnvironments: true
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
ignoreHtmlClass: ".*|",
|
||||||
|
processHtmlClass: "arithmatex"
|
||||||
|
}
|
||||||
|
};
|
@ -31,7 +31,7 @@ usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[--plot-limit INT] [--db-url PATH]
|
[--plot-limit INT] [--db-url PATH]
|
||||||
[--trade-source {DB,file}] [--export EXPORT]
|
[--trade-source {DB,file}] [--export EXPORT]
|
||||||
[--export-filename PATH]
|
[--export-filename PATH]
|
||||||
[--timerange TIMERANGE] [-i TICKER_INTERVAL]
|
[--timerange TIMERANGE] [-i TIMEFRAME]
|
||||||
[--no-trades]
|
[--no-trades]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
@ -65,7 +65,7 @@ optional arguments:
|
|||||||
_today.json`
|
_today.json`
|
||||||
--timerange TIMERANGE
|
--timerange TIMERANGE
|
||||||
Specify what timerange of data to use.
|
Specify what timerange of data to use.
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
|
||||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
`1d`).
|
`1d`).
|
||||||
--no-trades Skip using trades from backtesting file and DB.
|
--no-trades Skip using trades from backtesting file and DB.
|
||||||
@ -168,6 +168,7 @@ Additional features when using plot_config include:
|
|||||||
|
|
||||||
* Specify colors per indicator
|
* Specify colors per indicator
|
||||||
* Specify additional subplots
|
* Specify additional subplots
|
||||||
|
* Specify indicator pairs to fill area in between
|
||||||
|
|
||||||
The sample plot configuration below specifies fixed colors for the indicators. Otherwise consecutive plots may produce different colorschemes each time, making comparisons difficult.
|
The sample plot configuration below specifies fixed colors for the indicators. Otherwise consecutive plots may produce different colorschemes each time, making comparisons difficult.
|
||||||
It also allows multiple subplots to display both MACD and RSI at the same time.
|
It also allows multiple subplots to display both MACD and RSI at the same time.
|
||||||
@ -183,23 +184,33 @@ Sample configuration with inline comments explaining the process:
|
|||||||
'ema50': {'color': '#CCCCCC'},
|
'ema50': {'color': '#CCCCCC'},
|
||||||
# By omitting color, a random color is selected.
|
# By omitting color, a random color is selected.
|
||||||
'sar': {},
|
'sar': {},
|
||||||
|
# fill area between senkou_a and senkou_b
|
||||||
|
'senkou_a': {
|
||||||
|
'color': 'green', #optional
|
||||||
|
'fill_to': 'senkou_b',
|
||||||
|
'fill_label': 'Ichimoku Cloud' #optional,
|
||||||
|
'fill_color': 'rgba(255,76,46,0.2)', #optional
|
||||||
|
},
|
||||||
|
# plot senkou_b, too. Not only the area to it.
|
||||||
|
'senkou_b': {}
|
||||||
},
|
},
|
||||||
'subplots': {
|
'subplots': {
|
||||||
# Create subplot MACD
|
# Create subplot MACD
|
||||||
"MACD": {
|
"MACD": {
|
||||||
'macd': {'color': 'blue'},
|
'macd': {'color': 'blue', 'fill_to': 'macdhist'},
|
||||||
'macdsignal': {'color': 'orange'},
|
'macdsignal': {'color': 'orange'}
|
||||||
},
|
},
|
||||||
# Additional subplot RSI
|
# Additional subplot RSI
|
||||||
"RSI": {
|
"RSI": {
|
||||||
'rsi': {'color': 'red'},
|
'rsi': {'color': 'red'}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
|
||||||
|
|
||||||
|
```
|
||||||
!!! Note
|
!!! Note
|
||||||
The above configuration assumes that `ema10`, `ema50`, `macd`, `macdsignal` and `rsi` are columns in the DataFrame created by the strategy.
|
The above configuration assumes that `ema10`, `ema50`, `senkou_a`, `senkou_b`,
|
||||||
|
`macd`, `macdsignal`, `macdhist` and `rsi` are columns in the DataFrame created by the strategy.
|
||||||
|
|
||||||
## Plot profit
|
## Plot profit
|
||||||
|
|
||||||
@ -224,10 +235,11 @@ Possible options for the `freqtrade plot-profit` subcommand:
|
|||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]
|
[-d PATH] [--userdir PATH] [-s NAME]
|
||||||
|
[--strategy-path PATH] [-p PAIRS [PAIRS ...]]
|
||||||
[--timerange TIMERANGE] [--export EXPORT]
|
[--timerange TIMERANGE] [--export EXPORT]
|
||||||
[--export-filename PATH] [--db-url PATH]
|
[--export-filename PATH] [--db-url PATH]
|
||||||
[--trade-source {DB,file}] [-i TICKER_INTERVAL]
|
[--trade-source {DB,file}] [-i TIMEFRAME]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@ -250,7 +262,7 @@ optional arguments:
|
|||||||
--trade-source {DB,file}
|
--trade-source {DB,file}
|
||||||
Specify the source for trades (Can be DB or file
|
Specify the source for trades (Can be DB or file
|
||||||
(backtest file)) Default: file
|
(backtest file)) Default: file
|
||||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
-i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
|
||||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||||
`1d`).
|
`1d`).
|
||||||
|
|
||||||
@ -261,14 +273,20 @@ Common arguments:
|
|||||||
details.
|
details.
|
||||||
-V, --version show program's version number and exit
|
-V, --version show program's version number and exit
|
||||||
-c PATH, --config PATH
|
-c PATH, --config PATH
|
||||||
Specify configuration file (default: `config.json`).
|
Specify configuration file (default:
|
||||||
Multiple --config options may be used. Can be set to
|
`userdir/config.json` or `config.json` whichever
|
||||||
`-` to read config from stdin.
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
-d PATH, --datadir PATH
|
-d PATH, --datadir PATH
|
||||||
Path to directory with historical backtesting data.
|
Path to directory with historical backtesting data.
|
||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
|
|
||||||
|
Strategy arguments:
|
||||||
|
-s NAME, --strategy NAME
|
||||||
|
Specify strategy class name which will be used by the
|
||||||
|
bot.
|
||||||
|
--strategy-path PATH Specify additional strategy lookup path.
|
||||||
```
|
```
|
||||||
|
|
||||||
The `-p/--pairs` argument, can be used to limit the pairs that are considered for this calculation.
|
The `-p/--pairs` argument, can be used to limit the pairs that are considered for this calculation.
|
||||||
@ -278,7 +296,7 @@ Examples:
|
|||||||
Use custom backtest-export file
|
Use custom backtest-export file
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result-Strategy005.json
|
freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Use custom database
|
Use custom database
|
||||||
|
3
docs/plugins.md
Normal file
3
docs/plugins.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# Plugins
|
||||||
|
--8<-- "includes/pairlists.md"
|
||||||
|
--8<-- "includes/protections.md"
|
@ -1,2 +1,3 @@
|
|||||||
mkdocs-material==5.2.3
|
mkdocs-material==6.1.7
|
||||||
mdx_truly_sane_lists==1.2
|
mdx_truly_sane_lists==1.2
|
||||||
|
pymdown-extensions==8.0.1
|
||||||
|
192
docs/rest-api.md
192
docs/rest-api.md
@ -13,6 +13,7 @@ Sample configuration:
|
|||||||
"listen_port": 8080,
|
"listen_port": 8080,
|
||||||
"verbosity": "info",
|
"verbosity": "info",
|
||||||
"jwt_secret_key": "somethingrandom",
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": [],
|
||||||
"username": "Freqtrader",
|
"username": "Freqtrader",
|
||||||
"password": "SuperSecret1!"
|
"password": "SuperSecret1!"
|
||||||
},
|
},
|
||||||
@ -45,7 +46,7 @@ secrets.token_hex()
|
|||||||
|
|
||||||
### Configuration with docker
|
### Configuration with docker
|
||||||
|
|
||||||
If you run your bot using docker, you'll need to have the bot listen to incomming connections. The security is then handled by docker.
|
If you run your bot using docker, you'll need to have the bot listen to incoming connections. The security is then handled by docker.
|
||||||
|
|
||||||
``` json
|
``` json
|
||||||
"api_server": {
|
"api_server": {
|
||||||
@ -103,28 +104,43 @@ By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be use
|
|||||||
python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]
|
python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Available commands
|
## Available endpoints
|
||||||
|
|
||||||
| Command | Default | Description |
|
| Command | Description |
|
||||||
|----------|---------|-------------|
|
|----------|-------------|
|
||||||
| `start` | | Starts the trader
|
| `ping` | Simple command testing the API Readiness - requires no authentication.
|
||||||
| `stop` | | Stops the trader
|
| `start` | Starts the trader.
|
||||||
| `stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `stop` | Stops the trader.
|
||||||
| `reload_conf` | | Reloads the configuration file
|
| `stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `show_config` | | Shows part of the current configuration with relevant settings to operation
|
| `reload_config` | Reloads the configuration file.
|
||||||
| `status` | | Lists all open trades
|
| `trades` | List last trades.
|
||||||
| `count` | | Displays number of trades used and available
|
| `delete_trade <trade_id>` | Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange.
|
||||||
| `profit` | | Display a summary of your profit/loss from close trades and some stats about your performance
|
| `show_config` | Shows part of the current configuration with relevant settings to operation.
|
||||||
| `forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
| `logs` | Shows last log messages.
|
||||||
| `forcesell all` | | Instantly sells all open trades (Ignoring `minimum_roi`).
|
| `status` | Lists all open trades.
|
||||||
| `forcebuy <pair> [rate]` | | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
| `count` | Displays number of trades used and available.
|
||||||
| `performance` | | Show performance of each finished trade grouped by pair
|
| `locks` | Displays currently locked pairs.
|
||||||
| `balance` | | Show account balance per currency
|
| `profit` | Display a summary of your profit/loss from close trades and some stats about your performance.
|
||||||
| `daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
| `forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||||
| `whitelist` | | Show the current whitelist
|
| `forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`).
|
||||||
| `blacklist [pair]` | | Show the current blacklist, or adds a pair to the blacklist.
|
| `forcebuy <pair> [rate]` | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
||||||
| `edge` | | Show validated pairs by Edge if it is enabled.
|
| `performance` | Show performance of each finished trade grouped by pair.
|
||||||
| `version` | | Show version
|
| `balance` | Show account balance per currency.
|
||||||
|
| `daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7).
|
||||||
|
| `stats` | Display a summary of profit / loss reasons as well as average holding times.
|
||||||
|
| `whitelist` | Show the current whitelist.
|
||||||
|
| `blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||||
|
| `edge` | Show validated pairs by Edge if it is enabled.
|
||||||
|
| `pair_candles` | Returns dataframe for a pair / timeframe combination while the bot is running. **Alpha**
|
||||||
|
| `pair_history` | Returns an analyzed dataframe for a given timerange, analyzed by a given strategy. **Alpha**
|
||||||
|
| `plot_config` | Get plot config from the strategy (or nothing if not configured). **Alpha**
|
||||||
|
| `strategies` | List strategies in strategy directory. **Alpha**
|
||||||
|
| `strategy <strategy>` | Get specific Strategy content. **Alpha**
|
||||||
|
| `available_pairs` | List available backtest data. **Alpha**
|
||||||
|
| `version` | Show version.
|
||||||
|
|
||||||
|
!!! Warning "Alpha status"
|
||||||
|
Endpoints labeled with *Alpha status* above may change at any time without notice.
|
||||||
|
|
||||||
Possible commands can be listed from the rest-client script using the `help` command.
|
Possible commands can be listed from the rest-client script using the `help` command.
|
||||||
|
|
||||||
@ -134,78 +150,117 @@ python3 scripts/rest_client.py help
|
|||||||
|
|
||||||
``` output
|
``` output
|
||||||
Possible commands:
|
Possible commands:
|
||||||
|
|
||||||
|
available_pairs
|
||||||
|
Return available pair (backtest data) based on timeframe / stake_currency selection
|
||||||
|
|
||||||
|
:param timeframe: Only pairs with this timeframe available.
|
||||||
|
:param stake_currency: Only pairs that include this timeframe
|
||||||
|
|
||||||
balance
|
balance
|
||||||
Get the account balance
|
Get the account balance.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
blacklist
|
blacklist
|
||||||
Show the current blacklist
|
Show the current blacklist.
|
||||||
|
|
||||||
:param add: List of coins to add (example: "BNB/BTC")
|
:param add: List of coins to add (example: "BNB/BTC")
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
count
|
count
|
||||||
Returns the amount of open trades
|
Return the amount of open trades.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
daily
|
daily
|
||||||
Returns the amount of open trades
|
Return the amount of open trades.
|
||||||
:returns: json object
|
|
||||||
|
delete_trade
|
||||||
|
Delete trade from the database.
|
||||||
|
Tries to close open orders. Requires manual handling of this asset on the exchange.
|
||||||
|
|
||||||
|
:param trade_id: Deletes the trade with this ID from the database.
|
||||||
|
|
||||||
edge
|
edge
|
||||||
Returns information about edge
|
Return information about edge.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
forcebuy
|
forcebuy
|
||||||
Buy an asset
|
Buy an asset.
|
||||||
|
|
||||||
: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
|
||||||
:returns: json object of the trade
|
|
||||||
|
|
||||||
forcesell
|
forcesell
|
||||||
Force-sell a trade
|
Force-sell 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)
|
||||||
:returns: json object
|
|
||||||
|
logs
|
||||||
|
Show latest logs.
|
||||||
|
|
||||||
|
:param limit: Limits log messages to the last <limit> logs. No limit to get all the trades.
|
||||||
|
|
||||||
|
pair_candles
|
||||||
|
Return live dataframe for <pair><timeframe>.
|
||||||
|
|
||||||
|
:param pair: Pair to get data for
|
||||||
|
:param timeframe: Only pairs with this timeframe available.
|
||||||
|
:param limit: Limit result to the last n candles.
|
||||||
|
|
||||||
|
pair_history
|
||||||
|
Return historic, analyzed dataframe
|
||||||
|
|
||||||
|
:param pair: Pair to get data for
|
||||||
|
:param timeframe: Only pairs with this timeframe available.
|
||||||
|
:param strategy: Strategy to analyze and get values for
|
||||||
|
:param timerange: Timerange to get data for (same format than --timerange endpoints)
|
||||||
|
|
||||||
performance
|
performance
|
||||||
Returns the performance of the different coins
|
Return the performance of the different coins.
|
||||||
:returns: json object
|
|
||||||
|
plot_config
|
||||||
|
Return plot configuration if the strategy defines one.
|
||||||
|
|
||||||
profit
|
profit
|
||||||
Returns the profit summary
|
Return the profit summary.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
reload_conf
|
reload_config
|
||||||
Reload configuration
|
Reload configuration.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
show_config
|
show_config
|
||||||
|
|
||||||
Returns part of the configuration, relevant for trading operations.
|
Returns part of the configuration, relevant for trading operations.
|
||||||
:return: json object containing the version
|
|
||||||
|
|
||||||
start
|
start
|
||||||
Start the bot if it's in stopped state.
|
Start the bot if it's in the stopped state.
|
||||||
:returns: json object
|
|
||||||
|
stats
|
||||||
|
Return the stats report (durations, sell-reasons).
|
||||||
|
|
||||||
status
|
status
|
||||||
Get the status of open trades
|
Get the status of open trades.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
stop
|
stop
|
||||||
Stop the bot. Use start to restart
|
Stop the bot. Use `start` to restart.
|
||||||
:returns: json object
|
|
||||||
|
|
||||||
stopbuy
|
stopbuy
|
||||||
Stop buying (but handle sells gracefully).
|
Stop buying (but handle sells gracefully). Use `reload_config` to reset.
|
||||||
use reload_conf to reset
|
|
||||||
:returns: json object
|
strategies
|
||||||
|
Lists available strategies
|
||||||
|
|
||||||
|
strategy
|
||||||
|
Get strategy details
|
||||||
|
|
||||||
|
:param strategy: Strategy class name
|
||||||
|
|
||||||
|
trades
|
||||||
|
Return trades history.
|
||||||
|
|
||||||
|
:param limit: Limits trades to the X last trades. No limit to get all the trades.
|
||||||
|
|
||||||
version
|
version
|
||||||
Returns the version of the bot
|
Return the version of the bot.
|
||||||
:returns: json object containing the version
|
|
||||||
|
|
||||||
whitelist
|
whitelist
|
||||||
Show the current whitelist
|
Show the current whitelist.
|
||||||
:returns: json object
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Advanced API usage using JWT tokens
|
## Advanced API usage using JWT tokens
|
||||||
@ -232,3 +287,26 @@ Since the access token has a short timeout (15 min) - the `token/refresh` reques
|
|||||||
> curl -X POST --header "Authorization: Bearer ${refresh_token}"http://localhost:8080/api/v1/token/refresh
|
> curl -X POST --header "Authorization: Bearer ${refresh_token}"http://localhost:8080/api/v1/token/refresh
|
||||||
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs"}
|
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs"}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## CORS
|
||||||
|
|
||||||
|
All web-based frontends are subject to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) - Cross-Origin Resource Sharing.
|
||||||
|
Since most of the requests to the Freqtrade API must be authenticated, a proper CORS policy is key to avoid security problems.
|
||||||
|
Also, the standard disallows `*` CORS policies for requests with credentials, so this setting must be set appropriately.
|
||||||
|
|
||||||
|
Users can configure this themselves via the `CORS_origins` configuration setting.
|
||||||
|
It consists of a list of allowed sites that are allowed to consume resources from the bot's API.
|
||||||
|
|
||||||
|
Assuming your application is deployed as `https://frequi.freqtrade.io/home/` - this would mean that the following configuration becomes necessary:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
//...
|
||||||
|
"jwt_secret_key": "somethingrandom",
|
||||||
|
"CORS_origins": ["https://frequi.freqtrade.io"],
|
||||||
|
//...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
We strongly recommend to also set `jwt_secret_key` to something random and known only to yourself to avoid unauthorized access to your bot.
|
||||||
|
@ -1,104 +1,59 @@
|
|||||||
# Sandbox API testing
|
# Sandbox API testing
|
||||||
|
|
||||||
Where an exchange provides a sandbox for risk-free integration, or end-to-end, testing CCXT provides access to these.
|
Some exchanges provide sandboxes or testbeds for risk-free testing, while running the bot against a real exchange.
|
||||||
|
With some configuration, freqtrade (in combination with ccxt) provides access to these.
|
||||||
|
|
||||||
This document is a *light overview of configuring Freqtrade and GDAX sandbox.
|
This document is an overview to configure Freqtrade to be used with sandboxes.
|
||||||
This can be useful to developers and trader alike as Freqtrade is quite customisable.
|
This can be useful to developers and trader alike.
|
||||||
|
|
||||||
When testing your API connectivity, make sure to use the following URLs.
|
## Exchanges known to have a sandbox / testnet
|
||||||
***Website**
|
|
||||||
https://public.sandbox.gdax.com
|
* [binance](https://testnet.binance.vision/)
|
||||||
***REST API**
|
* [coinbasepro](https://public.sandbox.pro.coinbase.com)
|
||||||
https://api-public.sandbox.gdax.com
|
* [gemini](https://exchange.sandbox.gemini.com/)
|
||||||
|
* [huobipro](https://www.testnet.huobi.pro/)
|
||||||
|
* [kucoin](https://sandbox.kucoin.com/)
|
||||||
|
* [phemex](https://testnet.phemex.com/)
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
We did not test correct functioning of all of the above testnets. Please report your experiences with each sandbox.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Configure a Sandbox account on Gdax
|
## Configure a Sandbox account
|
||||||
|
|
||||||
Aim of this document section
|
When testing your API connectivity, make sure to use the appropriate sandbox / testnet URL.
|
||||||
|
|
||||||
- An sanbox account
|
In general, you should follow these steps to enable an exchange's sandbox:
|
||||||
- create 2FA (needed to create an API)
|
|
||||||
- Add test 50BTC to account
|
|
||||||
- Create :
|
|
||||||
- - API-KEY
|
|
||||||
- - API-Secret
|
|
||||||
- - API Password
|
|
||||||
|
|
||||||
## Acccount
|
* Figure out if an exchange has a sandbox (most likely by using google or the exchange's support documents)
|
||||||
|
* Create a sandbox account (often the sandbox-account requires separate registration)
|
||||||
|
* [Add some test assets to account](#add-test-funds)
|
||||||
|
* Create API keys
|
||||||
|
|
||||||
This link will redirect to the sandbox main page to login / create account dialogues:
|
### Add test funds
|
||||||
https://public.sandbox.pro.coinbase.com/orders/
|
|
||||||
|
|
||||||
After registration and Email confimation you wil be redirected into your sanbox account. It is easy to verify you're in sandbox by checking the URL bar.
|
Usually, sandbox exchanges allow depositing funds directly via web-interface.
|
||||||
> https://public.sandbox.pro.coinbase.com/
|
You should make sure to have a realistic amount of funds available to your test-account, so results are representable of your real account funds.
|
||||||
|
|
||||||
## Enable 2Fa (a prerequisite to creating sandbox API Keys)
|
!!! Warning
|
||||||
|
Test exchanges will **NEVER** require your real credit card or banking details!
|
||||||
|
|
||||||
From within sand box site select your profile, top right.
|
## Configure freqtrade to use a exchange's sandbox
|
||||||
>Or as a direct link: https://public.sandbox.pro.coinbase.com/profile
|
|
||||||
|
|
||||||
From the menu panel to the left of the screen select
|
### Sandbox URLs
|
||||||
|
|
||||||
> Security: "*View or Update*"
|
|
||||||
|
|
||||||
In the new site select "enable authenticator" as typical google Authenticator.
|
|
||||||
|
|
||||||
- open Google Authenticator on your phone
|
|
||||||
- scan barcode
|
|
||||||
- enter your generated 2fa
|
|
||||||
|
|
||||||
## Enable API Access
|
|
||||||
|
|
||||||
From within sandbox select profile>api>create api-keys
|
|
||||||
>or as a direct link: https://public.sandbox.pro.coinbase.com/profile/api
|
|
||||||
|
|
||||||
Click on "create one" and ensure **view** and **trade** are "checked" and sumbit your 2FA
|
|
||||||
|
|
||||||
- **Copy and paste the Passphase** into a notepade this will be needed later
|
|
||||||
- **Copy and paste the API Secret** popup into a notepad this will needed later
|
|
||||||
- **Copy and paste the API Key** into a notepad this will needed later
|
|
||||||
|
|
||||||
## Add 50 BTC test funds
|
|
||||||
|
|
||||||
To add funds, use the web interface deposit and withdraw buttons.
|
|
||||||
|
|
||||||
To begin select 'Wallets' from the top menu.
|
|
||||||
> Or as a direct link: https://public.sandbox.pro.coinbase.com/wallets
|
|
||||||
|
|
||||||
- Deposits (bottom left of screen)
|
|
||||||
- - Deposit Funds Bitcoin
|
|
||||||
- - - Coinbase BTC Wallet
|
|
||||||
- - - - Max (50 BTC)
|
|
||||||
- - - - - Deposit
|
|
||||||
|
|
||||||
*This process may be repeated for other currencies, ETH as example*
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Configure Freqtrade to use Gax Sandbox
|
|
||||||
|
|
||||||
The aim of this document section
|
|
||||||
|
|
||||||
- Enable sandbox URLs in Freqtrade
|
|
||||||
- Configure API
|
|
||||||
- - secret
|
|
||||||
- - key
|
|
||||||
- - passphrase
|
|
||||||
|
|
||||||
## Sandbox URLs
|
|
||||||
|
|
||||||
Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade.
|
Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade.
|
||||||
These include `['test']` and `['api']`.
|
These include `['test']` and `['api']`.
|
||||||
|
|
||||||
- `[Test]` if available will point to an Exchanges sandbox.
|
* `[Test]` if available will point to an Exchanges sandbox.
|
||||||
- `[Api]` normally used, and resolves to live API target on the exchange
|
* `[Api]` normally used, and resolves to live API target on the exchange.
|
||||||
|
|
||||||
To make use of sandbox / test add "sandbox": true, to your config.json
|
To make use of sandbox / test add "sandbox": true, to your config.json
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"exchange": {
|
"exchange": {
|
||||||
"name": "gdax",
|
"name": "coinbasepro",
|
||||||
"sandbox": true,
|
"sandbox": true,
|
||||||
"key": "5wowfxemogxeowo;heiohgmd",
|
"key": "5wowfxemogxeowo;heiohgmd",
|
||||||
"secret": "/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==",
|
"secret": "/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==",
|
||||||
@ -106,36 +61,57 @@ To make use of sandbox / test add "sandbox": true, to your config.json
|
|||||||
"outdated_offset": 5
|
"outdated_offset": 5
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"BTC/USD"
|
"BTC/USD"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"datadir": "user_data/data/coinbasepro_sandbox"
|
||||||
```
|
```
|
||||||
|
|
||||||
Also insert your
|
Also the following information:
|
||||||
|
|
||||||
- api-key (noted earlier)
|
* api-key (created for the sandbox webpage)
|
||||||
- api-secret (noted earlier)
|
* api-secret (noted earlier)
|
||||||
- password (the passphrase - noted earlier)
|
* password (the passphrase - noted earlier)
|
||||||
|
|
||||||
|
!!! Tip "Different data directory"
|
||||||
|
We also recommend to set `datadir` to something identifying downloaded data as sandbox data, to avoid having sandbox data mixed with data from the real exchange.
|
||||||
|
This can be done by adding the `"datadir"` key to the configuration.
|
||||||
|
Now, whenever you use this configuration, your data directory will be set to this directory.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## You should now be ready to test your sandbox
|
## You should now be ready to test your sandbox
|
||||||
|
|
||||||
Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox.
|
Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox. Also make sure to select a pair which shows at least some decent value (which very often is BTC/<somestablecoin>).
|
||||||
** Typically the BTC/USD has the most activity in sandbox to test against.
|
|
||||||
|
|
||||||
## GDAX - Old Candles problem
|
## Common problems with sandbox exchanges
|
||||||
|
|
||||||
It is my experience that GDAX sandbox candles may be 20+- minutes out of date. This can cause trades to fail as one of Freqtrades safety checks.
|
Sandbox exchange instances often have very low volume, which can cause some problems which usually are not seen on a real exchange instance.
|
||||||
|
|
||||||
To disable this check, add / change the `"outdated_offset"` parameter in the exchange section of your configuration to adjust for this delay.
|
### Old Candles problem
|
||||||
Example based on the above configuration:
|
|
||||||
|
|
||||||
```json
|
Since Sandboxes often have low volume, candles can be quite old and show no volume.
|
||||||
"exchange": {
|
To disable the error "Outdated history for pair ...", best increase the parameter `"outdated_offset"` to a number that seems realistic for the sandbox you're using.
|
||||||
"name": "gdax",
|
|
||||||
"sandbox": true,
|
### Unfilled orders
|
||||||
"key": "5wowfxemogxeowo;heiohgmd",
|
|
||||||
"secret": "/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==",
|
Sandboxes often have very low volumes - which means that many trades can go unfilled, or can go unfilled for a very long time.
|
||||||
"password": "1bkjfkhfhfu6sr",
|
|
||||||
"outdated_offset": 30
|
To mitigate this, you can try to match the first order on the opposite orderbook side using the following configuration:
|
||||||
"pair_whitelist": [
|
|
||||||
"BTC/USD"
|
``` jsonc
|
||||||
```
|
"order_types": {
|
||||||
|
"buy": "limit",
|
||||||
|
"sell": "limit"
|
||||||
|
// ...
|
||||||
|
},
|
||||||
|
"bid_strategy": {
|
||||||
|
"price_side": "ask",
|
||||||
|
// ...
|
||||||
|
},
|
||||||
|
"ask_strategy":{
|
||||||
|
"price_side": "bid",
|
||||||
|
// ...
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
The configuration is similar to the suggested configuration for market orders - however by using limit-orders you can avoid moving the price too much, and you can set the worst price you might get.
|
||||||
|
@ -13,6 +13,15 @@ Feel free to use a visual Database editor like SqliteBrowser if you feel more co
|
|||||||
sudo apt-get install sqlite3
|
sudo apt-get install sqlite3
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Using sqlite3 via docker-compose
|
||||||
|
|
||||||
|
The freqtrade docker image does contain sqlite3, so you can edit the database without having to install anything on the host system.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose exec freqtrade /bin/bash
|
||||||
|
sqlite3 <databasefile>.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
## Open the DB
|
## Open the DB
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@ -34,52 +43,6 @@ sqlite3
|
|||||||
.schema <table_name>
|
.schema <table_name>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Trade table structure
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE TABLE trades
|
|
||||||
id INTEGER NOT NULL,
|
|
||||||
exchange VARCHAR NOT NULL,
|
|
||||||
pair VARCHAR NOT NULL,
|
|
||||||
is_open BOOLEAN NOT NULL,
|
|
||||||
fee_open FLOAT NOT NULL,
|
|
||||||
fee_open_cost FLOAT,
|
|
||||||
fee_open_currency VARCHAR,
|
|
||||||
fee_close FLOAT NOT NULL,
|
|
||||||
fee_close_cost FLOAT,
|
|
||||||
fee_close_currency VARCHAR,
|
|
||||||
open_rate FLOAT,
|
|
||||||
open_rate_requested FLOAT,
|
|
||||||
open_trade_price FLOAT,
|
|
||||||
close_rate FLOAT,
|
|
||||||
close_rate_requested FLOAT,
|
|
||||||
close_profit FLOAT,
|
|
||||||
close_profit_abs FLOAT,
|
|
||||||
stake_amount FLOAT NOT NULL,
|
|
||||||
amount FLOAT,
|
|
||||||
open_date DATETIME NOT NULL,
|
|
||||||
close_date DATETIME,
|
|
||||||
open_order_id VARCHAR,
|
|
||||||
stop_loss FLOAT,
|
|
||||||
stop_loss_pct FLOAT,
|
|
||||||
initial_stop_loss FLOAT,
|
|
||||||
initial_stop_loss_pct FLOAT,
|
|
||||||
stoploss_order_id VARCHAR,
|
|
||||||
stoploss_last_update DATETIME,
|
|
||||||
max_rate FLOAT,
|
|
||||||
min_rate FLOAT,
|
|
||||||
sell_reason VARCHAR,
|
|
||||||
strategy VARCHAR,
|
|
||||||
ticker_interval INTEGER,
|
|
||||||
PRIMARY KEY (id),
|
|
||||||
CHECK (is_open IN (0, 1))
|
|
||||||
);
|
|
||||||
CREATE INDEX ix_trades_stoploss_order_id ON trades (stoploss_order_id);
|
|
||||||
CREATE INDEX ix_trades_pair ON trades (pair);
|
|
||||||
CREATE INDEX ix_trades_is_open ON trades (is_open);
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## Get all trades in the table
|
## Get all trades in the table
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@ -89,19 +52,19 @@ SELECT * FROM trades;
|
|||||||
## Fix trade still open after a manual sell on the exchange
|
## Fix trade still open after a manual sell 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, forcesell <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 /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
UPDATE trades
|
UPDATE trades
|
||||||
SET is_open=0,
|
SET is_open=0,
|
||||||
close_date=<close_date>,
|
close_date=<close_date>,
|
||||||
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>
|
sell_reason=<sell_reason>
|
||||||
WHERE id=<trade_ID_to_update>;
|
WHERE id=<trade_ID_to_update>;
|
||||||
```
|
```
|
||||||
@ -111,24 +74,28 @@ WHERE id=<trade_ID_to_update>;
|
|||||||
```sql
|
```sql
|
||||||
UPDATE trades
|
UPDATE trades
|
||||||
SET is_open=0,
|
SET is_open=0,
|
||||||
close_date='2017-12-20 03:08:45.103418',
|
close_date='2020-06-20 03:08:45.103418',
|
||||||
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'
|
sell_reason='force_sell'
|
||||||
WHERE id=31;
|
WHERE id=31;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Insert manually a new trade
|
## Remove trade from the database
|
||||||
|
|
||||||
|
!!! Tip "Use RPC Methods to delete trades"
|
||||||
|
Consider using `/delete <tradeid>` via telegram or rest API. That's the recommended way to deleting trades.
|
||||||
|
|
||||||
|
If you'd still like to remove a trade from the database directly, you can use the below query.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
DELETE FROM trades WHERE id = <tradeid>;
|
||||||
VALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')
|
|
||||||
```
|
```
|
||||||
|
|
||||||
##### Example:
|
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)
|
DELETE FROM trades WHERE id = 31;
|
||||||
VALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Warning
|
||||||
|
This will remove this trade from the database. Please make sure you got the correct id and **NEVER** run this query without the `where` clause.
|
||||||
|
162
docs/stoploss.md
162
docs/stoploss.md
@ -6,7 +6,69 @@ For example, value `-0.10` will cause immediate sell if the profit dips below -1
|
|||||||
Most of the strategy files already include the optimal `stoploss` value.
|
Most of the strategy files already include the optimal `stoploss` value.
|
||||||
|
|
||||||
!!! Info
|
!!! Info
|
||||||
All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values.
|
All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration.
|
||||||
|
<ins>Configuration values will override the strategy values.</ins>
|
||||||
|
|
||||||
|
## Stop Loss On-Exchange/Freqtrade
|
||||||
|
|
||||||
|
Those stoploss modes can be *on exchange* or *off exchange*.
|
||||||
|
|
||||||
|
These modes can be configured with these values:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
'emergencysell': 'market',
|
||||||
|
'stoploss_on_exchange': False
|
||||||
|
'stoploss_on_exchange_interval': 60,
|
||||||
|
'stoploss_on_exchange_limit_ratio': 0.99
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Stoploss on exchange is only supported for Binance (stop-loss-limit), Kraken (stop-loss-market, stop-loss-limit) and FTX (stop limit and stop-market) as of now.
|
||||||
|
<ins>Do not set too low/tight stoploss value if using stop loss on exchange!</ins>
|
||||||
|
If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work.
|
||||||
|
|
||||||
|
### stoploss_on_exchange and stoploss_on_exchange_limit_ratio
|
||||||
|
|
||||||
|
Enable or Disable stop loss on exchange.
|
||||||
|
If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
||||||
|
|
||||||
|
If `stoploss_on_exchange` uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price.
|
||||||
|
`stoploss` defines the stop-price where the limit order is placed - and limit should be slightly below this.
|
||||||
|
If an exchange supports both limit and market stoploss orders, then the value of `stoploss` will be used to determine the stoploss type.
|
||||||
|
|
||||||
|
Calculation example: we bought the asset at 100\$.
|
||||||
|
Stop-price is 95\$, then limit would be `95 * 0.99 = 94.05$` - so the limit order fill can happen between 95$ and 94.05$.
|
||||||
|
|
||||||
|
For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.
|
||||||
|
|
||||||
|
### stoploss_on_exchange_interval
|
||||||
|
|
||||||
|
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
|
||||||
|
The bot cannot do these every 5 seconds (at each iteration), otherwise it would get banned by the exchange.
|
||||||
|
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.
|
||||||
|
|
||||||
|
### emergencysell
|
||||||
|
|
||||||
|
`emergencysell` 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.
|
||||||
|
|
||||||
|
Example from strategy file:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
order_types = {
|
||||||
|
'buy': 'limit',
|
||||||
|
'sell': 'limit',
|
||||||
|
'emergencysell': 'market',
|
||||||
|
'stoploss': 'market',
|
||||||
|
'stoploss_on_exchange': True,
|
||||||
|
'stoploss_on_exchange_interval': 60,
|
||||||
|
'stoploss_on_exchange_limit_ratio': 0.99
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Stop Loss Types
|
## Stop Loss Types
|
||||||
|
|
||||||
@ -17,29 +79,30 @@ At this stage the bot contains the following stoploss support modes:
|
|||||||
3. Trailing stop loss, custom positive loss.
|
3. Trailing stop loss, custom positive loss.
|
||||||
4. Trailing stop loss only once the trade has reached a certain offset.
|
4. Trailing stop loss only once the trade has reached a certain offset.
|
||||||
|
|
||||||
Those stoploss modes can be *on exchange* or *off exchange*. If the stoploss is *on exchange* it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.
|
### Static Stop Loss
|
||||||
|
|
||||||
In case of stoploss on exchange there is another parameter called `stoploss_on_exchange_interval`. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
|
|
||||||
|
|
||||||
For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order.
|
|
||||||
The bot cannot do this every 5 seconds (at each iteration), otherwise it would get banned by the exchange.
|
|
||||||
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.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Stoploss on exchange is only supported for Binance (stop-loss-limit) and Kraken (stop-loss-market) as of now.
|
|
||||||
|
|
||||||
## Static Stop Loss
|
|
||||||
|
|
||||||
This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss.
|
This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss.
|
||||||
|
|
||||||
## Trailing Stop Loss
|
Example of stop loss:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
stoploss = -0.10
|
||||||
|
```
|
||||||
|
|
||||||
|
For example, simplified math:
|
||||||
|
|
||||||
|
* the bot buys an asset at a price of 100$
|
||||||
|
* the stop loss is defined at -10%
|
||||||
|
* the stop loss would get triggered once the asset drops below 90$
|
||||||
|
|
||||||
|
### Trailing Stop Loss
|
||||||
|
|
||||||
The initial value for this is `stoploss`, just as you would define your static Stop loss.
|
The initial value for this is `stoploss`, just as you would define your static Stop loss.
|
||||||
To enable trailing stoploss:
|
To enable trailing stoploss:
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
trailing_stop = True
|
stoploss = -0.10
|
||||||
|
trailing_stop = True
|
||||||
```
|
```
|
||||||
|
|
||||||
This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.
|
This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.
|
||||||
@ -47,35 +110,43 @@ This will now activate an algorithm, which automatically moves the stop loss up
|
|||||||
For example, simplified math:
|
For example, simplified math:
|
||||||
|
|
||||||
* the bot buys an asset at a price of 100$
|
* the bot buys an asset at a price of 100$
|
||||||
* the stop loss is defined at 2%
|
* the stop loss is defined at -10%
|
||||||
* the stop loss would get triggered once the asset dropps below 98$
|
* the stop loss would get triggered once the asset drops below 90$
|
||||||
* assuming the asset now increases to 102$
|
* assuming the asset now increases to 102$
|
||||||
* the stop loss will now be 2% of 102$ or 99.96$
|
* the stop loss will now be -10% of 102$ = 91.8$
|
||||||
* now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$.
|
* now the asset drops in value to 101\$, the stop loss will still be 91.8$ and would trigger at 91.8$.
|
||||||
|
|
||||||
In summary: The stoploss will be adjusted to be always be 2% of the highest observed price.
|
In summary: The stoploss will be adjusted to be always be -10% of the highest observed price.
|
||||||
|
|
||||||
### Custom positive stoploss
|
### Trailing stop loss, custom positive loss
|
||||||
|
|
||||||
It is also possible to have a default stop loss, when you are in the red with your buy, but once your profit surpasses a certain percentage, the system will utilize a new stop loss, which can have a different value.
|
It is also possible to have a default stop loss, when you are in the red with your buy (buy - fee), but once you hit positive result the system will utilize a new stop loss, which can have a different value.
|
||||||
For example your default stop loss is 5%, but once you have 1.1% profit, it will be changed to be only a 1% stop loss, which trails the green candles until it goes below them.
|
For example, your default stop loss is -10%, but once you have more than 0% profit (example 0.1%) a different trailing stoploss will be used.
|
||||||
|
|
||||||
Both values require `trailing_stop` to be set to true.
|
!!! Note
|
||||||
|
If you want the stoploss to only be changed when you break even of making a profit (what most users want) please refer to next section with [offset enabled](#Trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset).
|
||||||
|
|
||||||
|
Both values require `trailing_stop` to be set to true and `trailing_stop_positive` with a value.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
trailing_stop_positive = 0.01
|
stoploss = -0.10
|
||||||
trailing_stop_positive_offset = 0.011
|
trailing_stop = True
|
||||||
|
trailing_stop_positive = 0.02
|
||||||
```
|
```
|
||||||
|
|
||||||
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit.
|
For example, simplified math:
|
||||||
|
|
||||||
|
* the bot buys an asset at a price of 100$
|
||||||
|
* the stop loss is defined at -10%
|
||||||
|
* the stop loss would get triggered once the asset drops below 90$
|
||||||
|
* assuming the asset now increases to 102$
|
||||||
|
* the stop loss will now be -2% of 102$ = 99.96$ (99.96$ stop loss will be locked in and will follow asset price increments with -2%)
|
||||||
|
* now the asset drops in value to 101\$, the stop loss will still be 99.96$ and would trigger at 99.96$
|
||||||
|
|
||||||
|
The 0.02 would translate to a -2% stop loss.
|
||||||
Before this, `stoploss` is used for the trailing stoploss.
|
Before this, `stoploss` is used for the trailing stoploss.
|
||||||
|
|
||||||
Read the [next section](#trailing-only-once-offset-is-reached) to keep stoploss at 5% of the entry point.
|
### Trailing stop loss only once the trade has reached a certain offset
|
||||||
|
|
||||||
!!! Tip
|
|
||||||
Make sure to have this value (`trailing_stop_positive_offset`) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.
|
|
||||||
|
|
||||||
### Trailing only once offset is reached
|
|
||||||
|
|
||||||
It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns.
|
It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns.
|
||||||
|
|
||||||
@ -84,24 +155,35 @@ This option can be used with or without `trailing_stop_positive`, but uses `trai
|
|||||||
|
|
||||||
``` python
|
``` python
|
||||||
trailing_stop_positive_offset = 0.011
|
trailing_stop_positive_offset = 0.011
|
||||||
trailing_only_offset_is_reached = true
|
trailing_only_offset_is_reached = True
|
||||||
```
|
```
|
||||||
|
|
||||||
Simplified example:
|
Configuration (offset is buy-price + 3%):
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
stoploss = 0.05
|
stoploss = -0.10
|
||||||
|
trailing_stop = True
|
||||||
|
trailing_stop_positive = 0.02
|
||||||
trailing_stop_positive_offset = 0.03
|
trailing_stop_positive_offset = 0.03
|
||||||
trailing_only_offset_is_reached = True
|
trailing_only_offset_is_reached = True
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For example, simplified math:
|
||||||
|
|
||||||
* the bot buys an asset at a price of 100$
|
* the bot buys an asset at a price of 100$
|
||||||
* the stop loss is defined at 5%
|
* the stop loss is defined at -10%
|
||||||
* the stop loss will remain at 95% until profit reaches +3%
|
* the stop loss would get triggered once the asset drops below 90$
|
||||||
|
* stoploss will remain at 90$ unless asset increases to or above our configured offset
|
||||||
|
* assuming the asset now increases to 103$ (where we have the offset configured)
|
||||||
|
* the stop loss will now be -2% of 103$ = 100.94$
|
||||||
|
* now the asset drops in value to 101\$, the stop loss will still be 100.94$ and would trigger at 100.94$
|
||||||
|
|
||||||
|
!!! Tip
|
||||||
|
Make sure to have this value (`trailing_stop_positive_offset`) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.
|
||||||
|
|
||||||
## Changing stoploss on open trades
|
## Changing stoploss on open trades
|
||||||
|
|
||||||
A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the `/reload_conf` command (alternatively, completely stopping and restarting the bot also works).
|
A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the `/reload_config` command (alternatively, completely stopping and restarting the bot also works).
|
||||||
|
|
||||||
The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).
|
The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).
|
||||||
|
|
||||||
|
@ -1,7 +1,12 @@
|
|||||||
# Advanced Strategies
|
# Advanced Strategies
|
||||||
|
|
||||||
This page explains some advanced concepts available for strategies.
|
This page explains some advanced concepts available for strategies.
|
||||||
If you're just getting started, please be familiar with the methods described in the [Strategy Customization](strategy-customization.md) documentation first.
|
If you're just getting started, please be familiar with the methods described in the [Strategy Customization](strategy-customization.md) documentation and with the [Freqtrade basics](bot-basics.md) first.
|
||||||
|
|
||||||
|
[Freqtrade basics](bot-basics.md) describes in which sequence each method described below is called, which can be helpful to understand which method to use for your custom needs.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
All callback methods described below should only be implemented in a strategy if they are actually used.
|
||||||
|
|
||||||
## Custom order timeout rules
|
## Custom order timeout rules
|
||||||
|
|
||||||
@ -89,3 +94,129 @@ class Awesomestrategy(IStrategy):
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Bot loop start callback
|
||||||
|
|
||||||
|
A simple callback which is called once at the start of every bot throttling iteration.
|
||||||
|
This can be used to perform calculations which are pair independent (apply to all pairs), loading of external data, etc.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
import requests
|
||||||
|
|
||||||
|
class Awesomestrategy(IStrategy):
|
||||||
|
|
||||||
|
# ... populate_* methods
|
||||||
|
|
||||||
|
def bot_loop_start(self, **kwargs) -> None:
|
||||||
|
"""
|
||||||
|
Called at the start of the bot iteration (one loop).
|
||||||
|
Might be used to perform pair-independent tasks
|
||||||
|
(e.g. gather some remote resource for comparison)
|
||||||
|
: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.remote_data = requests.get('https://some_remote_source.example.com')
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bot order confirmation
|
||||||
|
|
||||||
|
### Trade entry (buy order) confirmation
|
||||||
|
|
||||||
|
`confirm_trade_entry()` can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).
|
||||||
|
|
||||||
|
``` python
|
||||||
|
class Awesomestrategy(IStrategy):
|
||||||
|
|
||||||
|
# ... populate_* methods
|
||||||
|
|
||||||
|
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||||
|
time_in_force: str, **kwargs) -> bool:
|
||||||
|
"""
|
||||||
|
Called right before placing a buy order.
|
||||||
|
Timing for this function is critical, so avoid doing heavy computations or
|
||||||
|
network requests in this method.
|
||||||
|
|
||||||
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
|
|
||||||
|
When not implemented by a strategy, returns True (always confirming).
|
||||||
|
|
||||||
|
:param pair: Pair that's about to be bought.
|
||||||
|
: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 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 **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.
|
||||||
|
False aborts the process
|
||||||
|
"""
|
||||||
|
return True
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Trade exit (sell order) confirmation
|
||||||
|
|
||||||
|
`confirm_trade_exit()` can be used to abort a trade exit (sell) at the latest second (maybe because the price is not what we expect).
|
||||||
|
|
||||||
|
``` python
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
|
||||||
|
|
||||||
|
class Awesomestrategy(IStrategy):
|
||||||
|
|
||||||
|
# ... populate_* methods
|
||||||
|
|
||||||
|
def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
|
||||||
|
rate: float, time_in_force: str, sell_reason: str, **kwargs) -> bool:
|
||||||
|
"""
|
||||||
|
Called right before placing a regular sell order.
|
||||||
|
Timing for this function is critical, so avoid doing heavy computations or
|
||||||
|
network requests in this method.
|
||||||
|
|
||||||
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
|
|
||||||
|
When not implemented by a strategy, returns True (always confirming).
|
||||||
|
|
||||||
|
:param pair: Pair that's about to be sold.
|
||||||
|
:param order_type: Order type (as configured in order_types). usually limit or market.
|
||||||
|
:param amount: Amount in quote currency.
|
||||||
|
: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 sell_reason: Sell reason.
|
||||||
|
Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
|
||||||
|
'sell_signal', 'force_sell', 'emergency_sell']
|
||||||
|
: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.
|
||||||
|
False aborts the process
|
||||||
|
"""
|
||||||
|
if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0:
|
||||||
|
# Reject force-sells with negative profit
|
||||||
|
# This is just a sample, please adjust to your needs
|
||||||
|
# (this does not necessarily make sense, assuming you know when you're force-selling)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Derived strategies
|
||||||
|
|
||||||
|
The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
class MyAwesomeStrategy(IStrategy):
|
||||||
|
...
|
||||||
|
stoploss = 0.13
|
||||||
|
trailing_stop = False
|
||||||
|
# All other attributes and methods are here as they
|
||||||
|
# should be in any custom strategy...
|
||||||
|
...
|
||||||
|
|
||||||
|
class MyAwesomeStrategy2(MyAwesomeStrategy):
|
||||||
|
# Override something
|
||||||
|
stoploss = 0.08
|
||||||
|
trailing_stop = True
|
||||||
|
```
|
||||||
|
|
||||||
|
Both attributes and methods may be overriden, altering behavior of the original strategy in a way you need.
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
# Strategy Customization
|
# Strategy Customization
|
||||||
|
|
||||||
This page explains where to customize your strategies, and add new indicators.
|
This page explains how to customize your strategies, add new indicators and set up trading rules.
|
||||||
|
|
||||||
|
Please familiarize yourself with [Freqtrade basics](bot-basics.md) first, which provides overall info on how the bot operates.
|
||||||
|
|
||||||
## Install a custom strategy file
|
## Install a custom strategy file
|
||||||
|
|
||||||
@ -56,12 +58,12 @@ file as reference.**
|
|||||||
|
|
||||||
!!! Note "Strategies and Backtesting"
|
!!! Note "Strategies and Backtesting"
|
||||||
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware
|
||||||
that during backtesting the full time-interval is passed to the `populate_*()` methods at once.
|
that during backtesting the full time range is passed to the `populate_*()` methods at once.
|
||||||
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
It is therefore best to use vectorized operations (across the whole dataframe, not loops) and
|
||||||
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
avoid index referencing (`df.iloc[-1]`), but instead use `df.shift()` to get to the previous candle.
|
||||||
|
|
||||||
!!! Warning "Warning: Using future data"
|
!!! Warning "Warning: Using future data"
|
||||||
Since backtesting passes the full time interval to the `populate_*()` methods, the strategy author
|
Since backtesting passes the full time range to the `populate_*()` methods, the strategy author
|
||||||
needs to take care to avoid having the strategy utilize data from the future.
|
needs to take care to avoid having the strategy utilize data from the future.
|
||||||
Some common patterns for this are listed in the [Common Mistakes](#common-mistakes-when-developing-strategies) section of this document.
|
Some common patterns for this are listed in the [Common Mistakes](#common-mistakes-when-developing-strategies) section of this document.
|
||||||
|
|
||||||
@ -139,13 +141,13 @@ By letting the bot know how much history is needed, backtest trades can start at
|
|||||||
|
|
||||||
#### Example
|
#### Example
|
||||||
|
|
||||||
Let's try to backtest 1 month (January 2019) of 5m candles using the an example strategy with EMA100, as above.
|
Let's try to backtest 1 month (January 2019) of 5m candles using an example strategy with EMA100, as above.
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
freqtrade backtesting --timerange 20190101-20190201 --ticker-interval 5m
|
freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m
|
||||||
```
|
```
|
||||||
|
|
||||||
Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2019-12-31 15:30:00.
|
Assuming `startup_candle_count` is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from `20190101 - (100 * 5m)` - which is ~2018-12-31 15:30:00.
|
||||||
If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
|
If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
@ -248,20 +250,20 @@ minimal_roi = {
|
|||||||
|
|
||||||
While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
|
While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
|
||||||
|
|
||||||
To use times based on candle duration (ticker_interval or 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 ticket_interval 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 ...)
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
|
||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
ticker_interval = "1d"
|
timeframe = "1d"
|
||||||
ticker_interval_mins = timeframe_to_minutes(ticker_interval)
|
timeframe_mins = timeframe_to_minutes(timeframe)
|
||||||
minimal_roi = {
|
minimal_roi = {
|
||||||
"0": 0.05, # 5% for the first 3 candles
|
"0": 0.05, # 5% for the first 3 candles
|
||||||
str(ticker_interval_mins * 3)): 0.02, # 2% after 3 candles
|
str(timeframe_mins * 3)): 0.02, # 2% after 3 candles
|
||||||
str(ticker_interval_mins * 6)): 0.01, # 1% After 6 candles
|
str(timeframe_mins * 6)): 0.01, # 1% After 6 candles
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -283,14 +285,14 @@ If your exchange supports it, it's recommended to also set `"stoploss_on_exchang
|
|||||||
|
|
||||||
For more information on order_types please look [here](configuration.md#understand-order_types).
|
For more information on order_types please look [here](configuration.md#understand-order_types).
|
||||||
|
|
||||||
### Timeframe (ticker interval)
|
### Timeframe (formerly ticker interval)
|
||||||
|
|
||||||
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 buy/sell signals may work well with one timeframe, but not with the others.
|
||||||
|
|
||||||
This setting is accessible within the strategy methods as the `self.ticker_interval` attribute.
|
This setting is accessible within the strategy methods as the `self.timeframe` attribute.
|
||||||
|
|
||||||
### Metadata dict
|
### Metadata dict
|
||||||
|
|
||||||
@ -310,12 +312,17 @@ The name of the variable can be chosen at will, but should be prefixed with `cus
|
|||||||
class Awesomestrategy(IStrategy):
|
class Awesomestrategy(IStrategy):
|
||||||
# Create custom dictionary
|
# Create custom dictionary
|
||||||
cust_info = {}
|
cust_info = {}
|
||||||
|
|
||||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
# Check if the entry already exists
|
# Check if the entry already exists
|
||||||
|
if not metadata["pair"] in self._cust_info:
|
||||||
|
# Create empty entry for this pair
|
||||||
|
self._cust_info[metadata["pair"]] = {}
|
||||||
|
|
||||||
if "crosstime" in self.cust_info[metadata["pair"]:
|
if "crosstime" in self.cust_info[metadata["pair"]:
|
||||||
self.cust_info[metadata["pair"]["crosstime"] += 1
|
self.cust_info[metadata["pair"]]["crosstime"] += 1
|
||||||
else:
|
else:
|
||||||
self.cust_info[metadata["pair"]["crosstime"] = 1
|
self.cust_info[metadata["pair"]]["crosstime"] = 1
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
@ -326,15 +333,15 @@ class Awesomestrategy(IStrategy):
|
|||||||
|
|
||||||
***
|
***
|
||||||
|
|
||||||
### Additional data (informative_pairs)
|
## Additional data (informative_pairs)
|
||||||
|
|
||||||
#### Get data for non-tradeable pairs
|
### Get data for non-tradeable pairs
|
||||||
|
|
||||||
Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
|
Data for additional, informative pairs (reference pairs) can be beneficial for some strategies.
|
||||||
Ohlcv data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via `DataProvider` just as other pairs (see below).
|
OHLCV data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via `DataProvider` just as other pairs (see below).
|
||||||
These parts will **not** be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.
|
These parts will **not** be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.
|
||||||
|
|
||||||
The pairs need to be specified as tuples in the format `("pair", "interval")`, with pair as the first and time interval as the second argument.
|
The pairs need to be specified as tuples in the format `("pair", "timeframe")`, with pair as the first and timeframe as the second argument.
|
||||||
|
|
||||||
Sample:
|
Sample:
|
||||||
|
|
||||||
@ -345,15 +352,17 @@ def informative_pairs(self):
|
|||||||
]
|
]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
A full sample can be found [in the DataProvider section](#complete-data-provider-sample).
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short.
|
||||||
All intervals and all pairs can be specified as long as they are available (and active) on the used exchange.
|
All timeframes and all pairs can be specified as long as they are available (and active) on the used exchange.
|
||||||
It is however better to use resampling to longer time-intervals when 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.
|
||||||
|
|
||||||
***
|
***
|
||||||
|
|
||||||
### 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.
|
||||||
|
|
||||||
@ -361,11 +370,16 @@ All methods return `None` in case of failure (do not raise an exception).
|
|||||||
|
|
||||||
Please always check the mode of operation to select the correct method to get data (samples see below).
|
Please always check the mode of operation to select the correct method to get data (samples see below).
|
||||||
|
|
||||||
#### Possible options for DataProvider
|
!!! Warning "Hyperopt"
|
||||||
|
Dataprovider is available during hyperopt, however it can only be used in `populate_indicators()` within a strategy.
|
||||||
|
It is not available in `populate_buy()` and `populate_sell()` methods, nor in `populate_indicators()`, if this method located in the hyperopt file.
|
||||||
|
|
||||||
- [`available_pairs`](#available_pairs) - Property with tuples listing cached pairs with their intervals (pair, interval).
|
### Possible options for DataProvider
|
||||||
- [`current_whitelist()`](#current_whitelist) - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (ie. VolumePairlist)
|
|
||||||
|
- [`available_pairs`](#available_pairs) - Property with tuples listing cached pairs with their timeframe (pair, timeframe).
|
||||||
|
- [`current_whitelist()`](#current_whitelist) - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (i.e. VolumePairlist)
|
||||||
- [`get_pair_dataframe(pair, timeframe)`](#get_pair_dataframepair-timeframe) - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
|
- [`get_pair_dataframe(pair, timeframe)`](#get_pair_dataframepair-timeframe) - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
|
||||||
|
- [`get_analyzed_dataframe(pair, timeframe)`](#get_analyzed_dataframepair-timeframe) - Returns the analyzed dataframe (after calling `populate_indicators()`, `populate_buy()`, `populate_sell()`) and the time of the latest analysis.
|
||||||
- `historic_ohlcv(pair, timeframe)` - Returns historical data stored on disk.
|
- `historic_ohlcv(pair, timeframe)` - Returns historical data stored on disk.
|
||||||
- `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on the Market data structure.
|
- `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on the Market data structure.
|
||||||
- `ohlcv(pair, timeframe)` - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame.
|
- `ohlcv(pair, timeframe)` - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame.
|
||||||
@ -373,9 +387,9 @@ Please always check the mode of operation to select the correct method to get da
|
|||||||
- [`ticker(pair)`](#tickerpair) - Returns current ticker data for the pair. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#price-tickers) for more details on the Ticker data structure.
|
- [`ticker(pair)`](#tickerpair) - Returns current ticker data for the pair. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#price-tickers) for more details on the Ticker data structure.
|
||||||
- `runmode` - Property containing the current runmode.
|
- `runmode` - Property containing the current runmode.
|
||||||
|
|
||||||
#### Example Usages:
|
### Example Usages
|
||||||
|
|
||||||
#### *available_pairs*
|
### *available_pairs*
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
if self.dp:
|
if self.dp:
|
||||||
@ -383,44 +397,31 @@ if self.dp:
|
|||||||
print(f"available {pair}, {timeframe}")
|
print(f"available {pair}, {timeframe}")
|
||||||
```
|
```
|
||||||
|
|
||||||
#### *current_whitelist()*
|
### *current_whitelist()*
|
||||||
|
|
||||||
Imagine you've developed a strategy that trades the `5m` timeframe using signals generated from a `1d` timeframe on the top 10 volume pairs by volume.
|
Imagine you've developed a strategy that trades the `5m` timeframe using signals generated from a `1d` timeframe on the top 10 volume pairs by volume.
|
||||||
|
|
||||||
The strategy might look something like this:
|
The strategy might look something like this:
|
||||||
|
|
||||||
*Scan through the top 10 pairs by volume using the `VolumePairList` every 5 minutes and use a 14 day ATR to buy and sell.*
|
*Scan through the top 10 pairs by volume using the `VolumePairList` every 5 minutes and use a 14 day RSI to buy and sell.*
|
||||||
|
|
||||||
Due to the limited available data, it's very difficult to resample our `5m` candles into daily candles for use in a 14 day ATR. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least!
|
Due to the limited available data, it's very difficult to resample our `5m` candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least!
|
||||||
|
|
||||||
Since we can't resample our data we will have to use an informative pair; and since our whitelist will be dynamic we don't know which pair(s) to use.
|
Since we can't resample our data we will have to use an informative pair; and since our whitelist will be dynamic we don't know which pair(s) to use.
|
||||||
|
|
||||||
This is where calling `self.dp.current_whitelist()` comes in handy.
|
This is where calling `self.dp.current_whitelist()` comes in handy.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class SampleStrategy(IStrategy):
|
|
||||||
# strategy init stuff...
|
|
||||||
|
|
||||||
ticker_interval = '5m'
|
|
||||||
|
|
||||||
# more strategy init stuff..
|
|
||||||
|
|
||||||
def informative_pairs(self):
|
def informative_pairs(self):
|
||||||
|
|
||||||
# get access to all pairs available in whitelist.
|
# get access to all pairs available in whitelist.
|
||||||
pairs = self.dp.current_whitelist()
|
pairs = self.dp.current_whitelist()
|
||||||
# Assign tf to each pair so they can be downloaded and cached for strategy.
|
# Assign tf to each pair so they can be downloaded and cached for strategy.
|
||||||
informative_pairs = [(pair, '1d') for pair in pairs]
|
informative_pairs = [(pair, '1d') for pair in pairs]
|
||||||
return informative_pairs
|
return informative_pairs
|
||||||
|
|
||||||
def populate_indicators(self, dataframe, metadata):
|
|
||||||
# Get the informative pair
|
|
||||||
informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe='1d')
|
|
||||||
# Get the 14 day ATR.
|
|
||||||
atr = ta.ATR(informative, timeperiod=14)
|
|
||||||
# Do other stuff
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### *get_pair_dataframe(pair, timeframe)*
|
### *get_pair_dataframe(pair, timeframe)*
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
# fetch live / historical candle (OHLCV) data for the first informative pair
|
# fetch live / historical candle (OHLCV) data for the first informative pair
|
||||||
@ -431,14 +432,27 @@ if self.dp:
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning "Warning about backtesting"
|
!!! Warning "Warning about backtesting"
|
||||||
Be carefull when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
|
Be careful when using dataprovider in backtesting. `historic_ohlcv()` (and `get_pair_dataframe()`
|
||||||
for the backtesting runmode) provides the full time-range in one go,
|
for the backtesting runmode) provides the full time-range in one go,
|
||||||
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode).
|
so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode.
|
||||||
|
|
||||||
!!! Warning "Warning in hyperopt"
|
### *get_analyzed_dataframe(pair, timeframe)*
|
||||||
This option cannot currently be used during hyperopt.
|
|
||||||
|
|
||||||
#### *orderbook(pair, maximum)*
|
This method is used by freqtrade internally to determine the last signal.
|
||||||
|
It can also be used in specific callbacks to get the signal that caused the action (see [Advanced Strategy Documentation](strategy-advanced.md) for more details on available callbacks).
|
||||||
|
|
||||||
|
``` python
|
||||||
|
# fetch current dataframe
|
||||||
|
if self.dp:
|
||||||
|
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'],
|
||||||
|
timeframe=self.timeframe)
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note "No data available"
|
||||||
|
Returns an empty dataframe if the requested pair was not cached.
|
||||||
|
This should not happen when using whitelisted pairs.
|
||||||
|
|
||||||
|
### *orderbook(pair, maximum)*
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
if self.dp:
|
if self.dp:
|
||||||
@ -449,10 +463,9 @@ if self.dp:
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
The order book is not part of the historic data which means backtesting and hyperopt will not work if this
|
The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used.
|
||||||
method is used.
|
|
||||||
|
|
||||||
#### *ticker(pair)*
|
### *ticker(pair)*
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
if self.dp:
|
if self.dp:
|
||||||
@ -469,8 +482,138 @@ if self.dp:
|
|||||||
does not always fills in the `last` field (so it can be None), etc. So you need to carefully verify the ticker
|
does not always fills in the `last` field (so it can be None), etc. So you need to carefully verify the ticker
|
||||||
data returned from the exchange and add appropriate error handling / defaults.
|
data returned from the exchange and add appropriate error handling / defaults.
|
||||||
|
|
||||||
|
!!! Warning "Warning about backtesting"
|
||||||
|
This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results.
|
||||||
|
|
||||||
|
### Complete Data-provider sample
|
||||||
|
|
||||||
|
```python
|
||||||
|
from freqtrade.strategy import IStrategy, merge_informative_pair
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
class SampleStrategy(IStrategy):
|
||||||
|
# strategy init stuff...
|
||||||
|
|
||||||
|
timeframe = '5m'
|
||||||
|
|
||||||
|
# more strategy init stuff..
|
||||||
|
|
||||||
|
def informative_pairs(self):
|
||||||
|
|
||||||
|
# get access to all pairs available in whitelist.
|
||||||
|
pairs = self.dp.current_whitelist()
|
||||||
|
# Assign tf to each pair so they can be downloaded and cached for strategy.
|
||||||
|
informative_pairs = [(pair, '1d') for pair in pairs]
|
||||||
|
# Optionally Add additional "static" pairs
|
||||||
|
informative_pairs += [("ETH/USDT", "5m"),
|
||||||
|
("BTC/TUSD", "15m"),
|
||||||
|
]
|
||||||
|
return informative_pairs
|
||||||
|
|
||||||
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
if not self.dp:
|
||||||
|
# Don't do anything if DataProvider is not available.
|
||||||
|
return dataframe
|
||||||
|
|
||||||
|
inf_tf = '1d'
|
||||||
|
# Get the informative pair
|
||||||
|
informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf)
|
||||||
|
# Get the 14 day rsi
|
||||||
|
informative['rsi'] = ta.RSI(informative, timeperiod=14)
|
||||||
|
|
||||||
|
# Use the helper function merge_informative_pair to safely merge the pair
|
||||||
|
# Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair
|
||||||
|
# use ffill to have the 1d value available in every row throughout the day.
|
||||||
|
# Without this, comparisons between columns of the original and the informative pair would only work once per day.
|
||||||
|
# Full documentation of this method, see below
|
||||||
|
dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True)
|
||||||
|
|
||||||
|
# Calculate rsi of the original dataframe (5m timeframe)
|
||||||
|
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
|
||||||
|
|
||||||
|
# Do other stuff
|
||||||
|
# ...
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
|
||||||
|
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
|
||||||
|
dataframe.loc[
|
||||||
|
(
|
||||||
|
(qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
|
||||||
|
(dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30
|
||||||
|
(dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting)
|
||||||
|
),
|
||||||
|
'buy'] = 1
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
***
|
***
|
||||||
### Additional data (Wallets)
|
|
||||||
|
## Helper functions
|
||||||
|
|
||||||
|
### *merge_informative_pair()*
|
||||||
|
|
||||||
|
This method helps you merge an informative pair to a regular dataframe without lookahead bias.
|
||||||
|
It's there to help you merge the dataframe in a safe and consistent way.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
|
||||||
|
- Rename the columns for you to create unique columns
|
||||||
|
- Merge the dataframe without lookahead bias
|
||||||
|
- Forward-fill (optional)
|
||||||
|
|
||||||
|
All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
|
||||||
|
|
||||||
|
!!! Example "Column renaming"
|
||||||
|
Assuming `inf_tf = '1d'` the resulting columns will be:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe
|
||||||
|
'date_1d', 'open_1d', 'high_1d', 'low_1d', 'close_1d', 'rsi_1d' # from the informative dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
??? Example "Column renaming - 1h"
|
||||||
|
Assuming `inf_tf = '1h'` the resulting columns will be:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe
|
||||||
|
'date_1h', 'open_1h', 'high_1h', 'low_1h', 'close_1h', 'rsi_1h' # from the informative dataframe
|
||||||
|
```
|
||||||
|
|
||||||
|
??? Example "Custom implementation"
|
||||||
|
A custom implementation for this is possible, and can be done as follows:
|
||||||
|
|
||||||
|
``` python
|
||||||
|
|
||||||
|
# Shift date by 1 candle
|
||||||
|
# This is necessary since the data is always the "open date"
|
||||||
|
# and a 15m candle starting at 12:15 should not know the close of the 1h candle from 12:00 to 13:00
|
||||||
|
minutes = timeframe_to_minutes(inf_tf)
|
||||||
|
# Only do this if the timeframes are different:
|
||||||
|
informative['date_merge'] = informative["date"] + pd.to_timedelta(minutes, 'm')
|
||||||
|
|
||||||
|
# Rename columns to be unique
|
||||||
|
informative.columns = [f"{col}_{inf_tf}" for col in informative.columns]
|
||||||
|
# Assuming inf_tf = '1d' - then the columns will now be:
|
||||||
|
# date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d
|
||||||
|
|
||||||
|
# Combine the 2 dataframes
|
||||||
|
# all indicators on the informative sample MUST be calculated before this point
|
||||||
|
dataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_merge_{inf_tf}', how='left')
|
||||||
|
# FFill to have the 1d value available in every row throughout the day.
|
||||||
|
# Without this, comparisons would only work once per day.
|
||||||
|
dataframe = dataframe.ffill()
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Warning "Informative timeframe < timeframe"
|
||||||
|
Using informative timeframes smaller than the dataframe timeframe is not recommended with this method, as it will not use any of the additional information this would provide.
|
||||||
|
To use the more detailed information properly, more advanced methods should be applied (which are out of scope for freqtrade documentation, as it'll depend on the respective need).
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
## Additional data (Wallets)
|
||||||
|
|
||||||
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
The strategy provides access to the `Wallets` object. This contains the current balances on the exchange.
|
||||||
|
|
||||||
@ -486,14 +629,15 @@ if self.wallets:
|
|||||||
total_eth = self.wallets.get_total('ETH')
|
total_eth = self.wallets.get_total('ETH')
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Possible options for Wallets
|
### Possible options for Wallets
|
||||||
|
|
||||||
- `get_free(asset)` - currently available balance to trade
|
- `get_free(asset)` - currently available balance to trade
|
||||||
- `get_used(asset)` - currently tied up balance (open orders)
|
- `get_used(asset)` - currently tied up balance (open orders)
|
||||||
- `get_total(asset)` - total available balance - sum of the 2 above
|
- `get_total(asset)` - total available balance - sum of the 2 above
|
||||||
|
|
||||||
***
|
***
|
||||||
### Additional data (Trades)
|
|
||||||
|
## Additional data (Trades)
|
||||||
|
|
||||||
A history of Trades can be retrieved in the strategy by querying the database.
|
A history of Trades can be retrieved in the strategy by querying the database.
|
||||||
|
|
||||||
@ -539,30 +683,30 @@ Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of
|
|||||||
!!! Warning
|
!!! Warning
|
||||||
Trade history is not available during backtesting or hyperopt.
|
Trade history is not available during backtesting or hyperopt.
|
||||||
|
|
||||||
### Prevent trades from happening for a specific pair
|
## Prevent trades from happening for a specific pair
|
||||||
|
|
||||||
Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair.
|
Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair.
|
||||||
|
|
||||||
Locked pairs will show the message `Pair <pair> is currently locked.`.
|
Locked pairs will show the message `Pair <pair> is currently locked.`.
|
||||||
|
|
||||||
#### Locking pairs from within the strategy
|
### Locking pairs from within the strategy
|
||||||
|
|
||||||
Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).
|
Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).
|
||||||
|
|
||||||
Freqtrade has an easy method to do this from within the strategy, by calling `self.lock_pair(pair, until)`.
|
Freqtrade has an easy method to do this from within the strategy, by calling `self.lock_pair(pair, until, [reason])`.
|
||||||
`until` must be a datetime object in the future, after which trading will be reenabled for that pair.
|
`until` must be a datetime object in the future, after which trading will be re-enabled for that pair, while `reason` is an optional string detailing why the pair was locked.
|
||||||
|
|
||||||
Locks can also be lifted manually, by calling `self.unlock_pair(pair)`.
|
Locks can also be lifted manually, by calling `self.unlock_pair(pair)`.
|
||||||
|
|
||||||
To verify if a pair is currently locked, use `self.is_pair_locked(pair)`.
|
To verify if a pair is currently locked, use `self.is_pair_locked(pair)`.
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Locked pairs are not persisted, so a restart of the bot, or calling `/reload_conf` will reset locked pairs.
|
Locked pairs will always be rounded up to the next candle. So assuming a `5m` timeframe, a lock with `until` set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished.
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
Locking pairs is not functioning during backtesting.
|
Locking pairs is not available during backtesting.
|
||||||
|
|
||||||
##### Pair locking example
|
#### Pair locking example
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
from freqtrade.persistence import Trade
|
from freqtrade.persistence import Trade
|
||||||
@ -584,7 +728,7 @@ if self.config['runmode'].value in ('live', 'dry_run'):
|
|||||||
self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12))
|
self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12))
|
||||||
```
|
```
|
||||||
|
|
||||||
### 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_buy_trend()` or `populate_sell_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.
|
||||||
@ -608,36 +752,7 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|||||||
|
|
||||||
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
||||||
|
|
||||||
### Specify custom strategy location
|
## Common mistakes when developing strategies
|
||||||
|
|
||||||
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory
|
|
||||||
```
|
|
||||||
|
|
||||||
### Derived strategies
|
|
||||||
|
|
||||||
The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
|
|
||||||
|
|
||||||
``` python
|
|
||||||
class MyAwesomeStrategy(IStrategy):
|
|
||||||
...
|
|
||||||
stoploss = 0.13
|
|
||||||
trailing_stop = False
|
|
||||||
# All other attributes and methods are here as they
|
|
||||||
# should be in any custom strategy...
|
|
||||||
...
|
|
||||||
|
|
||||||
class MyAwesomeStrategy2(MyAwesomeStrategy):
|
|
||||||
# Override something
|
|
||||||
stoploss = 0.08
|
|
||||||
trailing_stop = True
|
|
||||||
```
|
|
||||||
|
|
||||||
Both attributes and methods may be overriden, altering behavior of the original strategy in a way you need.
|
|
||||||
|
|
||||||
### Common mistakes when developing strategies
|
|
||||||
|
|
||||||
Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future.
|
Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future.
|
||||||
This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
|
This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
|
||||||
@ -649,14 +764,12 @@ The following lists some common patterns which should be avoided to prevent frus
|
|||||||
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
- don't use `dataframe['volume'].mean()`. This uses the full DataFrame for backtesting, including data from the future. Use `dataframe['volume'].rolling(<window>).mean()` instead
|
||||||
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
- don't use `.resample('1h')`. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use `.resample('1h', label='right')` instead.
|
||||||
|
|
||||||
### Further strategy ideas
|
## Further strategy ideas
|
||||||
|
|
||||||
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
To get additional Ideas for strategies, head over to our [strategy repository](https://github.com/freqtrade/freqtrade-strategies). Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk.
|
||||||
Feel free to use any of them as inspiration for your own strategies.
|
Feel free to use any of them as inspiration for your own strategies.
|
||||||
We're happy to accept Pull Requests containing new Strategies to that repo.
|
We're happy to accept Pull Requests containing new Strategies to that repo.
|
||||||
|
|
||||||
We also got a *strategy-sharing* channel in our [Slack community](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) which is a great place to get and/or share ideas.
|
|
||||||
|
|
||||||
## Next step
|
## Next step
|
||||||
|
|
||||||
Now you have a perfect strategy you probably want to backtest it.
|
Now you have a perfect strategy you probably want to backtest it.
|
||||||
|
@ -18,7 +18,7 @@ config = Configuration.from_files([])
|
|||||||
# config = Configuration.from_files(["config.json"])
|
# config = Configuration.from_files(["config.json"])
|
||||||
|
|
||||||
# Define some constants
|
# Define some constants
|
||||||
config["ticker_interval"] = "5m"
|
config["timeframe"] = "5m"
|
||||||
# Name of the strategy class
|
# Name of the strategy class
|
||||||
config["strategy"] = "SampleStrategy"
|
config["strategy"] = "SampleStrategy"
|
||||||
# Location of the data
|
# Location of the data
|
||||||
@ -33,7 +33,7 @@ pair = "BTC_USDT"
|
|||||||
from freqtrade.data.history import load_pair_history
|
from freqtrade.data.history import load_pair_history
|
||||||
|
|
||||||
candles = load_pair_history(datadir=data_location,
|
candles = load_pair_history(datadir=data_location,
|
||||||
timeframe=config["ticker_interval"],
|
timeframe=config["timeframe"],
|
||||||
pair=pair)
|
pair=pair)
|
||||||
|
|
||||||
# Confirm success
|
# Confirm success
|
||||||
@ -85,10 +85,44 @@ Analyze a trades dataframe (also used below for plotting)
|
|||||||
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from freqtrade.data.btanalysis import load_backtest_data
|
from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats
|
||||||
|
|
||||||
# Load backtest results
|
# if backtest_dir points to a directory, it'll automatically load the last backtest file.
|
||||||
trades = load_backtest_data(config["user_data_dir"] / "backtest_results/backtest-result.json")
|
backtest_dir = config["user_data_dir"] / "backtest_results"
|
||||||
|
# backtest_dir can also point to a specific file
|
||||||
|
# backtest_dir = config["user_data_dir"] / "backtest_results/backtest-result-2020-07-01_20-04-22.json"
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# You can get the full backtest statistics by using the following command.
|
||||||
|
# This contains all information used to generate the backtest result.
|
||||||
|
stats = load_backtest_stats(backtest_dir)
|
||||||
|
|
||||||
|
strategy = 'SampleStrategy'
|
||||||
|
# All statistics are available per strategy, so if `--strategy-list` was used during backtest, this will be reflected here as well.
|
||||||
|
# Example usages:
|
||||||
|
print(stats['strategy'][strategy]['results_per_pair'])
|
||||||
|
# Get pairlist used for this backtest
|
||||||
|
print(stats['strategy'][strategy]['pairlist'])
|
||||||
|
# Get market change (average change of all pairs from start to end of the backtest period)
|
||||||
|
print(stats['strategy'][strategy]['market_change'])
|
||||||
|
# Maximum drawdown ()
|
||||||
|
print(stats['strategy'][strategy]['max_drawdown'])
|
||||||
|
# Maximum drawdown start and end
|
||||||
|
print(stats['strategy'][strategy]['drawdown_start'])
|
||||||
|
print(stats['strategy'][strategy]['drawdown_end'])
|
||||||
|
|
||||||
|
|
||||||
|
# Get strategy comparison (only relevant if multiple strategies were compared)
|
||||||
|
print(stats['strategy_comparison'])
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Load backtested trades as dataframe
|
||||||
|
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")["sell_reason"].value_counts()
|
||||||
|
@ -9,7 +9,7 @@ Telegram user id.
|
|||||||
|
|
||||||
Start a chat with the [Telegram BotFather](https://telegram.me/BotFather)
|
Start a chat with the [Telegram BotFather](https://telegram.me/BotFather)
|
||||||
|
|
||||||
Send the message `/newbot`.
|
Send the message `/newbot`.
|
||||||
|
|
||||||
*BotFather response:*
|
*BotFather response:*
|
||||||
|
|
||||||
@ -35,40 +35,126 @@ Copy the API Token (`22222222:APITOKEN` in the above example) and keep use it fo
|
|||||||
|
|
||||||
Don't forget to start the conversation with your bot, by clicking `/START` button
|
Don't forget to start the conversation with your bot, by clicking `/START` button
|
||||||
|
|
||||||
### 2. Get your user id
|
### 2. Telegram user_id
|
||||||
|
|
||||||
|
#### Get your user id
|
||||||
|
|
||||||
Talk to the [userinfobot](https://telegram.me/userinfobot)
|
Talk to the [userinfobot](https://telegram.me/userinfobot)
|
||||||
|
|
||||||
Get your "Id", you will use it for the config parameter `chat_id`.
|
Get your "Id", you will use it for the config parameter `chat_id`.
|
||||||
|
|
||||||
|
#### Use Group id
|
||||||
|
|
||||||
|
You can use bots in telegram groups by just adding them to the group. You can find the group id by first adding a [RawDataBot](https://telegram.me/rawdatabot) to your group. The Group id is shown as id in the `"chat"` section, which the RawDataBot will send to you:
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"chat":{
|
||||||
|
"id":-1001332619709
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For the Freqtrade configuration, you can then use the the full value (including `-` if it's there) as string:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"chat_id": "-1001332619709"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Control telegram noise
|
||||||
|
|
||||||
|
Freqtrade provides means to control the verbosity of your telegram bot.
|
||||||
|
Each setting has the following possible values:
|
||||||
|
|
||||||
|
* `on` - Messages will be sent, and user will be notified.
|
||||||
|
* `silent` - Message will be sent, Notification will be without sound / vibration.
|
||||||
|
* `off` - Skip sending a message-type all together.
|
||||||
|
|
||||||
|
Example configuration showing the different settings:
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"telegram": {
|
||||||
|
"enabled": true,
|
||||||
|
"token": "your_telegram_token",
|
||||||
|
"chat_id": "your_telegram_chat_id",
|
||||||
|
"notification_settings": {
|
||||||
|
"status": "silent",
|
||||||
|
"warning": "on",
|
||||||
|
"startup": "off",
|
||||||
|
"buy": "silent",
|
||||||
|
"sell": "on",
|
||||||
|
"buy_cancel": "silent",
|
||||||
|
"sell_cancel": "on"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
## Create a custom keyboard (command shortcut buttons)
|
||||||
|
|
||||||
|
Telegram allows us to create a custom keyboard with buttons for commands.
|
||||||
|
The default custom keyboard looks like this.
|
||||||
|
|
||||||
|
```python
|
||||||
|
[
|
||||||
|
["/daily", "/profit", "/balance"], # row 1, 3 commands
|
||||||
|
["/status", "/status table", "/performance"], # row 2, 3 commands
|
||||||
|
["/count", "/start", "/stop", "/help"] # row 3, 4 commands
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
You can create your own keyboard in `config.json`:
|
||||||
|
|
||||||
|
``` json
|
||||||
|
"telegram": {
|
||||||
|
"enabled": true,
|
||||||
|
"token": "your_telegram_token",
|
||||||
|
"chat_id": "your_telegram_chat_id",
|
||||||
|
"keyboard": [
|
||||||
|
["/daily", "/stats", "/balance", "/profit"],
|
||||||
|
["/status table", "/performance"],
|
||||||
|
["/reload_config", "/count", "/logs"]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note "Supported Commands"
|
||||||
|
Only the following commands are allowed. Command arguments are not supported!
|
||||||
|
|
||||||
|
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopbuy`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
|
||||||
|
|
||||||
## Telegram commands
|
## Telegram commands
|
||||||
|
|
||||||
Per default, the Telegram bot shows predefined commands. Some commands
|
Per default, the Telegram bot shows predefined commands. Some commands
|
||||||
are only available by sending them to the bot. The table below list the
|
are only available by sending them to the bot. The table below list the
|
||||||
official commands. You can ask at any moment for help with `/help`.
|
official commands. You can ask at any moment for help with `/help`.
|
||||||
|
|
||||||
| Command | Default | Description |
|
| Command | Description |
|
||||||
|----------|---------|-------------|
|
|----------|-------------|
|
||||||
| `/start` | | Starts the trader
|
| `/start` | Starts the trader
|
||||||
| `/stop` | | Stops the trader
|
| `/stop` | Stops the trader
|
||||||
| `/stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
| `/stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
|
||||||
| `/reload_conf` | | Reloads the configuration file
|
| `/reload_config` | Reloads the configuration file
|
||||||
| `/show_config` | | Shows part of the current configuration with relevant settings to operation
|
| `/show_config` | Shows part of the current configuration with relevant settings to operation
|
||||||
| `/status` | | Lists all open trades
|
| `/logs [limit]` | Show last log messages.
|
||||||
| `/status table` | | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
|
| `/status` | Lists all open trades
|
||||||
| `/count` | | Displays number of trades used and available
|
| `/status table` | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
|
||||||
| `/profit` | | Display a summary of your profit/loss from close trades and some stats about your performance
|
| `/trades [limit]` | List all recently closed trades in a table format.
|
||||||
| `/forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
| `/delete <trade_id>` | Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange.
|
||||||
| `/forcesell all` | | Instantly sells all open trades (Ignoring `minimum_roi`).
|
| `/count` | Displays number of trades used and available
|
||||||
| `/forcebuy <pair> [rate]` | | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
| `/locks` | Show currently locked pairs.
|
||||||
| `/performance` | | Show performance of each finished trade grouped by pair
|
| `/profit` | Display a summary of your profit/loss from close trades and some stats about your performance
|
||||||
| `/balance` | | Show account balance per currency
|
| `/forcesell <trade_id>` | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||||
| `/daily <n>` | 7 | Shows profit or loss per day, over the last n days
|
| `/forcesell all` | Instantly sells all open trades (Ignoring `minimum_roi`).
|
||||||
| `/whitelist` | | Show the current whitelist
|
| `/forcebuy <pair> [rate]` | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True)
|
||||||
| `/blacklist [pair]` | | Show the current blacklist, or adds a pair to the blacklist.
|
| `/performance` | Show performance of each finished trade grouped by pair
|
||||||
| `/edge` | | Show validated pairs by Edge if it is enabled.
|
| `/balance` | Show account balance per currency
|
||||||
| `/help` | | Show help message
|
| `/daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7)
|
||||||
| `/version` | | Show version
|
| `/stats` | Shows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells
|
||||||
|
| `/whitelist` | Show the current whitelist
|
||||||
|
| `/blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||||
|
| `/edge` | Show validated pairs by Edge if it is enabled.
|
||||||
|
| `/help` | Show help message
|
||||||
|
| `/version` | Show version
|
||||||
|
|
||||||
## Telegram commands in action
|
## Telegram commands in action
|
||||||
|
|
||||||
@ -85,14 +171,14 @@ Below, example of Telegram message you will receive for each command.
|
|||||||
|
|
||||||
### /stopbuy
|
### /stopbuy
|
||||||
|
|
||||||
> **status:** `Setting max_open_trades to 0. Run /reload_conf to reset.`
|
> **status:** `Setting max_open_trades to 0. Run /reload_config to reset.`
|
||||||
|
|
||||||
Prevents the bot from opening new trades by temporarily setting "max_open_trades" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...).
|
Prevents the bot from opening new trades by temporarily setting "max_open_trades" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...).
|
||||||
|
|
||||||
After this, give the bot time to close off open trades (can be checked via `/status table`).
|
After this, give the bot time to close off open trades (can be checked via `/status table`).
|
||||||
Once all positions are sold, run `/stop` to completely stop the bot.
|
Once all positions are sold, run `/stop` to completely stop the bot.
|
||||||
|
|
||||||
`/reload_conf` resets "max_open_trades" to the value set in the configuration and resets this command.
|
`/reload_config` resets "max_open_trades" to the value set in the configuration and resets this command.
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
|
||||||
@ -113,6 +199,7 @@ For each open trade, the bot will send you the following message.
|
|||||||
### /status table
|
### /status table
|
||||||
|
|
||||||
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 Pair Since Profit
|
||||||
---- -------- ------- --------
|
---- -------- ------- --------
|
||||||
@ -123,6 +210,7 @@ Return the status of all open trades in a table format.
|
|||||||
### /count
|
### /count
|
||||||
|
|
||||||
Return the number of trades used and available.
|
Return the number of trades used and available.
|
||||||
|
|
||||||
```
|
```
|
||||||
current max
|
current max
|
||||||
--------- -----
|
--------- -----
|
||||||
@ -156,7 +244,7 @@ Return a summary of your profit/loss and performance.
|
|||||||
|
|
||||||
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
Note that for this to work, `forcebuy_enable` needs to be set to true.
|
||||||
|
|
||||||
[More details](configuration.md/#understand-forcebuy_enable)
|
[More details](configuration.md#understand-forcebuy_enable)
|
||||||
|
|
||||||
### /performance
|
### /performance
|
||||||
|
|
||||||
@ -208,15 +296,15 @@ Shows the current whitelist
|
|||||||
|
|
||||||
Shows the current blacklist.
|
Shows the current blacklist.
|
||||||
If Pair is set, then this pair will be added to the pairlist.
|
If Pair is set, then this pair will be added to the pairlist.
|
||||||
Also supports multiple pairs, seperated by a space.
|
Also supports multiple pairs, separated by a space.
|
||||||
Use `/reload_conf` to reset the blacklist.
|
Use `/reload_config` to reset the blacklist.
|
||||||
|
|
||||||
> Using blacklist `StaticPairList` with 2 pairs
|
> Using blacklist `StaticPairList` with 2 pairs
|
||||||
>`DODGE/BTC`, `HOT/BTC`.
|
>`DODGE/BTC`, `HOT/BTC`.
|
||||||
|
|
||||||
### /edge
|
### /edge
|
||||||
|
|
||||||
Shows pairs validated by Edge along with their corresponding winrate, expectancy and stoploss values.
|
Shows pairs validated by Edge along with their corresponding win-rate, expectancy and stoploss values.
|
||||||
|
|
||||||
> **Edge only validated following pairs:**
|
> **Edge only validated following pairs:**
|
||||||
```
|
```
|
||||||
|
31
docs/updating.md
Normal file
31
docs/updating.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# How to update
|
||||||
|
|
||||||
|
To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.
|
||||||
|
|
||||||
|
## docker-compose
|
||||||
|
|
||||||
|
!!! Note "Legacy installations using the `master` image"
|
||||||
|
We're switching from master to stable for the release Images - please adjust your docker-file and replace `freqtradeorg/freqtrade:master` with `freqtradeorg/freqtrade:stable`
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
docker-compose pull
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installation via setup script
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
./setup.sh --update
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure to run this command with your virtual environment disabled!
|
||||||
|
|
||||||
|
## Plain native installation
|
||||||
|
|
||||||
|
Please ensure that you're also updating dependencies - otherwise things might break without you noticing.
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
git pull
|
||||||
|
pip install -U -r requirements.txt
|
||||||
|
```
|
@ -62,7 +62,7 @@ $ freqtrade new-config --config config_binance.json
|
|||||||
? Please insert your stake currency: BTC
|
? Please insert your stake currency: BTC
|
||||||
? Please insert your stake amount: 0.05
|
? Please insert your stake amount: 0.05
|
||||||
? Please insert max_open_trades (Integer or 'unlimited'): 3
|
? Please insert max_open_trades (Integer or 'unlimited'): 3
|
||||||
? Please insert your timeframe (ticker interval): 5m
|
? Please insert your desired timeframe (e.g. 5m): 5m
|
||||||
? Please insert your display Currency (for reporting): USD
|
? Please insert your display Currency (for reporting): USD
|
||||||
? Select exchange binance
|
? Select exchange binance
|
||||||
? Do you want to enable Telegram? No
|
? Do you want to enable Telegram? No
|
||||||
@ -423,7 +423,7 @@ freqtrade test-pairlist --config config.json --quote USDT BTC
|
|||||||
|
|
||||||
## List Hyperopt results
|
## List Hyperopt results
|
||||||
|
|
||||||
You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the `hyperopt-list` subcommand.
|
You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the `hyperopt-list` sub-command.
|
||||||
|
|
||||||
```
|
```
|
||||||
usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
@ -433,9 +433,10 @@ usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
|||||||
[--max-avg-time FLOAT] [--min-avg-profit FLOAT]
|
[--max-avg-time FLOAT] [--min-avg-profit FLOAT]
|
||||||
[--max-avg-profit FLOAT]
|
[--max-avg-profit FLOAT]
|
||||||
[--min-total-profit FLOAT]
|
[--min-total-profit FLOAT]
|
||||||
[--max-total-profit FLOAT] [--no-color]
|
[--max-total-profit FLOAT]
|
||||||
[--print-json] [--no-details]
|
[--min-objective FLOAT] [--max-objective FLOAT]
|
||||||
[--export-csv FILE]
|
[--no-color] [--print-json] [--no-details]
|
||||||
|
[--hyperopt-filename PATH] [--export-csv FILE]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
@ -443,20 +444,27 @@ optional arguments:
|
|||||||
--profitable Select only profitable epochs.
|
--profitable Select only profitable epochs.
|
||||||
--min-trades INT Select epochs with more than INT trades.
|
--min-trades INT Select epochs with more than INT trades.
|
||||||
--max-trades INT Select epochs with less than INT trades.
|
--max-trades INT Select epochs with less than INT trades.
|
||||||
--min-avg-time FLOAT Select epochs on above average time.
|
--min-avg-time FLOAT Select epochs above average time.
|
||||||
--max-avg-time FLOAT Select epochs on under average time.
|
--max-avg-time FLOAT Select epochs below average time.
|
||||||
--min-avg-profit FLOAT
|
--min-avg-profit FLOAT
|
||||||
Select epochs on above average profit.
|
Select epochs above average profit.
|
||||||
--max-avg-profit FLOAT
|
--max-avg-profit FLOAT
|
||||||
Select epochs on below average profit.
|
Select epochs below average profit.
|
||||||
--min-total-profit FLOAT
|
--min-total-profit FLOAT
|
||||||
Select epochs on above total profit.
|
Select epochs above total profit.
|
||||||
--max-total-profit FLOAT
|
--max-total-profit FLOAT
|
||||||
Select epochs on below total profit.
|
Select epochs below total profit.
|
||||||
|
--min-objective FLOAT
|
||||||
|
Select epochs above objective.
|
||||||
|
--max-objective FLOAT
|
||||||
|
Select epochs below objective.
|
||||||
--no-color Disable colorization of hyperopt results. May be
|
--no-color Disable colorization of hyperopt results. May be
|
||||||
useful if you are redirecting output to a file.
|
useful if you are redirecting output to a file.
|
||||||
--print-json Print best result detailization in JSON format.
|
--print-json Print output in JSON format.
|
||||||
--no-details Do not print best epoch details.
|
--no-details Do not print best epoch details.
|
||||||
|
--hyperopt-filename FILENAME
|
||||||
|
Hyperopt result filename.Example: `--hyperopt-
|
||||||
|
filename=hyperopt_results_2020-09-27_16-20-48.pickle`
|
||||||
--export-csv FILE Export to CSV-File. This will disable table print.
|
--export-csv FILE Export to CSV-File. This will disable table print.
|
||||||
Example: --export-csv hyperopt.csv
|
Example: --export-csv hyperopt.csv
|
||||||
|
|
||||||
@ -476,7 +484,11 @@ Common arguments:
|
|||||||
--userdir PATH, --user-data-dir PATH
|
--userdir PATH, --user-data-dir PATH
|
||||||
Path to userdata directory.
|
Path to userdata directory.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
`hyperopt-list` will automatically use the latest available hyperopt results file.
|
||||||
|
You can override this using the `--hyperopt-filename` argument, and specify another, available filename (without path!).
|
||||||
|
|
||||||
### Examples
|
### Examples
|
||||||
|
|
||||||
List all results, print details of the best result at the end:
|
List all results, print details of the best result at the end:
|
||||||
@ -497,17 +509,41 @@ You can show the details of any hyperoptimization epoch previously evaluated by
|
|||||||
usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
[-d PATH] [--userdir PATH] [--best]
|
[-d PATH] [--userdir PATH] [--best]
|
||||||
[--profitable] [-n INT] [--print-json]
|
[--profitable] [-n INT] [--print-json]
|
||||||
[--no-header]
|
[--hyperopt-filename PATH] [--no-header]
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--best Select only best epochs.
|
--best Select only best epochs.
|
||||||
--profitable Select only profitable epochs.
|
--profitable Select only profitable epochs.
|
||||||
-n INT, --index INT Specify the index of the epoch to print details for.
|
-n INT, --index INT Specify the index of the epoch to print details for.
|
||||||
--print-json Print best result detailization in JSON format.
|
--print-json Print output in JSON format.
|
||||||
|
--hyperopt-filename FILENAME
|
||||||
|
Hyperopt result filename.Example: `--hyperopt-
|
||||||
|
filename=hyperopt_results_2020-09-27_16-20-48.pickle`
|
||||||
--no-header Do not print epoch details header.
|
--no-header Do not print epoch details header.
|
||||||
|
|
||||||
|
Common arguments:
|
||||||
|
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||||
|
--logfile FILE Log to the file specified. Special values are:
|
||||||
|
'syslog', 'journald'. See the documentation for more
|
||||||
|
details.
|
||||||
|
-V, --version show program's version number and exit
|
||||||
|
-c PATH, --config PATH
|
||||||
|
Specify configuration file (default:
|
||||||
|
`userdir/config.json` or `config.json` whichever
|
||||||
|
exists). Multiple --config options may be used. Can be
|
||||||
|
set to `-` to read config from stdin.
|
||||||
|
-d PATH, --datadir PATH
|
||||||
|
Path to directory with historical backtesting data.
|
||||||
|
--userdir PATH, --user-data-dir PATH
|
||||||
|
Path to userdata directory.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
`hyperopt-show` will automatically use the latest available hyperopt results file.
|
||||||
|
You can override this using the `--hyperopt-filename` argument, and specify another, available filename (without path!).
|
||||||
|
|
||||||
### Examples
|
### Examples
|
||||||
|
|
||||||
Print details for the epoch 168 (the number of the epoch is shown by the `hyperopt-list` subcommand or by Hyperopt itself during hyperoptimization run):
|
Print details for the epoch 168 (the number of the epoch is shown by the `hyperopt-list` subcommand or by Hyperopt itself during hyperoptimization run):
|
||||||
|
@ -47,6 +47,7 @@ Different payloads can be configured for different events. Not all fields are ne
|
|||||||
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. Parameters are filled using string.format.
|
The fields in `webhook.webhookbuy` are filled when the bot executes a buy. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
|
* `trade_id`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
* `limit`
|
* `limit`
|
||||||
@ -63,6 +64,7 @@ Possible parameters are:
|
|||||||
The fields in `webhook.webhookbuycancel` are filled when the bot cancels a buy order. Parameters are filled using string.format.
|
The fields in `webhook.webhookbuycancel` are filled when the bot cancels a buy order. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
|
* `trade_id`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
* `limit`
|
* `limit`
|
||||||
@ -79,6 +81,7 @@ Possible parameters are:
|
|||||||
The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
|
The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
|
* `trade_id`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
* `gain`
|
* `gain`
|
||||||
@ -100,6 +103,7 @@ Possible parameters are:
|
|||||||
The fields in `webhook.webhooksellcancel` are filled when the bot cancels a sell order. Parameters are filled using string.format.
|
The fields in `webhook.webhooksellcancel` are filled when the bot cancels a sell order. Parameters are filled using string.format.
|
||||||
Possible parameters are:
|
Possible parameters are:
|
||||||
|
|
||||||
|
* `trade_id`
|
||||||
* `exchange`
|
* `exchange`
|
||||||
* `pair`
|
* `pair`
|
||||||
* `gain`
|
* `gain`
|
||||||
|
57
docs/windows_installation.md
Normal file
57
docs/windows_installation.md
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
We **strongly** recommend that Windows users use [Docker](docker.md) as this will work much easier and smoother (also more secure).
|
||||||
|
|
||||||
|
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work.
|
||||||
|
Otherwise, try the instructions below.
|
||||||
|
|
||||||
|
## Install freqtrade manually
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
|
||||||
|
|
||||||
|
!!! Hint
|
||||||
|
Using the [Anaconda Distribution](https://www.anaconda.com/distribution/) under Windows can greatly help with installation problems. Check out the [Anaconda installation section](installation.md#Anaconda) in this document for more information.
|
||||||
|
|
||||||
|
### 1. Clone the git repository
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/freqtrade/freqtrade.git
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Install ta-lib
|
||||||
|
|
||||||
|
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||||
|
|
||||||
|
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which needs to be downloaded and installed using `pip install TA_Lib‑0.4.19‑cp38‑cp38‑win_amd64.whl` (make sure to use the version matching your python version)
|
||||||
|
|
||||||
|
Freqtrade provides these dependencies for the latest 2 Python versions (3.7 and 3.8) and for 64bit Windows.
|
||||||
|
Other versions must be downloaded from the above link.
|
||||||
|
|
||||||
|
``` powershell
|
||||||
|
cd \path\freqtrade
|
||||||
|
python -m venv .env
|
||||||
|
.env\Scripts\activate.ps1
|
||||||
|
# optionally install ta-lib from wheel
|
||||||
|
# Eventually adjust the below filename to match the downloaded wheel
|
||||||
|
pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install -e .
|
||||||
|
freqtrade
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! Note "Use Powershell"
|
||||||
|
The above installation script assumes you're using powershell on a 64bit windows.
|
||||||
|
Commands for the legacy CMD windows console may differ.
|
||||||
|
|
||||||
|
> Thanks [Owdr](https://github.com/Owdr) for the commands. Source: [Issue #222](https://github.com/freqtrade/freqtrade/issues/222)
|
||||||
|
|
||||||
|
### Error during installation on Windows
|
||||||
|
|
||||||
|
``` bash
|
||||||
|
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
|
||||||
|
```
|
||||||
|
|
||||||
|
Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
|
||||||
|
|
||||||
|
The easiest way is to download install Microsoft Visual Studio Community [here](https://visualstudio.microsoft.com/downloads/) and make sure to install "Common Tools for Visual C++" to enable building C code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or [docker](docker.md) first.
|
||||||
|
|
||||||
|
---
|
@ -4,7 +4,7 @@ channels:
|
|||||||
- conda-forge
|
- conda-forge
|
||||||
dependencies:
|
dependencies:
|
||||||
# Required for app
|
# Required for app
|
||||||
- python>=3.6
|
- python>=3.7
|
||||||
- pip
|
- pip
|
||||||
- wheel
|
- wheel
|
||||||
- numpy
|
- numpy
|
||||||
|
@ -3,10 +3,11 @@
|
|||||||
__main__.py for Freqtrade
|
__main__.py for Freqtrade
|
||||||
To launch Freqtrade as a module
|
To launch Freqtrade as a module
|
||||||
|
|
||||||
> python -m freqtrade (with Python >= 3.6)
|
> python -m freqtrade (with Python >= 3.7)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from freqtrade import main
|
from freqtrade import main
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main.main()
|
main.main()
|
||||||
|
@ -8,22 +8,15 @@ Note: Be careful with file-scoped imports in these subfiles.
|
|||||||
"""
|
"""
|
||||||
from freqtrade.commands.arguments import Arguments
|
from freqtrade.commands.arguments import Arguments
|
||||||
from freqtrade.commands.build_config_commands import start_new_config
|
from freqtrade.commands.build_config_commands import start_new_config
|
||||||
from freqtrade.commands.data_commands import (start_convert_data,
|
from freqtrade.commands.data_commands import (start_convert_data, start_download_data,
|
||||||
start_download_data)
|
start_list_data)
|
||||||
from freqtrade.commands.deploy_commands import (start_create_userdir,
|
from freqtrade.commands.deploy_commands import (start_create_userdir, start_new_hyperopt,
|
||||||
start_new_hyperopt,
|
|
||||||
start_new_strategy)
|
start_new_strategy)
|
||||||
from freqtrade.commands.hyperopt_commands import (start_hyperopt_list,
|
from freqtrade.commands.hyperopt_commands import start_hyperopt_list, start_hyperopt_show
|
||||||
start_hyperopt_show)
|
from freqtrade.commands.list_commands import (start_list_exchanges, start_list_hyperopts,
|
||||||
from freqtrade.commands.list_commands import (start_list_exchanges,
|
start_list_markets, start_list_strategies,
|
||||||
start_list_hyperopts,
|
start_list_timeframes, start_show_trades)
|
||||||
start_list_markets,
|
from freqtrade.commands.optimize_commands import start_backtesting, start_edge, start_hyperopt
|
||||||
start_list_strategies,
|
|
||||||
start_list_timeframes,
|
|
||||||
start_show_trades)
|
|
||||||
from freqtrade.commands.optimize_commands import (start_backtesting,
|
|
||||||
start_edge, start_hyperopt)
|
|
||||||
from freqtrade.commands.pairlist_commands import start_test_pairlist
|
from freqtrade.commands.pairlist_commands import start_test_pairlist
|
||||||
from freqtrade.commands.plot_commands import (start_plot_dataframe,
|
from freqtrade.commands.plot_commands import start_plot_dataframe, start_plot_profit
|
||||||
start_plot_profit)
|
|
||||||
from freqtrade.commands.trade_commands import start_trading
|
from freqtrade.commands.trade_commands import start_trading
|
||||||
|
@ -9,24 +9,27 @@ from typing import Any, Dict, List, Optional
|
|||||||
from freqtrade.commands.cli_options import AVAILABLE_CLI_OPTIONS
|
from freqtrade.commands.cli_options import AVAILABLE_CLI_OPTIONS
|
||||||
from freqtrade.constants import DEFAULT_CONFIG
|
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"]
|
||||||
|
|
||||||
ARGS_TRADE = ["db_url", "sd_notify", "dry_run"]
|
ARGS_TRADE = ["db_url", "sd_notify", "dry_run"]
|
||||||
|
|
||||||
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
ARGS_COMMON_OPTIMIZE = ["timeframe", "timerange", "dataformat_ohlcv",
|
||||||
"max_open_trades", "stake_amount", "fee"]
|
"max_open_trades", "stake_amount", "fee"]
|
||||||
|
|
||||||
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
ARGS_BACKTEST = ARGS_COMMON_OPTIMIZE + ["position_stacking", "use_max_market_positions",
|
||||||
|
"enable_protections",
|
||||||
"strategy_list", "export", "exportfilename"]
|
"strategy_list", "export", "exportfilename"]
|
||||||
|
|
||||||
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||||
"position_stacking", "epochs", "spaces",
|
"position_stacking", "use_max_market_positions",
|
||||||
"use_max_market_positions", "print_all",
|
"enable_protections",
|
||||||
|
"epochs", "spaces", "print_all",
|
||||||
"print_colorized", "print_json", "hyperopt_jobs",
|
"print_colorized", "print_json", "hyperopt_jobs",
|
||||||
"hyperopt_random_state", "hyperopt_min_trades",
|
"hyperopt_random_state", "hyperopt_min_trades",
|
||||||
"hyperopt_continue", "hyperopt_loss"]
|
"hyperopt_loss"]
|
||||||
|
|
||||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||||
|
|
||||||
@ -41,7 +44,8 @@ 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"]
|
||||||
|
|
||||||
ARGS_TEST_PAIRLIST = ["config", "quote_currencies", "print_one_column", "list_pairs_print_json"]
|
ARGS_TEST_PAIRLIST = ["verbosity", "config", "quote_currencies", "print_one_column",
|
||||||
|
"list_pairs_print_json"]
|
||||||
|
|
||||||
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||||
|
|
||||||
@ -54,15 +58,17 @@ ARGS_BUILD_HYPEROPT = ["user_data_dir", "hyperopt", "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"]
|
||||||
|
|
||||||
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "download_trades", "exchange",
|
ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs"]
|
||||||
|
|
||||||
|
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "timerange", "download_trades", "exchange",
|
||||||
"timeframes", "erase", "dataformat_ohlcv", "dataformat_trades"]
|
"timeframes", "erase", "dataformat_ohlcv", "dataformat_trades"]
|
||||||
|
|
||||||
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",
|
||||||
"timerange", "ticker_interval", "no_trades"]
|
"timerange", "timeframe", "no_trades"]
|
||||||
|
|
||||||
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
||||||
"trade_source", "ticker_interval"]
|
"trade_source", "timeframe"]
|
||||||
|
|
||||||
ARGS_SHOW_TRADES = ["db_url", "trade_ids", "print_json"]
|
ARGS_SHOW_TRADES = ["db_url", "trade_ids", "print_json"]
|
||||||
|
|
||||||
@ -71,14 +77,15 @@ ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable",
|
|||||||
"hyperopt_list_min_avg_time", "hyperopt_list_max_avg_time",
|
"hyperopt_list_min_avg_time", "hyperopt_list_max_avg_time",
|
||||||
"hyperopt_list_min_avg_profit", "hyperopt_list_max_avg_profit",
|
"hyperopt_list_min_avg_profit", "hyperopt_list_max_avg_profit",
|
||||||
"hyperopt_list_min_total_profit", "hyperopt_list_max_total_profit",
|
"hyperopt_list_min_total_profit", "hyperopt_list_max_total_profit",
|
||||||
|
"hyperopt_list_min_objective", "hyperopt_list_max_objective",
|
||||||
"print_colorized", "print_json", "hyperopt_list_no_details",
|
"print_colorized", "print_json", "hyperopt_list_no_details",
|
||||||
"export_csv"]
|
"hyperoptexportfilename", "export_csv"]
|
||||||
|
|
||||||
ARGS_HYPEROPT_SHOW = ["hyperopt_list_best", "hyperopt_list_profitable", "hyperopt_show_index",
|
ARGS_HYPEROPT_SHOW = ["hyperopt_list_best", "hyperopt_list_profitable", "hyperopt_show_index",
|
||||||
"print_json", "hyperopt_show_no_header"]
|
"print_json", "hyperoptexportfilename", "hyperopt_show_no_header"]
|
||||||
|
|
||||||
NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes",
|
NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes",
|
||||||
"list-markets", "list-pairs", "list-strategies",
|
"list-markets", "list-pairs", "list-strategies", "list-data",
|
||||||
"list-hyperopts", "hyperopt-list", "hyperopt-show",
|
"list-hyperopts", "hyperopt-list", "hyperopt-show",
|
||||||
"plot-dataframe", "plot-profit", "show-trades"]
|
"plot-dataframe", "plot-profit", "show-trades"]
|
||||||
|
|
||||||
@ -158,16 +165,14 @@ class Arguments:
|
|||||||
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||||
self._build_args(optionlist=['version'], parser=self.parser)
|
self._build_args(optionlist=['version'], parser=self.parser)
|
||||||
|
|
||||||
from freqtrade.commands import (start_create_userdir, start_convert_data,
|
from freqtrade.commands import (start_backtesting, start_convert_data, start_create_userdir,
|
||||||
start_download_data,
|
start_download_data, start_edge, start_hyperopt,
|
||||||
start_hyperopt_list, start_hyperopt_show,
|
start_hyperopt_list, start_hyperopt_show, start_list_data,
|
||||||
start_list_exchanges, start_list_hyperopts,
|
start_list_exchanges, start_list_hyperopts,
|
||||||
start_list_markets, start_list_strategies,
|
start_list_markets, start_list_strategies,
|
||||||
start_list_timeframes, start_new_config,
|
start_list_timeframes, start_new_config, start_new_hyperopt,
|
||||||
start_new_hyperopt, start_new_strategy,
|
start_new_strategy, start_plot_dataframe, start_plot_profit,
|
||||||
start_plot_dataframe, start_plot_profit, start_show_trades,
|
start_show_trades, start_test_pairlist, start_trading)
|
||||||
start_backtesting, start_hyperopt, start_edge,
|
|
||||||
start_test_pairlist, start_trading)
|
|
||||||
|
|
||||||
subparsers = self.parser.add_subparsers(dest='command',
|
subparsers = self.parser.add_subparsers(dest='command',
|
||||||
# Use custom message when no subhandler is added
|
# Use custom message when no subhandler is added
|
||||||
@ -233,6 +238,15 @@ class Arguments:
|
|||||||
convert_trade_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=False))
|
convert_trade_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=False))
|
||||||
self._build_args(optionlist=ARGS_CONVERT_DATA, parser=convert_trade_data_cmd)
|
self._build_args(optionlist=ARGS_CONVERT_DATA, parser=convert_trade_data_cmd)
|
||||||
|
|
||||||
|
# Add list-data subcommand
|
||||||
|
list_data_cmd = subparsers.add_parser(
|
||||||
|
'list-data',
|
||||||
|
help='List downloaded data.',
|
||||||
|
parents=[_common_parser],
|
||||||
|
)
|
||||||
|
list_data_cmd.set_defaults(func=start_list_data)
|
||||||
|
self._build_args(optionlist=ARGS_LIST_DATA, parser=list_data_cmd)
|
||||||
|
|
||||||
# Add backtesting subcommand
|
# Add backtesting subcommand
|
||||||
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.',
|
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.',
|
||||||
parents=[_common_parser, _strategy_parser])
|
parents=[_common_parser, _strategy_parser])
|
||||||
@ -318,7 +332,7 @@ class Arguments:
|
|||||||
# Add list-timeframes subcommand
|
# Add list-timeframes subcommand
|
||||||
list_timeframes_cmd = subparsers.add_parser(
|
list_timeframes_cmd = subparsers.add_parser(
|
||||||
'list-timeframes',
|
'list-timeframes',
|
||||||
help='Print available ticker intervals (timeframes) for the exchange.',
|
help='Print available timeframes for the exchange.',
|
||||||
parents=[_common_parser],
|
parents=[_common_parser],
|
||||||
)
|
)
|
||||||
list_timeframes_cmd.set_defaults(func=start_list_timeframes)
|
list_timeframes_cmd.set_defaults(func=start_list_timeframes)
|
||||||
@ -354,7 +368,7 @@ class Arguments:
|
|||||||
plot_profit_cmd = subparsers.add_parser(
|
plot_profit_cmd = subparsers.add_parser(
|
||||||
'plot-profit',
|
'plot-profit',
|
||||||
help='Generate plot showing profits.',
|
help='Generate plot showing profits.',
|
||||||
parents=[_common_parser],
|
parents=[_common_parser, _strategy_parser],
|
||||||
)
|
)
|
||||||
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
||||||
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
||||||
|
@ -1,13 +1,15 @@
|
|||||||
import logging
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
from questionary import Separator, prompt
|
from questionary import Separator, prompt
|
||||||
|
|
||||||
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT
|
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT
|
||||||
from freqtrade.exchange import available_exchanges, MAP_EXCHANGE_CHILDCLASS
|
|
||||||
from freqtrade.misc import render_template
|
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.exchange import MAP_EXCHANGE_CHILDCLASS, available_exchanges
|
||||||
|
from freqtrade.misc import render_template
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -46,7 +48,7 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
Interactive questions built using https://github.com/tmbo/questionary
|
Interactive questions built using https://github.com/tmbo/questionary
|
||||||
:returns: Dict with keys to put into template
|
:returns: Dict with keys to put into template
|
||||||
"""
|
"""
|
||||||
questions = [
|
questions: List[Dict[str, Any]] = [
|
||||||
{
|
{
|
||||||
"type": "confirm",
|
"type": "confirm",
|
||||||
"name": "dry_run",
|
"name": "dry_run",
|
||||||
@ -75,8 +77,8 @@ def ask_user_config() -> Dict[str, Any]:
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"name": "ticker_interval",
|
"name": "timeframe",
|
||||||
"message": "Please insert your timeframe (ticker interval):",
|
"message": "Please insert your desired timeframe (e.g. 5m):",
|
||||||
"default": "5m",
|
"default": "5m",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
@ -4,6 +4,7 @@ Definition of cli arguments used in arguments.py
|
|||||||
from argparse import ArgumentTypeError
|
from argparse import ArgumentTypeError
|
||||||
|
|
||||||
from freqtrade import __version__, constants
|
from freqtrade import __version__, constants
|
||||||
|
from freqtrade.constants import HYPEROPT_LOSS_BUILTIN
|
||||||
|
|
||||||
|
|
||||||
def check_int_positive(value: str) -> int:
|
def check_int_positive(value: str) -> int:
|
||||||
@ -110,8 +111,8 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
action='store_true',
|
action='store_true',
|
||||||
),
|
),
|
||||||
# Optimize common
|
# Optimize common
|
||||||
"ticker_interval": Arg(
|
"timeframe": Arg(
|
||||||
'-i', '--ticker-interval',
|
'-i', '--timeframe', '--ticker-interval',
|
||||||
help='Specify ticker interval (`1m`, `5m`, `30m`, `1h`, `1d`).',
|
help='Specify ticker interval (`1m`, `5m`, `30m`, `1h`, `1d`).',
|
||||||
),
|
),
|
||||||
"timerange": Arg(
|
"timerange": Arg(
|
||||||
@ -143,6 +144,14 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
action='store_false',
|
action='store_false',
|
||||||
default=True,
|
default=True,
|
||||||
),
|
),
|
||||||
|
"enable_protections": Arg(
|
||||||
|
'--enable-protections', '--enableprotections',
|
||||||
|
help='Enable protections for backtesting.'
|
||||||
|
'Will slow backtesting down by a considerable amount, but will include '
|
||||||
|
'configured protections',
|
||||||
|
action='store_true',
|
||||||
|
default=False,
|
||||||
|
),
|
||||||
"strategy_list": Arg(
|
"strategy_list": Arg(
|
||||||
'--strategy-list',
|
'--strategy-list',
|
||||||
help='Provide a space-separated list of strategies to backtest. '
|
help='Provide a space-separated list of strategies to backtest. '
|
||||||
@ -252,23 +261,19 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
metavar='INT',
|
metavar='INT',
|
||||||
default=1,
|
default=1,
|
||||||
),
|
),
|
||||||
"hyperopt_continue": Arg(
|
|
||||||
"--continue",
|
|
||||||
help="Continue hyperopt from previous runs. "
|
|
||||||
"By default, temporary files will be removed and hyperopt will start from scratch.",
|
|
||||||
default=False,
|
|
||||||
action='store_true',
|
|
||||||
),
|
|
||||||
"hyperopt_loss": Arg(
|
"hyperopt_loss": Arg(
|
||||||
'--hyperopt-loss',
|
'--hyperopt-loss',
|
||||||
help='Specify the class name of the hyperopt loss function class (IHyperOptLoss). '
|
help='Specify the class name of the hyperopt loss function class (IHyperOptLoss). '
|
||||||
'Different functions can generate completely different results, '
|
'Different functions can generate completely different results, '
|
||||||
'since the target for optimization is different. Built-in Hyperopt-loss-functions are: '
|
'since the target for optimization is different. Built-in Hyperopt-loss-functions are: '
|
||||||
'DefaultHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss, SharpeHyperOptLossDaily, '
|
f'{", ".join(HYPEROPT_LOSS_BUILTIN)}',
|
||||||
'SortinoHyperOptLoss, SortinoHyperOptLossDaily.'
|
|
||||||
'(default: `%(default)s`).',
|
|
||||||
metavar='NAME',
|
metavar='NAME',
|
||||||
default=constants.DEFAULT_HYPEROPT_LOSS,
|
),
|
||||||
|
"hyperoptexportfilename": Arg(
|
||||||
|
'--hyperopt-filename',
|
||||||
|
help='Hyperopt result filename.'
|
||||||
|
'Example: `--hyperopt-filename=hyperopt_results_2020-09-27_16-20-48.pickle`',
|
||||||
|
metavar='FILENAME',
|
||||||
),
|
),
|
||||||
# List exchanges
|
# List exchanges
|
||||||
"print_one_column": Arg(
|
"print_one_column": Arg(
|
||||||
@ -357,13 +362,11 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
'--data-format-ohlcv',
|
'--data-format-ohlcv',
|
||||||
help='Storage format for downloaded candle (OHLCV) data. (default: `%(default)s`).',
|
help='Storage format for downloaded candle (OHLCV) data. (default: `%(default)s`).',
|
||||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||||
default='json'
|
|
||||||
),
|
),
|
||||||
"dataformat_trades": Arg(
|
"dataformat_trades": Arg(
|
||||||
'--data-format-trades',
|
'--data-format-trades',
|
||||||
help='Storage format for downloaded trades data. (default: `%(default)s`).',
|
help='Storage format for downloaded trades data. (default: `%(default)s`).',
|
||||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||||
default='jsongz'
|
|
||||||
),
|
),
|
||||||
"exchange": Arg(
|
"exchange": Arg(
|
||||||
'--exchange',
|
'--exchange',
|
||||||
@ -375,7 +378,7 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help='Specify which tickers to download. Space-separated list. '
|
help='Specify which tickers to download. Space-separated list. '
|
||||||
'Default: `1m 5m`.',
|
'Default: `1m 5m`.',
|
||||||
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
choices=['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h',
|
||||||
'6h', '8h', '12h', '1d', '3d', '1w'],
|
'6h', '8h', '12h', '1d', '3d', '1w', '2w', '1M', '1y'],
|
||||||
default=['1m', '5m'],
|
default=['1m', '5m'],
|
||||||
nargs='+',
|
nargs='+',
|
||||||
),
|
),
|
||||||
@ -455,37 +458,49 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
),
|
),
|
||||||
"hyperopt_list_min_avg_time": Arg(
|
"hyperopt_list_min_avg_time": Arg(
|
||||||
'--min-avg-time',
|
'--min-avg-time',
|
||||||
help='Select epochs on above average time.',
|
help='Select epochs above average time.',
|
||||||
type=float,
|
type=float,
|
||||||
metavar='FLOAT',
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
"hyperopt_list_max_avg_time": Arg(
|
"hyperopt_list_max_avg_time": Arg(
|
||||||
'--max-avg-time',
|
'--max-avg-time',
|
||||||
help='Select epochs on under average time.',
|
help='Select epochs below average time.',
|
||||||
type=float,
|
type=float,
|
||||||
metavar='FLOAT',
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
"hyperopt_list_min_avg_profit": Arg(
|
"hyperopt_list_min_avg_profit": Arg(
|
||||||
'--min-avg-profit',
|
'--min-avg-profit',
|
||||||
help='Select epochs on above average profit.',
|
help='Select epochs above average profit.',
|
||||||
type=float,
|
type=float,
|
||||||
metavar='FLOAT',
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
"hyperopt_list_max_avg_profit": Arg(
|
"hyperopt_list_max_avg_profit": Arg(
|
||||||
'--max-avg-profit',
|
'--max-avg-profit',
|
||||||
help='Select epochs on below average profit.',
|
help='Select epochs below average profit.',
|
||||||
type=float,
|
type=float,
|
||||||
metavar='FLOAT',
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
"hyperopt_list_min_total_profit": Arg(
|
"hyperopt_list_min_total_profit": Arg(
|
||||||
'--min-total-profit',
|
'--min-total-profit',
|
||||||
help='Select epochs on above total profit.',
|
help='Select epochs above total profit.',
|
||||||
type=float,
|
type=float,
|
||||||
metavar='FLOAT',
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
"hyperopt_list_max_total_profit": Arg(
|
"hyperopt_list_max_total_profit": Arg(
|
||||||
'--max-total-profit',
|
'--max-total-profit',
|
||||||
help='Select epochs on below total profit.',
|
help='Select epochs below total profit.',
|
||||||
|
type=float,
|
||||||
|
metavar='FLOAT',
|
||||||
|
),
|
||||||
|
"hyperopt_list_min_objective": Arg(
|
||||||
|
'--min-objective',
|
||||||
|
help='Select epochs above objective.',
|
||||||
|
type=float,
|
||||||
|
metavar='FLOAT',
|
||||||
|
),
|
||||||
|
"hyperopt_list_max_objective": Arg(
|
||||||
|
'--max-objective',
|
||||||
|
help='Select epochs below objective.',
|
||||||
type=float,
|
type=float,
|
||||||
metavar='FLOAT',
|
metavar='FLOAT',
|
||||||
),
|
),
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
import arrow
|
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||||
from freqtrade.data.converter import (convert_ohlcv_format,
|
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_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.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
from freqtrade.resolvers import ExchangeResolver
|
from freqtrade.resolvers import ExchangeResolver
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -23,18 +23,27 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
|||||||
"""
|
"""
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||||
|
|
||||||
|
if 'days' in config and 'timerange' in config:
|
||||||
|
raise OperationalException("--days and --timerange are mutually exclusive. "
|
||||||
|
"You can only specify one or the other.")
|
||||||
timerange = TimeRange()
|
timerange = TimeRange()
|
||||||
if 'days' in config:
|
if 'days' in config:
|
||||||
time_since = arrow.utcnow().shift(days=-config['days']).strftime("%Y%m%d")
|
time_since = (datetime.now() - timedelta(days=config['days'])).strftime("%Y%m%d")
|
||||||
timerange = TimeRange.parse_timerange(f'{time_since}-')
|
timerange = TimeRange.parse_timerange(f'{time_since}-')
|
||||||
|
|
||||||
|
if 'timerange' in config:
|
||||||
|
timerange = timerange.parse_timerange(config['timerange'])
|
||||||
|
|
||||||
|
# Remove stake-currency to skip checks which are not relevant for datadownload
|
||||||
|
config['stake_currency'] = ''
|
||||||
|
|
||||||
if 'pairs' not in config:
|
if 'pairs' not in config:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
"Downloading data requires a list of pairs. "
|
"Downloading data requires a list of pairs. "
|
||||||
"Please check the documentation on how to configure this.")
|
"Please check the documentation on how to configure this.")
|
||||||
|
|
||||||
logger.info(f'About to download pairs: {config["pairs"]}, '
|
logger.info(f"About to download pairs: {config['pairs']}, "
|
||||||
f'intervals: {config["timeframes"]} to {config["datadir"]}')
|
f"intervals: {config['timeframes']} to {config['datadir']}")
|
||||||
|
|
||||||
pairs_not_available: List[str] = []
|
pairs_not_available: List[str] = []
|
||||||
|
|
||||||
@ -49,21 +58,21 @@ def start_download_data(args: Dict[str, Any]) -> None:
|
|||||||
|
|
||||||
if config.get('download_trades'):
|
if config.get('download_trades'):
|
||||||
pairs_not_available = refresh_backtest_trades_data(
|
pairs_not_available = refresh_backtest_trades_data(
|
||||||
exchange, pairs=config["pairs"], datadir=config['datadir'],
|
exchange, pairs=config['pairs'], datadir=config['datadir'],
|
||||||
timerange=timerange, erase=bool(config.get("erase")),
|
timerange=timerange, erase=bool(config.get('erase')),
|
||||||
data_format=config['dataformat_trades'])
|
data_format=config['dataformat_trades'])
|
||||||
|
|
||||||
# Convert downloaded trade data to different timeframes
|
# Convert downloaded trade data to different timeframes
|
||||||
convert_trades_to_ohlcv(
|
convert_trades_to_ohlcv(
|
||||||
pairs=config["pairs"], timeframes=config["timeframes"],
|
pairs=config['pairs'], timeframes=config['timeframes'],
|
||||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get("erase")),
|
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
|
||||||
data_format_ohlcv=config['dataformat_ohlcv'],
|
data_format_ohlcv=config['dataformat_ohlcv'],
|
||||||
data_format_trades=config['dataformat_trades'],
|
data_format_trades=config['dataformat_trades'],
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
pairs_not_available = refresh_backtest_ohlcv_data(
|
pairs_not_available = refresh_backtest_ohlcv_data(
|
||||||
exchange, pairs=config["pairs"], timeframes=config["timeframes"],
|
exchange, pairs=config['pairs'], timeframes=config['timeframes'],
|
||||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get("erase")),
|
datadir=config['datadir'], timerange=timerange, erase=bool(config.get('erase')),
|
||||||
data_format=config['dataformat_ohlcv'])
|
data_format=config['dataformat_ohlcv'])
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
@ -88,3 +97,31 @@ def start_convert_data(args: Dict[str, Any], ohlcv: bool = True) -> None:
|
|||||||
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'],
|
||||||
erase=args['erase'])
|
erase=args['erase'])
|
||||||
|
|
||||||
|
|
||||||
|
def start_list_data(args: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
List available backtest data
|
||||||
|
"""
|
||||||
|
|
||||||
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
|
|
||||||
|
from tabulate import tabulate
|
||||||
|
|
||||||
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
|
dhc = get_datahandler(config['datadir'], config['dataformat_ohlcv'])
|
||||||
|
|
||||||
|
paircombs = dhc.ohlcv_get_available_data(config['datadir'])
|
||||||
|
|
||||||
|
if args['pairs']:
|
||||||
|
paircombs = [comb for comb in paircombs if comb[0] in args['pairs']]
|
||||||
|
|
||||||
|
print(f"Found {len(paircombs)} pair / timeframe combinations.")
|
||||||
|
groupedpair = defaultdict(list)
|
||||||
|
for pair, timeframe in sorted(paircombs, key=lambda x: (x[0], timeframe_to_minutes(x[1]))):
|
||||||
|
groupedpair[pair].append(timeframe)
|
||||||
|
|
||||||
|
if groupedpair:
|
||||||
|
print(tabulate([(pair, ', '.join(timeframes)) for pair, timeframes in groupedpair.items()],
|
||||||
|
headers=("Pair", "Timeframe"),
|
||||||
|
tablefmt='psql', stralign='right'))
|
||||||
|
@ -4,13 +4,13 @@ from pathlib import Path
|
|||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from freqtrade.configuration import setup_utils_configuration
|
from freqtrade.configuration import setup_utils_configuration
|
||||||
from freqtrade.configuration.directory_operations import (copy_sample_files,
|
from freqtrade.configuration.directory_operations import copy_sample_files, create_userdata_dir
|
||||||
create_userdata_dir)
|
|
||||||
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.misc import render_template, render_template_with_fallback
|
from freqtrade.misc import render_template, render_template_with_fallback
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -75,7 +75,7 @@ def start_new_strategy(args: Dict[str, Any]) -> None:
|
|||||||
if args["strategy"] == "DefaultStrategy":
|
if args["strategy"] == "DefaultStrategy":
|
||||||
raise OperationalException("DefaultStrategy is not allowed as name.")
|
raise OperationalException("DefaultStrategy is not allowed as name.")
|
||||||
|
|
||||||
new_path = config['user_data_dir'] / USERPATH_STRATEGIES / (args["strategy"] + ".py")
|
new_path = config['user_data_dir'] / USERPATH_STRATEGIES / (args['strategy'] + '.py')
|
||||||
|
|
||||||
if new_path.exists():
|
if new_path.exists():
|
||||||
raise OperationalException(f"`{new_path}` already exists. "
|
raise OperationalException(f"`{new_path}` already exists. "
|
||||||
@ -125,15 +125,15 @@ def start_new_hyperopt(args: Dict[str, Any]) -> None:
|
|||||||
|
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
|
|
||||||
if "hyperopt" in args and args["hyperopt"]:
|
if 'hyperopt' in args and args['hyperopt']:
|
||||||
if args["hyperopt"] == "DefaultHyperopt":
|
if args['hyperopt'] == 'DefaultHyperopt':
|
||||||
raise OperationalException("DefaultHyperopt is not allowed as name.")
|
raise OperationalException("DefaultHyperopt is not allowed as name.")
|
||||||
|
|
||||||
new_path = config['user_data_dir'] / USERPATH_HYPEROPTS / (args["hyperopt"] + ".py")
|
new_path = config['user_data_dir'] / USERPATH_HYPEROPTS / (args['hyperopt'] + '.py')
|
||||||
|
|
||||||
if new_path.exists():
|
if new_path.exists():
|
||||||
raise OperationalException(f"`{new_path}` already exists. "
|
raise OperationalException(f"`{new_path}` already exists. "
|
||||||
"Please choose another Strategy Name.")
|
"Please choose another Hyperopt Name.")
|
||||||
deploy_new_hyperopt(args['hyperopt'], new_path, args['template'])
|
deploy_new_hyperopt(args['hyperopt'], new_path, args['template'])
|
||||||
else:
|
else:
|
||||||
raise OperationalException("`new-hyperopt` requires --hyperopt to be set.")
|
raise OperationalException("`new-hyperopt` requires --hyperopt to be set.")
|
||||||
|
@ -5,9 +5,11 @@ from typing import Any, Dict, List
|
|||||||
from colorama import init as colorama_init
|
from colorama import init as colorama_init
|
||||||
|
|
||||||
from freqtrade.configuration import setup_utils_configuration
|
from freqtrade.configuration import setup_utils_configuration
|
||||||
|
from freqtrade.data.btanalysis import get_latest_hyperopt_file
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -35,17 +37,20 @@ def start_hyperopt_list(args: Dict[str, Any]) -> None:
|
|||||||
'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit', None),
|
'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit', None),
|
||||||
'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit', None),
|
'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit', None),
|
||||||
'filter_min_total_profit': config.get('hyperopt_list_min_total_profit', None),
|
'filter_min_total_profit': config.get('hyperopt_list_min_total_profit', None),
|
||||||
'filter_max_total_profit': config.get('hyperopt_list_max_total_profit', None)
|
'filter_max_total_profit': config.get('hyperopt_list_max_total_profit', None),
|
||||||
|
'filter_min_objective': config.get('hyperopt_list_min_objective', None),
|
||||||
|
'filter_max_objective': config.get('hyperopt_list_max_objective', None),
|
||||||
}
|
}
|
||||||
|
|
||||||
results_file = (config['user_data_dir'] /
|
results_file = get_latest_hyperopt_file(
|
||||||
'hyperopt_results' / 'hyperopt_results.pickle')
|
config['user_data_dir'] / 'hyperopt_results',
|
||||||
|
config.get('hyperoptexportfilename'))
|
||||||
|
|
||||||
# Previous evaluations
|
# Previous evaluations
|
||||||
epochs = Hyperopt.load_previous_results(results_file)
|
epochs = Hyperopt.load_previous_results(results_file)
|
||||||
total_epochs = len(epochs)
|
total_epochs = len(epochs)
|
||||||
|
|
||||||
epochs = _hyperopt_filter_epochs(epochs, filteroptions)
|
epochs = hyperopt_filter_epochs(epochs, filteroptions)
|
||||||
|
|
||||||
if print_colorized:
|
if print_colorized:
|
||||||
colorama_init(autoreset=True)
|
colorama_init(autoreset=True)
|
||||||
@ -78,8 +83,10 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
|
|||||||
|
|
||||||
print_json = config.get('print_json', False)
|
print_json = config.get('print_json', False)
|
||||||
no_header = config.get('hyperopt_show_no_header', False)
|
no_header = config.get('hyperopt_show_no_header', False)
|
||||||
results_file = (config['user_data_dir'] /
|
results_file = get_latest_hyperopt_file(
|
||||||
'hyperopt_results' / 'hyperopt_results.pickle')
|
config['user_data_dir'] / 'hyperopt_results',
|
||||||
|
config.get('hyperoptexportfilename'))
|
||||||
|
|
||||||
n = config.get('hyperopt_show_index', -1)
|
n = config.get('hyperopt_show_index', -1)
|
||||||
|
|
||||||
filteroptions = {
|
filteroptions = {
|
||||||
@ -92,14 +99,16 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
|
|||||||
'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit', None),
|
'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit', None),
|
||||||
'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit', None),
|
'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit', None),
|
||||||
'filter_min_total_profit': config.get('hyperopt_list_min_total_profit', None),
|
'filter_min_total_profit': config.get('hyperopt_list_min_total_profit', None),
|
||||||
'filter_max_total_profit': config.get('hyperopt_list_max_total_profit', None)
|
'filter_max_total_profit': config.get('hyperopt_list_max_total_profit', None),
|
||||||
|
'filter_min_objective': config.get('hyperopt_list_min_objective', None),
|
||||||
|
'filter_max_objective': config.get('hyperopt_list_max_objective', None)
|
||||||
}
|
}
|
||||||
|
|
||||||
# Previous evaluations
|
# Previous evaluations
|
||||||
epochs = Hyperopt.load_previous_results(results_file)
|
epochs = Hyperopt.load_previous_results(results_file)
|
||||||
total_epochs = len(epochs)
|
total_epochs = len(epochs)
|
||||||
|
|
||||||
epochs = _hyperopt_filter_epochs(epochs, filteroptions)
|
epochs = hyperopt_filter_epochs(epochs, filteroptions)
|
||||||
filtered_epochs = len(epochs)
|
filtered_epochs = len(epochs)
|
||||||
|
|
||||||
if n > filtered_epochs:
|
if n > filtered_epochs:
|
||||||
@ -119,7 +128,7 @@ def start_hyperopt_show(args: Dict[str, Any]) -> None:
|
|||||||
header_str="Epoch details")
|
header_str="Epoch details")
|
||||||
|
|
||||||
|
|
||||||
def _hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:
|
def hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:
|
||||||
"""
|
"""
|
||||||
Filter our items from the list of hyperopt results
|
Filter our items from the list of hyperopt results
|
||||||
"""
|
"""
|
||||||
@ -127,6 +136,24 @@ def _hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:
|
|||||||
epochs = [x for x in epochs if x['is_best']]
|
epochs = [x for x in epochs if x['is_best']]
|
||||||
if filteroptions['only_profitable']:
|
if filteroptions['only_profitable']:
|
||||||
epochs = [x for x in epochs if x['results_metrics']['profit'] > 0]
|
epochs = [x for x in epochs if x['results_metrics']['profit'] > 0]
|
||||||
|
|
||||||
|
epochs = _hyperopt_filter_epochs_trade_count(epochs, filteroptions)
|
||||||
|
|
||||||
|
epochs = _hyperopt_filter_epochs_duration(epochs, filteroptions)
|
||||||
|
|
||||||
|
epochs = _hyperopt_filter_epochs_profit(epochs, filteroptions)
|
||||||
|
|
||||||
|
epochs = _hyperopt_filter_epochs_objective(epochs, filteroptions)
|
||||||
|
|
||||||
|
logger.info(f"{len(epochs)} " +
|
||||||
|
("best " if filteroptions['only_best'] else "") +
|
||||||
|
("profitable " if filteroptions['only_profitable'] else "") +
|
||||||
|
"epochs found.")
|
||||||
|
return epochs
|
||||||
|
|
||||||
|
|
||||||
|
def _hyperopt_filter_epochs_trade_count(epochs: List, filteroptions: dict) -> List:
|
||||||
|
|
||||||
if filteroptions['filter_min_trades'] > 0:
|
if filteroptions['filter_min_trades'] > 0:
|
||||||
epochs = [
|
epochs = [
|
||||||
x for x in epochs
|
x for x in epochs
|
||||||
@ -137,6 +164,11 @@ def _hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:
|
|||||||
x for x in epochs
|
x for x in epochs
|
||||||
if x['results_metrics']['trade_count'] < filteroptions['filter_max_trades']
|
if x['results_metrics']['trade_count'] < filteroptions['filter_max_trades']
|
||||||
]
|
]
|
||||||
|
return epochs
|
||||||
|
|
||||||
|
|
||||||
|
def _hyperopt_filter_epochs_duration(epochs: List, filteroptions: dict) -> List:
|
||||||
|
|
||||||
if filteroptions['filter_min_avg_time'] is not None:
|
if filteroptions['filter_min_avg_time'] is not None:
|
||||||
epochs = [x for x in epochs if x['results_metrics']['trade_count'] > 0]
|
epochs = [x for x in epochs if x['results_metrics']['trade_count'] > 0]
|
||||||
epochs = [
|
epochs = [
|
||||||
@ -149,6 +181,12 @@ def _hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:
|
|||||||
x for x in epochs
|
x for x in epochs
|
||||||
if x['results_metrics']['duration'] < filteroptions['filter_max_avg_time']
|
if x['results_metrics']['duration'] < filteroptions['filter_max_avg_time']
|
||||||
]
|
]
|
||||||
|
|
||||||
|
return epochs
|
||||||
|
|
||||||
|
|
||||||
|
def _hyperopt_filter_epochs_profit(epochs: List, filteroptions: dict) -> List:
|
||||||
|
|
||||||
if filteroptions['filter_min_avg_profit'] is not None:
|
if filteroptions['filter_min_avg_profit'] is not None:
|
||||||
epochs = [x for x in epochs if x['results_metrics']['trade_count'] > 0]
|
epochs = [x for x in epochs if x['results_metrics']['trade_count'] > 0]
|
||||||
epochs = [
|
epochs = [
|
||||||
@ -173,10 +211,18 @@ def _hyperopt_filter_epochs(epochs: List, filteroptions: dict) -> List:
|
|||||||
x for x in epochs
|
x for x in epochs
|
||||||
if x['results_metrics']['profit'] < filteroptions['filter_max_total_profit']
|
if x['results_metrics']['profit'] < filteroptions['filter_max_total_profit']
|
||||||
]
|
]
|
||||||
|
return epochs
|
||||||
|
|
||||||
logger.info(f"{len(epochs)} " +
|
|
||||||
("best " if filteroptions['only_best'] else "") +
|
def _hyperopt_filter_epochs_objective(epochs: List, filteroptions: dict) -> List:
|
||||||
("profitable " if filteroptions['only_profitable'] else "") +
|
|
||||||
"epochs found.")
|
if filteroptions['filter_min_objective'] is not None:
|
||||||
|
epochs = [x for x in epochs if x['results_metrics']['trade_count'] > 0]
|
||||||
|
|
||||||
|
epochs = [x for x in epochs if x['loss'] < filteroptions['filter_min_objective']]
|
||||||
|
if filteroptions['filter_max_objective'] is not None:
|
||||||
|
epochs = [x for x in epochs if x['results_metrics']['trade_count'] > 0]
|
||||||
|
|
||||||
|
epochs = [x for x in epochs if x['loss'] > filteroptions['filter_max_objective']]
|
||||||
|
|
||||||
return epochs
|
return epochs
|
||||||
|
@ -5,20 +5,20 @@ from collections import OrderedDict
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
from colorama import init as colorama_init
|
|
||||||
from colorama import Fore, Style
|
|
||||||
import rapidjson
|
import rapidjson
|
||||||
|
from colorama import Fore, Style
|
||||||
|
from colorama import init as colorama_init
|
||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
|
|
||||||
from freqtrade.configuration import setup_utils_configuration
|
from freqtrade.configuration import setup_utils_configuration
|
||||||
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import (available_exchanges, ccxt_exchanges,
|
from freqtrade.exchange import available_exchanges, ccxt_exchanges, market_is_active
|
||||||
market_is_active, symbol_is_pair)
|
|
||||||
from freqtrade.misc import plural
|
from freqtrade.misc import plural
|
||||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -102,8 +102,8 @@ def start_list_timeframes(args: Dict[str, Any]) -> None:
|
|||||||
Print ticker intervals (timeframes) available on Exchange
|
Print ticker intervals (timeframes) available on Exchange
|
||||||
"""
|
"""
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||||
# Do not use ticker_interval set in the config
|
# Do not use timeframe set in the config
|
||||||
config['ticker_interval'] = None
|
config['timeframe'] = None
|
||||||
|
|
||||||
# Init exchange
|
# Init exchange
|
||||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||||
@ -163,7 +163,7 @@ def start_list_markets(args: Dict[str, Any], pairs_only: bool = False) -> None:
|
|||||||
tabular_data.append({'Id': v['id'], 'Symbol': v['symbol'],
|
tabular_data.append({'Id': v['id'], 'Symbol': v['symbol'],
|
||||||
'Base': v['base'], 'Quote': v['quote'],
|
'Base': v['base'], 'Quote': v['quote'],
|
||||||
'Active': market_is_active(v),
|
'Active': market_is_active(v),
|
||||||
**({'Is pair': symbol_is_pair(v['symbol'])}
|
**({'Is pair': exchange.market_is_tradable(v)}
|
||||||
if not pairs_only else {})})
|
if not pairs_only else {})})
|
||||||
|
|
||||||
if (args.get('print_one_column', False) or
|
if (args.get('print_one_column', False) or
|
||||||
@ -203,15 +203,16 @@ def start_show_trades(args: Dict[str, Any]) -> None:
|
|||||||
"""
|
"""
|
||||||
Show trades
|
Show trades
|
||||||
"""
|
"""
|
||||||
from freqtrade.persistence import init, Trade
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
|
from freqtrade.persistence import Trade, init_db
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
|
|
||||||
if 'db_url' not in config:
|
if 'db_url' not in config:
|
||||||
raise OperationalException("--db-url is required for this command.")
|
raise OperationalException("--db-url is required for this command.")
|
||||||
|
|
||||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||||
init(config['db_url'], clean_open_orders=False)
|
init_db(config['db_url'], clean_open_orders=False)
|
||||||
tfilter = []
|
tfilter = []
|
||||||
|
|
||||||
if config.get('trade_ids'):
|
if config.get('trade_ids'):
|
||||||
|
@ -6,6 +6,7 @@ from freqtrade.configuration import setup_utils_configuration
|
|||||||
from freqtrade.exceptions import DependencyException, OperationalException
|
from freqtrade.exceptions import DependencyException, OperationalException
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -58,6 +59,7 @@ def start_hyperopt(args: Dict[str, Any]) -> None:
|
|||||||
# Import here to avoid loading hyperopt module when it's not used
|
# Import here to avoid loading hyperopt module when it's not used
|
||||||
try:
|
try:
|
||||||
from filelock import FileLock, Timeout
|
from filelock import FileLock, Timeout
|
||||||
|
|
||||||
from freqtrade.optimize.hyperopt import Hyperopt
|
from freqtrade.optimize.hyperopt import Hyperopt
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
@ -98,6 +100,7 @@ def start_edge(args: Dict[str, Any]) -> None:
|
|||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
from freqtrade.optimize.edge_cli import EdgeCli
|
from freqtrade.optimize.edge_cli import EdgeCli
|
||||||
|
|
||||||
# Initialize configuration
|
# Initialize configuration
|
||||||
config = setup_optimize_configuration(args, RunMode.EDGE)
|
config = setup_optimize_configuration(args, RunMode.EDGE)
|
||||||
logger.info('Starting freqtrade in Edge mode')
|
logger.info('Starting freqtrade in Edge mode')
|
||||||
|
@ -7,6 +7,7 @@ from freqtrade.configuration import setup_utils_configuration
|
|||||||
from freqtrade.resolvers import ExchangeResolver
|
from freqtrade.resolvers import ExchangeResolver
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -14,7 +15,7 @@ def start_test_pairlist(args: Dict[str, Any]) -> None:
|
|||||||
"""
|
"""
|
||||||
Test Pairlist configuration
|
Test Pairlist configuration
|
||||||
"""
|
"""
|
||||||
from freqtrade.pairlist.pairlistmanager import PairListManager
|
from freqtrade.plugins.pairlistmanager import PairListManager
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||||
|
|
||||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||||
@ -25,7 +26,6 @@ def start_test_pairlist(args: Dict[str, Any]) -> None:
|
|||||||
results = {}
|
results = {}
|
||||||
for curr in quote_currencies:
|
for curr in quote_currencies:
|
||||||
config['stake_currency'] = curr
|
config['stake_currency'] = curr
|
||||||
# Do not use ticker_interval set in the config
|
|
||||||
pairlists = PairListManager(exchange, config)
|
pairlists = PairListManager(exchange, config)
|
||||||
pairlists.refresh_pairlist()
|
pairlists.refresh_pairlist()
|
||||||
results[curr] = pairlists.whitelist
|
results[curr] = pairlists.whitelist
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
# flake8: noqa: F401
|
# flake8: noqa: F401
|
||||||
|
|
||||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
|
||||||
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials
|
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials
|
||||||
from freqtrade.configuration.timerange import TimeRange
|
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||||
from freqtrade.configuration.configuration import Configuration
|
|
||||||
from freqtrade.configuration.config_validation import validate_config_consistency
|
from freqtrade.configuration.config_validation import validate_config_consistency
|
||||||
|
from freqtrade.configuration.configuration import Configuration
|
||||||
|
from freqtrade.configuration.timerange import TimeRange
|
||||||
|
@ -2,11 +2,11 @@ import logging
|
|||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason, is_exchange_bad,
|
||||||
is_exchange_bad, is_exchange_known_ccxt,
|
is_exchange_known_ccxt, is_exchange_officially_supported)
|
||||||
is_exchange_officially_supported)
|
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
from .check_exchange import remove_credentials
|
||||||
from .config_validation import validate_config_consistency
|
from .config_validation import validate_config_consistency
|
||||||
from .configuration import Configuration
|
from .configuration import Configuration
|
||||||
from .check_exchange import remove_credentials
|
|
||||||
from freqtrade.state import RunMode
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ from freqtrade import constants
|
|||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -73,6 +74,7 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
|||||||
_validate_trailing_stoploss(conf)
|
_validate_trailing_stoploss(conf)
|
||||||
_validate_edge(conf)
|
_validate_edge(conf)
|
||||||
_validate_whitelist(conf)
|
_validate_whitelist(conf)
|
||||||
|
_validate_protections(conf)
|
||||||
_validate_unlimited_amount(conf)
|
_validate_unlimited_amount(conf)
|
||||||
|
|
||||||
# validate configuration before returning
|
# validate configuration before returning
|
||||||
@ -136,6 +138,10 @@ def _validate_edge(conf: Dict[str, Any]) -> None:
|
|||||||
"Edge and VolumePairList are incompatible, "
|
"Edge and VolumePairList are incompatible, "
|
||||||
"Edge will override whatever pairs VolumePairlist selects."
|
"Edge will override whatever pairs VolumePairlist selects."
|
||||||
)
|
)
|
||||||
|
if not conf.get('ask_strategy', {}).get('use_sell_signal', True):
|
||||||
|
raise OperationalException(
|
||||||
|
"Edge requires `use_sell_signal` to be True, otherwise no sells will happen."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
||||||
@ -150,3 +156,22 @@ def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
|||||||
if (pl.get('method') == 'StaticPairList'
|
if (pl.get('method') == 'StaticPairList'
|
||||||
and not conf.get('exchange', {}).get('pair_whitelist')):
|
and not conf.get('exchange', {}).get('pair_whitelist')):
|
||||||
raise OperationalException("StaticPairList requires pair_whitelist to be set.")
|
raise OperationalException("StaticPairList requires pair_whitelist to be set.")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_protections(conf: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Validate protection configuration validity
|
||||||
|
"""
|
||||||
|
|
||||||
|
for prot in conf.get('protections', []):
|
||||||
|
if ('stop_duration' in prot and 'stop_duration_candles' in prot):
|
||||||
|
raise OperationalException(
|
||||||
|
"Protections must specify either `stop_duration` or `stop_duration_candles`.\n"
|
||||||
|
f"Please fix the protection {prot.get('method')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if ('lookback_period' in prot and 'lookback_period_candles' in prot):
|
||||||
|
raise OperationalException(
|
||||||
|
"Protections must specify either `lookback_period` or `lookback_period_candles`.\n"
|
||||||
|
f"Please fix the protection {prot.get('method')}"
|
||||||
|
)
|
||||||
|
@ -10,14 +10,14 @@ from typing import Any, Callable, Dict, List, Optional
|
|||||||
from freqtrade import constants
|
from freqtrade import constants
|
||||||
from freqtrade.configuration.check_exchange import check_exchange
|
from freqtrade.configuration.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,
|
from freqtrade.configuration.directory_operations import create_datadir, create_userdata_dir
|
||||||
create_userdata_dir)
|
|
||||||
from freqtrade.configuration.load_config import load_config_file
|
from freqtrade.configuration.load_config import load_config_file
|
||||||
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, json_load
|
from freqtrade.misc import deep_merge_dicts, json_load
|
||||||
from freqtrade.state import NON_UTIL_MODES, TRADING_MODES, RunMode
|
from freqtrade.state import NON_UTIL_MODES, TRADING_MODES, RunMode
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -54,7 +54,7 @@ class Configuration:
|
|||||||
:param files: List of file paths
|
:param files: List of file paths
|
||||||
:return: configuration dictionary
|
:return: configuration dictionary
|
||||||
"""
|
"""
|
||||||
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]:
|
def load_from_files(self, files: List[str]) -> Dict[str, Any]:
|
||||||
@ -123,10 +123,10 @@ class Configuration:
|
|||||||
the -v/--verbose, --logfile options
|
the -v/--verbose, --logfile options
|
||||||
"""
|
"""
|
||||||
# Log level
|
# Log level
|
||||||
config.update({'verbosity': self.args.get("verbosity", 0)})
|
config.update({'verbosity': self.args.get('verbosity', 0)})
|
||||||
|
|
||||||
if 'logfile' in self.args and self.args["logfile"]:
|
if 'logfile' in self.args and self.args['logfile']:
|
||||||
config.update({'logfile': self.args["logfile"]})
|
config.update({'logfile': self.args['logfile']})
|
||||||
|
|
||||||
setup_logging(config)
|
setup_logging(config)
|
||||||
|
|
||||||
@ -149,22 +149,22 @@ class Configuration:
|
|||||||
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# Set strategy if not specified in config and or if it's non default
|
# Set strategy if not specified in config and or if it's non default
|
||||||
if self.args.get("strategy") or not config.get('strategy'):
|
if self.args.get('strategy') or not config.get('strategy'):
|
||||||
config.update({'strategy': self.args.get("strategy")})
|
config.update({'strategy': self.args.get('strategy')})
|
||||||
|
|
||||||
self._args_to_config(config, argname='strategy_path',
|
self._args_to_config(config, argname='strategy_path',
|
||||||
logstring='Using additional Strategy lookup path: {}')
|
logstring='Using additional Strategy lookup path: {}')
|
||||||
|
|
||||||
if ('db_url' in self.args and self.args["db_url"] and
|
if ('db_url' in self.args and self.args['db_url'] and
|
||||||
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
self.args['db_url'] != constants.DEFAULT_DB_PROD_URL):
|
||||||
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('forcebuy_enable', False):
|
||||||
logger.warning('`forcebuy` RPC message enabled.')
|
logger.warning('`forcebuy` 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']:
|
||||||
config['internals'].update({'sd_notify': True})
|
config['internals'].update({'sd_notify': True})
|
||||||
|
|
||||||
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||||
@ -173,24 +173,24 @@ class Configuration:
|
|||||||
--user-data, --datadir
|
--user-data, --datadir
|
||||||
"""
|
"""
|
||||||
# Check exchange parameter here - otherwise `datadir` might be wrong.
|
# Check exchange parameter here - otherwise `datadir` might be wrong.
|
||||||
if "exchange" in self.args and self.args["exchange"]:
|
if 'exchange' in self.args and self.args['exchange']:
|
||||||
config['exchange']['name'] = self.args["exchange"]
|
config['exchange']['name'] = self.args['exchange']
|
||||||
logger.info(f"Using exchange {config['exchange']['name']}")
|
logger.info(f"Using exchange {config['exchange']['name']}")
|
||||||
|
|
||||||
if 'pair_whitelist' not in config['exchange']:
|
if 'pair_whitelist' not in config['exchange']:
|
||||||
config['exchange']['pair_whitelist'] = []
|
config['exchange']['pair_whitelist'] = []
|
||||||
|
|
||||||
if 'user_data_dir' in self.args and self.args["user_data_dir"]:
|
if 'user_data_dir' in self.args and self.args['user_data_dir']:
|
||||||
config.update({'user_data_dir': self.args["user_data_dir"]})
|
config.update({'user_data_dir': self.args['user_data_dir']})
|
||||||
elif 'user_data_dir' not in config:
|
elif 'user_data_dir' not in config:
|
||||||
# Default to cwd/user_data (legacy option ...)
|
# Default to cwd/user_data (legacy option ...)
|
||||||
config.update({'user_data_dir': str(Path.cwd() / "user_data")})
|
config.update({'user_data_dir': str(Path.cwd() / 'user_data')})
|
||||||
|
|
||||||
# reset to user_data_dir so this contains the absolute path.
|
# reset to user_data_dir so this contains the absolute path.
|
||||||
config['user_data_dir'] = create_userdata_dir(config['user_data_dir'], create_dir=False)
|
config['user_data_dir'] = create_userdata_dir(config['user_data_dir'], create_dir=False)
|
||||||
logger.info('Using user-data directory: %s ...', config['user_data_dir'])
|
logger.info('Using user-data directory: %s ...', config['user_data_dir'])
|
||||||
|
|
||||||
config.update({'datadir': create_datadir(config, self.args.get("datadir", None))})
|
config.update({'datadir': create_datadir(config, self.args.get('datadir', None))})
|
||||||
logger.info('Using data directory: %s ...', config.get('datadir'))
|
logger.info('Using data directory: %s ...', config.get('datadir'))
|
||||||
|
|
||||||
if self.args.get('exportfilename'):
|
if self.args.get('exportfilename'):
|
||||||
@ -199,18 +199,21 @@ class Configuration:
|
|||||||
config['exportfilename'] = Path(config['exportfilename'])
|
config['exportfilename'] = Path(config['exportfilename'])
|
||||||
else:
|
else:
|
||||||
config['exportfilename'] = (config['user_data_dir']
|
config['exportfilename'] = (config['user_data_dir']
|
||||||
/ 'backtest_results/backtest-result.json')
|
/ 'backtest_results')
|
||||||
|
|
||||||
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
def _process_optimize_options(self, config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
# This will override the strategy configuration
|
# This will override the strategy configuration
|
||||||
self._args_to_config(config, argname='ticker_interval',
|
self._args_to_config(config, argname='timeframe',
|
||||||
logstring='Parameter -i/--ticker-interval detected ... '
|
logstring='Parameter -i/--timeframe detected ... '
|
||||||
'Using ticker_interval: {} ...')
|
'Using timeframe: {} ...')
|
||||||
|
|
||||||
self._args_to_config(config, argname='position_stacking',
|
self._args_to_config(config, argname='position_stacking',
|
||||||
logstring='Parameter --enable-position-stacking detected ...')
|
logstring='Parameter --enable-position-stacking detected ...')
|
||||||
|
|
||||||
|
self._args_to_config(
|
||||||
|
config, argname='enable_protections',
|
||||||
|
logstring='Parameter --enable-protections detected, enabling Protections. ...')
|
||||||
# Setting max_open_trades to infinite if -1
|
# Setting max_open_trades to infinite if -1
|
||||||
if config.get('max_open_trades') == -1:
|
if config.get('max_open_trades') == -1:
|
||||||
config['max_open_trades'] = float('inf')
|
config['max_open_trades'] = float('inf')
|
||||||
@ -219,8 +222,8 @@ class Configuration:
|
|||||||
config.update({'use_max_market_positions': False})
|
config.update({'use_max_market_positions': False})
|
||||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||||
logger.info('max_open_trades set to unlimited ...')
|
logger.info('max_open_trades set to unlimited ...')
|
||||||
elif 'max_open_trades' in self.args and self.args["max_open_trades"]:
|
elif 'max_open_trades' in self.args and self.args['max_open_trades']:
|
||||||
config.update({'max_open_trades': self.args["max_open_trades"]})
|
config.update({'max_open_trades': self.args['max_open_trades']})
|
||||||
logger.info('Parameter --max-open-trades detected, '
|
logger.info('Parameter --max-open-trades detected, '
|
||||||
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||||
elif config['runmode'] in NON_UTIL_MODES:
|
elif config['runmode'] in NON_UTIL_MODES:
|
||||||
@ -242,8 +245,8 @@ 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='ticker_interval',
|
self._args_to_config(config, argname='timeframe',
|
||||||
logstring='Overriding ticker interval with Command line argument')
|
logstring='Overriding timeframe with Command line argument')
|
||||||
|
|
||||||
self._args_to_config(config, argname='export',
|
self._args_to_config(config, argname='export',
|
||||||
logstring='Parameter --export detected: {} ...')
|
logstring='Parameter --export detected: {} ...')
|
||||||
@ -263,6 +266,9 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='hyperopt_path',
|
self._args_to_config(config, argname='hyperopt_path',
|
||||||
logstring='Using additional Hyperopt lookup path: {}')
|
logstring='Using additional Hyperopt lookup path: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperoptexportfilename',
|
||||||
|
logstring='Using hyperopt file: {}')
|
||||||
|
|
||||||
self._args_to_config(config, argname='epochs',
|
self._args_to_config(config, argname='epochs',
|
||||||
logstring='Parameter --epochs detected ... '
|
logstring='Parameter --epochs detected ... '
|
||||||
'Will run Hyperopt with for {} epochs ...'
|
'Will run Hyperopt with for {} epochs ...'
|
||||||
@ -295,9 +301,6 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='hyperopt_min_trades',
|
self._args_to_config(config, argname='hyperopt_min_trades',
|
||||||
logstring='Parameter --min-trades detected: {}')
|
logstring='Parameter --min-trades detected: {}')
|
||||||
|
|
||||||
self._args_to_config(config, argname='hyperopt_continue',
|
|
||||||
logstring='Hyperopt continue: {}')
|
|
||||||
|
|
||||||
self._args_to_config(config, argname='hyperopt_loss',
|
self._args_to_config(config, argname='hyperopt_loss',
|
||||||
logstring='Using Hyperopt loss class name: {}')
|
logstring='Using Hyperopt loss class name: {}')
|
||||||
|
|
||||||
@ -334,6 +337,12 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='hyperopt_list_max_total_profit',
|
self._args_to_config(config, argname='hyperopt_list_max_total_profit',
|
||||||
logstring='Parameter --max-total-profit detected: {}')
|
logstring='Parameter --max-total-profit detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_min_objective',
|
||||||
|
logstring='Parameter --min-objective detected: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='hyperopt_list_max_objective',
|
||||||
|
logstring='Parameter --max-objective detected: {}')
|
||||||
|
|
||||||
self._args_to_config(config, argname='hyperopt_list_no_details',
|
self._args_to_config(config, argname='hyperopt_list_no_details',
|
||||||
logstring='Parameter --no-details detected: {}')
|
logstring='Parameter --no-details detected: {}')
|
||||||
|
|
||||||
@ -441,12 +450,12 @@ class Configuration:
|
|||||||
config['pairs'].sort()
|
config['pairs'].sort()
|
||||||
return
|
return
|
||||||
|
|
||||||
if "config" in self.args and self.args["config"]:
|
if 'config' in self.args and self.args['config']:
|
||||||
logger.info("Using pairlist from configuration.")
|
logger.info("Using pairlist from configuration.")
|
||||||
config['pairs'] = config.get('exchange', {}).get('pair_whitelist')
|
config['pairs'] = config.get('exchange', {}).get('pair_whitelist')
|
||||||
else:
|
else:
|
||||||
# Fall back to /dl_path/pairs.json
|
# Fall back to /dl_path/pairs.json
|
||||||
pairs_file = config['datadir'] / "pairs.json"
|
pairs_file = config['datadir'] / 'pairs.json'
|
||||||
if pairs_file.exists():
|
if pairs_file.exists():
|
||||||
with pairs_file.open('r') as f:
|
with pairs_file.open('r') as f:
|
||||||
config['pairs'] = json_load(f)
|
config['pairs'] = json_load(f)
|
||||||
|
@ -26,6 +26,24 @@ def check_conflicting_settings(config: Dict[str, Any],
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def process_removed_setting(config: Dict[str, Any],
|
||||||
|
section1: str, name1: str,
|
||||||
|
section2: str, name2: str) -> None:
|
||||||
|
"""
|
||||||
|
:param section1: Removed section
|
||||||
|
:param name1: Removed setting name
|
||||||
|
:param section2: new section for this key
|
||||||
|
:param name2: new setting name
|
||||||
|
"""
|
||||||
|
section1_config = config.get(section1, {})
|
||||||
|
if name1 in section1_config:
|
||||||
|
raise OperationalException(
|
||||||
|
f"Setting `{section1}.{name1}` has been moved to `{section2}.{name2}. "
|
||||||
|
f"Please delete it from your configuration and use the `{section2}.{name2}` "
|
||||||
|
"setting instead."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def process_deprecated_setting(config: Dict[str, Any],
|
def process_deprecated_setting(config: Dict[str, Any],
|
||||||
section1: str, name1: str,
|
section1: str, name1: str,
|
||||||
section2: str, name2: str) -> None:
|
section2: str, name2: str) -> None:
|
||||||
@ -44,19 +62,18 @@ def process_deprecated_setting(config: Dict[str, Any],
|
|||||||
|
|
||||||
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||||
|
|
||||||
check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
# Kept for future deprecated / moved settings
|
||||||
'experimental', 'use_sell_signal')
|
# check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
|
||||||
check_conflicting_settings(config, 'ask_strategy', 'sell_profit_only',
|
# 'experimental', 'use_sell_signal')
|
||||||
'experimental', 'sell_profit_only')
|
# process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
||||||
check_conflicting_settings(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
# 'experimental', 'use_sell_signal')
|
||||||
'experimental', 'ignore_roi_if_buy_signal')
|
|
||||||
|
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
|
process_removed_setting(config, 'experimental', 'use_sell_signal',
|
||||||
'experimental', 'use_sell_signal')
|
'ask_strategy', 'use_sell_signal')
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_only',
|
process_removed_setting(config, 'experimental', 'sell_profit_only',
|
||||||
'experimental', 'sell_profit_only')
|
'ask_strategy', 'sell_profit_only')
|
||||||
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
process_removed_setting(config, 'experimental', 'ignore_roi_if_buy_signal',
|
||||||
'experimental', 'ignore_roi_if_buy_signal')
|
'ask_strategy', 'ignore_roi_if_buy_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', {})):
|
||||||
@ -67,3 +84,14 @@ def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
|||||||
"'tradable_balance_ratio' and remove 'capital_available_percentage' "
|
"'tradable_balance_ratio' and remove 'capital_available_percentage' "
|
||||||
"from the edge configuration."
|
"from the edge configuration."
|
||||||
)
|
)
|
||||||
|
if 'ticker_interval' in config:
|
||||||
|
logger.warning(
|
||||||
|
"DEPRECATED: "
|
||||||
|
"Please use 'timeframe' instead of 'ticker_interval."
|
||||||
|
)
|
||||||
|
if 'timeframe' in config:
|
||||||
|
raise OperationalException(
|
||||||
|
"Both 'timeframe' and 'ticker_interval' detected."
|
||||||
|
"Please remove 'ticker_interval' from your configuration to continue operating."
|
||||||
|
)
|
||||||
|
config['timeframe'] = config['ticker_interval']
|
||||||
|
@ -3,8 +3,9 @@ import shutil
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
from freqtrade.exceptions import OperationalException
|
|
||||||
from freqtrade.constants import USER_DATA_FILES
|
from freqtrade.constants import USER_DATA_FILES
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -11,6 +11,7 @@ import rapidjson
|
|||||||
|
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@ -52,11 +52,11 @@ class TimeRange:
|
|||||||
:return: None (Modifies the object in place)
|
:return: None (Modifies the object in place)
|
||||||
"""
|
"""
|
||||||
if (not self.starttype or (startup_candles
|
if (not self.starttype or (startup_candles
|
||||||
and min_date.timestamp >= self.startts)):
|
and min_date.int_timestamp >= self.startts)):
|
||||||
# If no startts was defined, or backtest-data starts at the defined backtest-date
|
# If no startts was defined, or backtest-data starts at the defined backtest-date
|
||||||
logger.warning("Moving start-date by %s candles to account for startup time.",
|
logger.warning("Moving start-date by %s candles to account for startup time.",
|
||||||
startup_candles)
|
startup_candles)
|
||||||
self.startts = (min_date.timestamp + timeframe_secs * startup_candles)
|
self.startts = (min_date.int_timestamp + timeframe_secs * startup_candles)
|
||||||
self.starttype = 'date'
|
self.starttype = 'date'
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -89,7 +89,7 @@ class TimeRange:
|
|||||||
if stype[0]:
|
if stype[0]:
|
||||||
starts = rvals[index]
|
starts = rvals[index]
|
||||||
if stype[0] == 'date' and len(starts) == 8:
|
if stype[0] == 'date' and len(starts) == 8:
|
||||||
start = arrow.get(starts, 'YYYYMMDD').timestamp
|
start = arrow.get(starts, 'YYYYMMDD').int_timestamp
|
||||||
elif len(starts) == 13:
|
elif len(starts) == 13:
|
||||||
start = int(starts) // 1000
|
start = int(starts) // 1000
|
||||||
else:
|
else:
|
||||||
@ -98,7 +98,7 @@ class TimeRange:
|
|||||||
if stype[1]:
|
if stype[1]:
|
||||||
stops = rvals[index]
|
stops = rvals[index]
|
||||||
if stype[1] == 'date' and len(stops) == 8:
|
if stype[1] == 'date' and len(stops) == 8:
|
||||||
stop = arrow.get(stops, 'YYYYMMDD').timestamp
|
stop = arrow.get(stops, 'YYYYMMDD').int_timestamp
|
||||||
elif len(stops) == 13:
|
elif len(stops) == 13:
|
||||||
stop = int(stops) // 1000
|
stop = int(stops) // 1000
|
||||||
else:
|
else:
|
||||||
|
@ -11,7 +11,6 @@ DEFAULT_EXCHANGE = 'bittrex'
|
|||||||
PROCESS_THROTTLE_SECS = 5 # sec
|
PROCESS_THROTTLE_SECS = 5 # sec
|
||||||
HYPEROPT_EPOCH = 100 # epochs
|
HYPEROPT_EPOCH = 100 # epochs
|
||||||
RETRY_TIMEOUT = 30 # sec
|
RETRY_TIMEOUT = 30 # sec
|
||||||
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
|
||||||
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'
|
||||||
@ -21,20 +20,31 @@ REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
|||||||
ORDERBOOK_SIDES = ['ask', 'bid']
|
ORDERBOOK_SIDES = ['ask', 'bid']
|
||||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||||
|
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
||||||
|
'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',
|
||||||
|
'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily']
|
||||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList',
|
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList',
|
||||||
'PrecisionFilter', 'PriceFilter', 'ShuffleFilter', 'SpreadFilter']
|
'AgeFilter', 'PerformanceFilter', 'PrecisionFilter',
|
||||||
AVAILABLE_DATAHANDLERS = ['json', 'jsongz']
|
'PriceFilter', 'RangeStabilityFilter', 'ShuffleFilter',
|
||||||
|
'SpreadFilter']
|
||||||
|
AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard']
|
||||||
|
AVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5']
|
||||||
DRY_RUN_WALLET = 1000
|
DRY_RUN_WALLET = 1000
|
||||||
|
DATETIME_PRINT_FORMAT = '%Y-%m-%d %H:%M:%S'
|
||||||
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
||||||
DEFAULT_DATAFRAME_COLUMNS = ['date', 'open', 'high', 'low', 'close', 'volume']
|
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']
|
||||||
|
|
||||||
|
LAST_BT_RESULT_FN = '.last_result.json'
|
||||||
|
|
||||||
USERPATH_HYPEROPTS = 'hyperopts'
|
USERPATH_HYPEROPTS = 'hyperopts'
|
||||||
USERPATH_STRATEGIES = 'strategies'
|
USERPATH_STRATEGIES = 'strategies'
|
||||||
USERPATH_NOTEBOOKS = 'notebooks'
|
USERPATH_NOTEBOOKS = 'notebooks'
|
||||||
|
|
||||||
|
TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent']
|
||||||
|
|
||||||
# Soure files with destination directories within user-directory
|
# Soure files with destination directories within user-directory
|
||||||
USER_DATA_FILES = {
|
USER_DATA_FILES = {
|
||||||
'sample_strategy.py': USERPATH_STRATEGIES,
|
'sample_strategy.py': USERPATH_STRATEGIES,
|
||||||
@ -71,7 +81,7 @@ CONF_SCHEMA = {
|
|||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'max_open_trades': {'type': ['integer', 'number'], 'minimum': -1},
|
'max_open_trades': {'type': ['integer', 'number'], 'minimum': -1},
|
||||||
'ticker_interval': {'type': 'string'},
|
'timeframe': {'type': 'string'},
|
||||||
'stake_currency': {'type': 'string'},
|
'stake_currency': {'type': 'string'},
|
||||||
'stake_amount': {
|
'stake_amount': {
|
||||||
'type': ['number', 'string'],
|
'type': ['number', 'string'],
|
||||||
@ -155,7 +165,9 @@ CONF_SCHEMA = {
|
|||||||
'emergencysell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'emergencysell': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},
|
||||||
'stoploss_on_exchange': {'type': 'boolean'},
|
'stoploss_on_exchange': {'type': 'boolean'},
|
||||||
'stoploss_on_exchange_interval': {'type': 'number'}
|
'stoploss_on_exchange_interval': {'type': 'number'},
|
||||||
|
'stoploss_on_exchange_limit_ratio': {'type': 'number', 'minimum': 0.0,
|
||||||
|
'maximum': 1.0}
|
||||||
},
|
},
|
||||||
'required': ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
'required': ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||||
},
|
},
|
||||||
@ -172,9 +184,6 @@ CONF_SCHEMA = {
|
|||||||
'experimental': {
|
'experimental': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'use_sell_signal': {'type': 'boolean'},
|
|
||||||
'sell_profit_only': {'type': 'boolean'},
|
|
||||||
'ignore_roi_if_buy_signal': {'type': 'boolean'},
|
|
||||||
'block_bad_exchanges': {'type': 'boolean'}
|
'block_bad_exchanges': {'type': 'boolean'}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@ -184,7 +193,21 @@ CONF_SCHEMA = {
|
|||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},
|
||||||
'config': {'type': 'object'}
|
},
|
||||||
|
'required': ['method'],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'protections': {
|
||||||
|
'type': 'array',
|
||||||
|
'items': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'method': {'type': 'string', 'enum': AVAILABLE_PROTECTIONS},
|
||||||
|
'stop_duration': {'type': 'number', 'minimum': 0.0},
|
||||||
|
'stop_duration_candles': {'type': 'number', 'minimum': 0},
|
||||||
|
'trade_limit': {'type': 'number', 'minimum': 1},
|
||||||
|
'lookback_period': {'type': 'number', 'minimum': 1},
|
||||||
|
'lookback_period_candles': {'type': 'number', 'minimum': 1},
|
||||||
},
|
},
|
||||||
'required': ['method'],
|
'required': ['method'],
|
||||||
}
|
}
|
||||||
@ -195,6 +218,18 @@ CONF_SCHEMA = {
|
|||||||
'enabled': {'type': 'boolean'},
|
'enabled': {'type': 'boolean'},
|
||||||
'token': {'type': 'string'},
|
'token': {'type': 'string'},
|
||||||
'chat_id': {'type': 'string'},
|
'chat_id': {'type': 'string'},
|
||||||
|
'notification_settings': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'status': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
|
'warning': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
|
'startup': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
|
'buy': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
|
'sell': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
|
'buy_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
|
||||||
|
'sell_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS}
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
'required': ['enabled', 'token', 'chat_id']
|
'required': ['enabled', 'token', 'chat_id']
|
||||||
},
|
},
|
||||||
@ -221,6 +256,8 @@ CONF_SCHEMA = {
|
|||||||
},
|
},
|
||||||
'username': {'type': 'string'},
|
'username': {'type': 'string'},
|
||||||
'password': {'type': 'string'},
|
'password': {'type': 'string'},
|
||||||
|
'jwt_secret_key': {'type': 'string'},
|
||||||
|
'CORS_origins': {'type': 'array', 'items': {'type': 'string'}},
|
||||||
'verbosity': {'type': 'string', 'enum': ['error', 'info']},
|
'verbosity': {'type': 'string', 'enum': ['error', 'info']},
|
||||||
},
|
},
|
||||||
'required': ['enabled', 'listen_ip_address', 'listen_port', 'username', 'password']
|
'required': ['enabled', 'listen_ip_address', 'listen_port', 'username', 'password']
|
||||||
@ -303,6 +340,7 @@ CONF_SCHEMA = {
|
|||||||
|
|
||||||
SCHEMA_TRADE_REQUIRED = [
|
SCHEMA_TRADE_REQUIRED = [
|
||||||
'exchange',
|
'exchange',
|
||||||
|
'timeframe',
|
||||||
'max_open_trades',
|
'max_open_trades',
|
||||||
'stake_currency',
|
'stake_currency',
|
||||||
'stake_amount',
|
'stake_amount',
|
||||||
@ -329,10 +367,17 @@ SCHEMA_MINIMAL_REQUIRED = [
|
|||||||
|
|
||||||
CANCEL_REASON = {
|
CANCEL_REASON = {
|
||||||
"TIMEOUT": "cancelled due to timeout",
|
"TIMEOUT": "cancelled due to timeout",
|
||||||
"PARTIALLY_FILLED": "partially filled - keeping order open",
|
"PARTIALLY_FILLED_KEEP_OPEN": "partially filled - keeping order open",
|
||||||
|
"PARTIALLY_FILLED": "partially filled",
|
||||||
|
"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",
|
||||||
}
|
}
|
||||||
|
|
||||||
# List of pairs with their timeframes
|
# List of pairs with their timeframes
|
||||||
ListPairsWithTimeframes = List[Tuple[str, str]]
|
PairWithTimeframe = Tuple[str, str]
|
||||||
|
ListPairsWithTimeframes = List[PairWithTimeframe]
|
||||||
|
|
||||||
|
# Type for trades list
|
||||||
|
TradeList = List[List]
|
||||||
|
@ -2,54 +2,173 @@
|
|||||||
Helpers when analyzing backtest data
|
Helpers when analyzing backtest data
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, Union, Tuple
|
from typing import Any, Dict, Optional, Tuple, Union
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from datetime import timezone, datetime
|
|
||||||
from scipy.ndimage.interpolation import shift
|
from scipy.ndimage.interpolation import shift
|
||||||
|
|
||||||
from freqtrade import persistence
|
from freqtrade.constants import LAST_BT_RESULT_FN
|
||||||
from freqtrade.misc import json_load
|
from freqtrade.misc import json_load
|
||||||
from freqtrade.persistence import Trade
|
from freqtrade.persistence import Trade, init_db
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# must align with columns in backtest.py
|
# must align with columns in backtest.py
|
||||||
BT_DATA_COLUMNS = ["pair", "profit_percent", "open_time", "close_time", "index", "duration",
|
BT_DATA_COLUMNS = ["pair", "profit_percent", "open_date", "close_date", "index", "trade_duration",
|
||||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||||
|
|
||||||
|
|
||||||
def load_backtest_data(filename: Union[Path, str]) -> pd.DataFrame:
|
def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str:
|
||||||
"""
|
"""
|
||||||
Load backtest data file.
|
Get latest backtest export based on '.last_result.json'.
|
||||||
:param filename: pathlib.Path object, or string pointing to the file.
|
:param directory: Directory to search for last result
|
||||||
:return: a dataframe with the analysis results
|
:param variant: 'backtest' or 'hyperopt' - the method to return
|
||||||
|
:return: string containing the filename of the latest backtest result
|
||||||
|
:raises: ValueError in the following cases:
|
||||||
|
* Directory does not exist
|
||||||
|
* `directory/.last_result.json` does not exist
|
||||||
|
* `directory/.last_result.json` has the wrong content
|
||||||
"""
|
"""
|
||||||
if isinstance(filename, str):
|
if isinstance(directory, str):
|
||||||
filename = Path(filename)
|
directory = Path(directory)
|
||||||
|
if not directory.is_dir():
|
||||||
|
raise ValueError(f"Directory '{directory}' does not exist.")
|
||||||
|
filename = directory / LAST_BT_RESULT_FN
|
||||||
|
|
||||||
if not filename.is_file():
|
if not filename.is_file():
|
||||||
raise ValueError(f"File {filename} does not exist.")
|
raise ValueError(
|
||||||
|
f"Directory '{directory}' does not seem to contain backtest statistics yet.")
|
||||||
|
|
||||||
with filename.open() as file:
|
with filename.open() as file:
|
||||||
data = json_load(file)
|
data = json_load(file)
|
||||||
|
|
||||||
df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)
|
if f'latest_{variant}' not in data:
|
||||||
|
raise ValueError(f"Invalid '{LAST_BT_RESULT_FN}' format.")
|
||||||
|
|
||||||
df['open_time'] = pd.to_datetime(df['open_time'],
|
return data[f'latest_{variant}']
|
||||||
unit='s',
|
|
||||||
utc=True,
|
|
||||||
infer_datetime_format=True
|
def get_latest_backtest_filename(directory: Union[Path, str]) -> str:
|
||||||
)
|
"""
|
||||||
df['close_time'] = pd.to_datetime(df['close_time'],
|
Get latest backtest export based on '.last_result.json'.
|
||||||
unit='s',
|
:param directory: Directory to search for last result
|
||||||
utc=True,
|
:return: string containing the filename of the latest backtest result
|
||||||
infer_datetime_format=True
|
:raises: ValueError in the following cases:
|
||||||
)
|
* Directory does not exist
|
||||||
df['profit'] = df['close_rate'] - df['open_rate']
|
* `directory/.last_result.json` does not exist
|
||||||
df = df.sort_values("open_time").reset_index(drop=True)
|
* `directory/.last_result.json` has the wrong content
|
||||||
|
"""
|
||||||
|
return get_latest_optimize_filename(directory, 'backtest')
|
||||||
|
|
||||||
|
|
||||||
|
def get_latest_hyperopt_filename(directory: Union[Path, str]) -> str:
|
||||||
|
"""
|
||||||
|
Get latest hyperopt export based on '.last_result.json'.
|
||||||
|
:param directory: Directory to search for last result
|
||||||
|
:return: string containing the filename of the latest hyperopt result
|
||||||
|
:raises: ValueError in the following cases:
|
||||||
|
* Directory does not exist
|
||||||
|
* `directory/.last_result.json` does not exist
|
||||||
|
* `directory/.last_result.json` has the wrong content
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return get_latest_optimize_filename(directory, 'hyperopt')
|
||||||
|
except ValueError:
|
||||||
|
# Return default (legacy) pickle filename
|
||||||
|
return 'hyperopt_results.pickle'
|
||||||
|
|
||||||
|
|
||||||
|
def get_latest_hyperopt_file(directory: Union[Path, str], predef_filename: str = None) -> Path:
|
||||||
|
"""
|
||||||
|
Get latest hyperopt export based on '.last_result.json'.
|
||||||
|
:param directory: Directory to search for last result
|
||||||
|
:return: string containing the filename of the latest hyperopt result
|
||||||
|
:raises: ValueError in the following cases:
|
||||||
|
* Directory does not exist
|
||||||
|
* `directory/.last_result.json` does not exist
|
||||||
|
* `directory/.last_result.json` has the wrong content
|
||||||
|
"""
|
||||||
|
if isinstance(directory, str):
|
||||||
|
directory = Path(directory)
|
||||||
|
if predef_filename:
|
||||||
|
return directory / predef_filename
|
||||||
|
return directory / get_latest_hyperopt_filename(directory)
|
||||||
|
|
||||||
|
|
||||||
|
def load_backtest_stats(filename: Union[Path, str]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Load backtest statistics file.
|
||||||
|
:param filename: pathlib.Path object, or string pointing to the file.
|
||||||
|
:return: a dictionary containing the resulting file.
|
||||||
|
"""
|
||||||
|
if isinstance(filename, str):
|
||||||
|
filename = Path(filename)
|
||||||
|
if filename.is_dir():
|
||||||
|
filename = filename / get_latest_backtest_filename(filename)
|
||||||
|
if not filename.is_file():
|
||||||
|
raise ValueError(f"File {filename} does not exist.")
|
||||||
|
logger.info(f"Loading backtest result from {filename}")
|
||||||
|
with filename.open() as file:
|
||||||
|
data = json_load(file)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def load_backtest_data(filename: Union[Path, str], strategy: Optional[str] = None) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Load backtest data file.
|
||||||
|
:param filename: pathlib.Path object, or string pointing to a file or directory
|
||||||
|
:param strategy: Strategy to load - mainly relevant for multi-strategy backtests
|
||||||
|
Can also serve as protection to load the correct result.
|
||||||
|
:return: a dataframe with the analysis results
|
||||||
|
:raise: ValueError if loading goes wrong.
|
||||||
|
"""
|
||||||
|
data = load_backtest_stats(filename)
|
||||||
|
if not isinstance(data, list):
|
||||||
|
# new, nested format
|
||||||
|
if 'strategy' not in data:
|
||||||
|
raise ValueError("Unknown dataformat.")
|
||||||
|
|
||||||
|
if not strategy:
|
||||||
|
if len(data['strategy']) == 1:
|
||||||
|
strategy = list(data['strategy'].keys())[0]
|
||||||
|
else:
|
||||||
|
raise ValueError("Detected backtest result with more than one strategy. "
|
||||||
|
"Please specify a strategy.")
|
||||||
|
|
||||||
|
if strategy not in data['strategy']:
|
||||||
|
raise ValueError(f"Strategy {strategy} not available in the backtest result.")
|
||||||
|
|
||||||
|
data = data['strategy'][strategy]['trades']
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
df['open_date'] = pd.to_datetime(df['open_date'],
|
||||||
|
utc=True,
|
||||||
|
infer_datetime_format=True
|
||||||
|
)
|
||||||
|
df['close_date'] = pd.to_datetime(df['close_date'],
|
||||||
|
utc=True,
|
||||||
|
infer_datetime_format=True
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# old format - only with lists.
|
||||||
|
df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)
|
||||||
|
|
||||||
|
df['open_date'] = pd.to_datetime(df['open_date'],
|
||||||
|
unit='s',
|
||||||
|
utc=True,
|
||||||
|
infer_datetime_format=True
|
||||||
|
)
|
||||||
|
df['close_date'] = pd.to_datetime(df['close_date'],
|
||||||
|
unit='s',
|
||||||
|
utc=True,
|
||||||
|
infer_datetime_format=True
|
||||||
|
)
|
||||||
|
df['profit_abs'] = df['close_rate'] - df['open_rate']
|
||||||
|
df = df.sort_values("open_date").reset_index(drop=True)
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
@ -64,12 +183,11 @@ def analyze_trade_parallelism(results: pd.DataFrame, timeframe: str) -> pd.DataF
|
|||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
timeframe_min = timeframe_to_minutes(timeframe)
|
timeframe_min = timeframe_to_minutes(timeframe)
|
||||||
# compute how long each trade was left outstanding as date indexes
|
# compute how long each trade was left outstanding as date indexes
|
||||||
dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time,
|
dates = [pd.Series(pd.date_range(row[1]['open_date'], row[1]['close_date'],
|
||||||
freq=f"{timeframe_min}min"))
|
freq=f"{timeframe_min}min"))
|
||||||
for row in results[['open_time', 'close_time']].iterrows()]
|
for row in results[['open_date', 'close_date']].iterrows()]
|
||||||
# track the lifetime of each trade in number of candles
|
|
||||||
deltas = [len(x) for x in dates]
|
deltas = [len(x) for x in dates]
|
||||||
# concat expands and flattens the list of lists of dates
|
# expand and flatten the list of lists of dates
|
||||||
dates = pd.Series(pd.concat(dates).values, name='date')
|
dates = pd.Series(pd.concat(dates).values, name='date')
|
||||||
# trades are repeated (column wise) according to their lifetime
|
# trades are repeated (column wise) according to their lifetime
|
||||||
df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)
|
df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)
|
||||||
@ -98,20 +216,25 @@ def evaluate_result_multi(results: pd.DataFrame, timeframe: str,
|
|||||||
return df_final[df_final['open_trades'] > max_open_trades]
|
return df_final[df_final['open_trades'] > max_open_trades]
|
||||||
|
|
||||||
|
|
||||||
def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
def load_trades_from_db(db_url: str, strategy: Optional[str] = None) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Load trades from a DB (using dburl)
|
Load trades from a DB (using dburl)
|
||||||
:param db_url: Sqlite url (default format sqlite:///tradesv3.dry-run.sqlite)
|
:param db_url: Sqlite url (default format sqlite:///tradesv3.dry-run.sqlite)
|
||||||
|
:param strategy: Strategy to load - mainly relevant for multi-strategy backtests
|
||||||
|
Can also serve as protection to load the correct result.
|
||||||
:return: Dataframe containing Trades
|
:return: Dataframe containing Trades
|
||||||
"""
|
"""
|
||||||
trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)
|
init_db(db_url, clean_open_orders=False)
|
||||||
persistence.init(db_url, clean_open_orders=False)
|
|
||||||
|
|
||||||
columns = ["pair", "open_time", "close_time", "profit", "profit_percent",
|
columns = ["pair", "open_date", "close_date", "profit", "profit_percent",
|
||||||
"open_rate", "close_rate", "amount", "duration", "sell_reason",
|
"open_rate", "close_rate", "amount", "trade_duration", "sell_reason",
|
||||||
"fee_open", "fee_close", "open_rate_requested", "close_rate_requested",
|
"fee_open", "fee_close", "open_rate_requested", "close_rate_requested",
|
||||||
"stake_amount", "max_rate", "min_rate", "id", "exchange",
|
"stake_amount", "max_rate", "min_rate", "id", "exchange",
|
||||||
"stop_loss", "initial_stop_loss", "strategy", "ticker_interval"]
|
"stop_loss", "initial_stop_loss", "strategy", "timeframe"]
|
||||||
|
|
||||||
|
filters = []
|
||||||
|
if strategy:
|
||||||
|
filters.append(Trade.strategy == strategy)
|
||||||
|
|
||||||
trades = pd.DataFrame([(t.pair,
|
trades = pd.DataFrame([(t.pair,
|
||||||
t.open_date.replace(tzinfo=timezone.utc),
|
t.open_date.replace(tzinfo=timezone.utc),
|
||||||
@ -129,18 +252,18 @@ def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
|||||||
t.min_rate,
|
t.min_rate,
|
||||||
t.id, t.exchange,
|
t.id, t.exchange,
|
||||||
t.stop_loss, t.initial_stop_loss,
|
t.stop_loss, t.initial_stop_loss,
|
||||||
t.strategy, t.ticker_interval
|
t.strategy, t.timeframe
|
||||||
)
|
)
|
||||||
for t in Trade.get_trades().all()],
|
for t in Trade.get_trades(filters).all()],
|
||||||
columns=columns)
|
columns=columns)
|
||||||
|
|
||||||
return trades
|
return trades
|
||||||
|
|
||||||
|
|
||||||
def load_trades(source: str, db_url: str, exportfilename: Path,
|
def load_trades(source: str, db_url: str, exportfilename: Path,
|
||||||
no_trades: bool = False) -> pd.DataFrame:
|
no_trades: bool = False, strategy: Optional[str] = None) -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
Based on configuration option "trade_source":
|
Based on configuration option 'trade_source':
|
||||||
* loads data from DB (using `db_url`)
|
* loads data from DB (using `db_url`)
|
||||||
* loads data from backtestfile (using `exportfilename`)
|
* loads data from backtestfile (using `exportfilename`)
|
||||||
:param source: "DB" or "file" - specify source to load from
|
:param source: "DB" or "file" - specify source to load from
|
||||||
@ -156,7 +279,7 @@ def load_trades(source: str, db_url: str, exportfilename: Path,
|
|||||||
if source == "DB":
|
if source == "DB":
|
||||||
return load_trades_from_db(db_url)
|
return load_trades_from_db(db_url)
|
||||||
elif source == "file":
|
elif source == "file":
|
||||||
return load_backtest_data(exportfilename)
|
return load_backtest_data(exportfilename, strategy)
|
||||||
|
|
||||||
|
|
||||||
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame,
|
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame,
|
||||||
@ -171,11 +294,31 @@ def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame,
|
|||||||
else:
|
else:
|
||||||
trades_start = dataframe.iloc[0]['date']
|
trades_start = dataframe.iloc[0]['date']
|
||||||
trades_stop = dataframe.iloc[-1]['date']
|
trades_stop = dataframe.iloc[-1]['date']
|
||||||
trades = trades.loc[(trades['open_time'] >= trades_start) &
|
trades = trades.loc[(trades['open_date'] >= trades_start) &
|
||||||
(trades['close_time'] <= 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 np.mean(tmp_means)
|
||||||
|
|
||||||
|
|
||||||
def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame],
|
def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame],
|
||||||
column: str = "close") -> pd.DataFrame:
|
column: str = "close") -> pd.DataFrame:
|
||||||
"""
|
"""
|
||||||
@ -198,7 +341,7 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
|||||||
"""
|
"""
|
||||||
Adds a column `col_name` with the cumulative profit for the given trades array.
|
Adds a column `col_name` with the cumulative profit for the given trades array.
|
||||||
:param df: DataFrame with date index
|
:param df: DataFrame with date index
|
||||||
:param trades: DataFrame containing trades (requires columns close_time and profit_percent)
|
:param trades: DataFrame containing trades (requires columns close_date and profit_percent)
|
||||||
:param col_name: Column name that will be assigned the results
|
:param col_name: Column name that will be assigned the results
|
||||||
:param timeframe: Timeframe used during the operations
|
:param timeframe: Timeframe used during the operations
|
||||||
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
:return: Returns df with one additional column, col_name, containing the cumulative profit.
|
||||||
@ -209,7 +352,7 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
|||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
timeframe_minutes = timeframe_to_minutes(timeframe)
|
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||||
# Resample to timeframe to make sure trades match candles
|
# Resample to timeframe to make sure trades match candles
|
||||||
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_time'
|
_trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_date'
|
||||||
)[['profit_percent']].sum()
|
)[['profit_percent']].sum()
|
||||||
df.loc[:, col_name] = _trades_sum.cumsum()
|
df.loc[:, col_name] = _trades_sum.cumsum()
|
||||||
# Set first value to 0
|
# Set first value to 0
|
||||||
@ -219,13 +362,13 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
|
|||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_time',
|
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date',
|
||||||
value_col: str = 'profit_percent'
|
value_col: str = 'profit_percent'
|
||||||
) -> Tuple[float, pd.Timestamp, pd.Timestamp]:
|
) -> Tuple[float, pd.Timestamp, pd.Timestamp]:
|
||||||
"""
|
"""
|
||||||
Calculate max drawdown and the corresponding close dates
|
Calculate max drawdown and the corresponding close dates
|
||||||
:param trades: DataFrame containing trades (requires columns close_time and profit_percent)
|
:param trades: DataFrame containing trades (requires columns close_date and profit_percent)
|
||||||
:param date_col: Column in DataFrame to use for dates (defaults to 'close_time')
|
:param date_col: Column in DataFrame to use for dates (defaults to 'close_date')
|
||||||
:param value_col: Column in DataFrame to use for values (defaults to 'profit_percent')
|
:param value_col: Column in DataFrame to use for values (defaults to 'profit_percent')
|
||||||
:return: Tuple (float, highdate, lowdate) with absolute max drawdown, high and low time
|
:return: Tuple (float, highdate, lowdate) with absolute max drawdown, high and low time
|
||||||
:raise: ValueError if trade-dataframe was found empty.
|
:raise: ValueError if trade-dataframe was found empty.
|
||||||
|
@ -10,8 +10,8 @@ from typing import Any, Dict, List
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas import DataFrame, to_datetime
|
from pandas import DataFrame, to_datetime
|
||||||
|
|
||||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS,
|
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
|
||||||
DEFAULT_TRADES_COLUMNS)
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -168,7 +168,7 @@ def trades_remove_duplicates(trades: List[List]) -> List[List]:
|
|||||||
return [i for i, _ in itertools.groupby(sorted(trades, key=itemgetter(0)))]
|
return [i for i, _ in itertools.groupby(sorted(trades, key=itemgetter(0)))]
|
||||||
|
|
||||||
|
|
||||||
def trades_dict_to_list(trades: List[Dict]) -> List[List]:
|
def trades_dict_to_list(trades: List[Dict]) -> TradeList:
|
||||||
"""
|
"""
|
||||||
Convert fetch_trades result into a List (to be more memory efficient).
|
Convert fetch_trades result into a List (to be more memory efficient).
|
||||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||||
@ -177,16 +177,18 @@ def trades_dict_to_list(trades: List[Dict]) -> List[List]:
|
|||||||
return [[t[col] for col in DEFAULT_TRADES_COLUMNS] for t in trades]
|
return [[t[col] for col in DEFAULT_TRADES_COLUMNS] for t in trades]
|
||||||
|
|
||||||
|
|
||||||
def trades_to_ohlcv(trades: List, timeframe: str) -> DataFrame:
|
def trades_to_ohlcv(trades: TradeList, timeframe: str) -> DataFrame:
|
||||||
"""
|
"""
|
||||||
Converts trades list to OHLCV list
|
Converts trades list to OHLCV list
|
||||||
TODO: This should get a dedicated test
|
|
||||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||||
:param timeframe: Timeframe to resample data to
|
:param timeframe: Timeframe to resample data to
|
||||||
:return: OHLCV Dataframe.
|
:return: OHLCV Dataframe.
|
||||||
|
:raises: ValueError if no trades are provided
|
||||||
"""
|
"""
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
timeframe_minutes = timeframe_to_minutes(timeframe)
|
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
if not trades:
|
||||||
|
raise ValueError('Trade-list empty.')
|
||||||
df = pd.DataFrame(trades, columns=DEFAULT_TRADES_COLUMNS)
|
df = pd.DataFrame(trades, columns=DEFAULT_TRADES_COLUMNS)
|
||||||
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms',
|
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms',
|
||||||
utc=True,)
|
utc=True,)
|
||||||
@ -236,12 +238,12 @@ def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to:
|
|||||||
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)
|
||||||
trg = get_datahandler(config['datadir'], convert_to)
|
trg = get_datahandler(config['datadir'], convert_to)
|
||||||
timeframes = config.get('timeframes', [config.get('ticker_interval')])
|
timeframes = config.get('timeframes', [config.get('timeframe')])
|
||||||
logger.info(f"Converting candle (OHLCV) for timeframe {timeframes}")
|
logger.info(f"Converting candle (OHLCV) for timeframe {timeframes}")
|
||||||
|
|
||||||
if 'pairs' not in config:
|
if 'pairs' not in config:
|
||||||
config['pairs'] = []
|
config['pairs'] = []
|
||||||
# Check timeframes or fall back to ticker_interval.
|
# 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(config['datadir'],
|
||||||
timeframe))
|
timeframe))
|
||||||
@ -255,7 +257,8 @@ def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to:
|
|||||||
drop_incomplete=False,
|
drop_incomplete=False,
|
||||||
startup_candles=0)
|
startup_candles=0)
|
||||||
logger.info(f"Converting {len(data)} candles for {pair}")
|
logger.info(f"Converting {len(data)} candles for {pair}")
|
||||||
trg.ohlcv_store(pair=pair, timeframe=timeframe, data=data)
|
if len(data) > 0:
|
||||||
if erase and convert_from != convert_to:
|
trg.ohlcv_store(pair=pair, timeframe=timeframe, data=data)
|
||||||
logger.info(f"Deleting source data for {pair} / {timeframe}")
|
if erase and convert_from != convert_to:
|
||||||
src.ohlcv_purge(pair=pair, timeframe=timeframe)
|
logger.info(f"Deleting source data for {pair} / {timeframe}")
|
||||||
|
src.ohlcv_purge(pair=pair, timeframe=timeframe)
|
||||||
|
@ -5,15 +5,16 @@ including ticker and orderbook data, live and historical candle (OHLCV) data
|
|||||||
Common Interface for bot and strategy to access data.
|
Common Interface for bot and strategy to access data.
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, List, Optional
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe
|
||||||
from freqtrade.data.history import load_pair_history
|
from freqtrade.data.history import load_pair_history
|
||||||
from freqtrade.exceptions import DependencyException, OperationalException
|
from freqtrade.exceptions import ExchangeError, OperationalException
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.state import RunMode
|
from freqtrade.state import RunMode
|
||||||
from freqtrade.constants import ListPairsWithTimeframes
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -25,6 +26,24 @@ class DataProvider:
|
|||||||
self._config = config
|
self._config = config
|
||||||
self._exchange = exchange
|
self._exchange = exchange
|
||||||
self._pairlists = pairlists
|
self._pairlists = pairlists
|
||||||
|
self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {}
|
||||||
|
|
||||||
|
def _set_cached_df(self, pair: str, timeframe: str, dataframe: DataFrame) -> None:
|
||||||
|
"""
|
||||||
|
Store cached Dataframe.
|
||||||
|
Using private method as this should never be used by a user
|
||||||
|
(but the class is exposed via `self.dp` to the strategy)
|
||||||
|
:param pair: pair to get the data for
|
||||||
|
:param timeframe: Timeframe to get data for
|
||||||
|
:param dataframe: analyzed dataframe
|
||||||
|
"""
|
||||||
|
self.__cached_pairs[(pair, timeframe)] = (dataframe, datetime.now(timezone.utc))
|
||||||
|
|
||||||
|
def add_pairlisthandler(self, pairlists) -> None:
|
||||||
|
"""
|
||||||
|
Allow adding pairlisthandler after initialization
|
||||||
|
"""
|
||||||
|
self._pairlists = pairlists
|
||||||
|
|
||||||
def refresh(self,
|
def refresh(self,
|
||||||
pairlist: ListPairsWithTimeframes,
|
pairlist: ListPairsWithTimeframes,
|
||||||
@ -55,7 +74,7 @@ class DataProvider:
|
|||||||
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.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['ticker_interval']),
|
return self._exchange.klines((pair, timeframe or self._config['timeframe']),
|
||||||
copy=copy)
|
copy=copy)
|
||||||
else:
|
else:
|
||||||
return DataFrame()
|
return DataFrame()
|
||||||
@ -67,8 +86,9 @@ class DataProvider:
|
|||||||
:param timeframe: timeframe to get data for
|
:param timeframe: timeframe to get data for
|
||||||
"""
|
"""
|
||||||
return load_pair_history(pair=pair,
|
return load_pair_history(pair=pair,
|
||||||
timeframe=timeframe or self._config['ticker_interval'],
|
timeframe=timeframe or self._config['timeframe'],
|
||||||
datadir=self._config['datadir']
|
datadir=self._config['datadir'],
|
||||||
|
data_format=self._config.get('dataformat_ohlcv', 'json')
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame:
|
def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame:
|
||||||
@ -89,6 +109,20 @@ class DataProvider:
|
|||||||
logger.warning(f"No data found for ({pair}, {timeframe}).")
|
logger.warning(f"No data found for ({pair}, {timeframe}).")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
def get_analyzed_dataframe(self, pair: str, timeframe: str) -> Tuple[DataFrame, datetime]:
|
||||||
|
"""
|
||||||
|
:param pair: pair to get the data for
|
||||||
|
:param timeframe: timeframe to get data for
|
||||||
|
:return: Tuple of (Analyzed Dataframe, lastrefreshed) for the requested pair / timeframe
|
||||||
|
combination.
|
||||||
|
Returns empty dataframe and Epoch 0 (1970-01-01) if no dataframe was cached.
|
||||||
|
"""
|
||||||
|
if (pair, timeframe) in self.__cached_pairs:
|
||||||
|
return self.__cached_pairs[(pair, timeframe)]
|
||||||
|
else:
|
||||||
|
|
||||||
|
return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc))
|
||||||
|
|
||||||
def market(self, pair: str) -> Optional[Dict[str, Any]]:
|
def market(self, pair: str) -> Optional[Dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
Return market data for the pair
|
Return market data for the pair
|
||||||
@ -105,7 +139,7 @@ class DataProvider:
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return self._exchange.fetch_ticker(pair)
|
return self._exchange.fetch_ticker(pair)
|
||||||
except DependencyException:
|
except ExchangeError:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def orderbook(self, pair: str, maximum: int) -> Dict[str, List]:
|
def orderbook(self, pair: str, maximum: int) -> Dict[str, List]:
|
||||||
|
@ -5,10 +5,8 @@ Includes:
|
|||||||
* load data for a pair (or a list of pairs) from disk
|
* load data for a pair (or a list of pairs) from disk
|
||||||
* download data from exchange and store to disk
|
* download data from exchange and store to disk
|
||||||
"""
|
"""
|
||||||
|
# flake8: noqa: F401
|
||||||
from .history_utils import (convert_trades_to_ohlcv, # noqa: F401
|
from .history_utils import (convert_trades_to_ohlcv, get_timerange, load_data, load_pair_history,
|
||||||
get_timerange, load_data, load_pair_history,
|
refresh_backtest_ohlcv_data, refresh_backtest_trades_data, refresh_data,
|
||||||
refresh_backtest_ohlcv_data,
|
|
||||||
refresh_backtest_trades_data, refresh_data,
|
|
||||||
validate_backtest_data)
|
validate_backtest_data)
|
||||||
from .idatahandler import get_datahandler # noqa: F401
|
from .idatahandler import get_datahandler
|
||||||
|
213
freqtrade/data/history/hdf5datahandler.py
Normal file
213
freqtrade/data/history/hdf5datahandler.py
Normal file
@ -0,0 +1,213 @@
|
|||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from freqtrade import misc
|
||||||
|
from freqtrade.configuration import TimeRange
|
||||||
|
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS,
|
||||||
|
ListPairsWithTimeframes, TradeList)
|
||||||
|
|
||||||
|
from .idatahandler import IDataHandler
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class HDF5DataHandler(IDataHandler):
|
||||||
|
|
||||||
|
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def ohlcv_get_available_data(cls, datadir: Path) -> ListPairsWithTimeframes:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:return: List of Tuples of (pair, timeframe)
|
||||||
|
"""
|
||||||
|
_tmp = [re.search(r'^([a-zA-Z_]+)\-(\d+\S+)(?=.h5)', p.name)
|
||||||
|
for p in datadir.glob("*.h5")]
|
||||||
|
return [(match[1].replace('_', '/'), match[2]) for match in _tmp
|
||||||
|
if match and len(match.groups()) > 1]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
|
for the specified timeframe
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:param timeframe: Timeframe to search pairs for
|
||||||
|
:return: List of Pairs
|
||||||
|
"""
|
||||||
|
|
||||||
|
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + '.h5)', p.name)
|
||||||
|
for p in datadir.glob(f"*{timeframe}.h5")]
|
||||||
|
# Check if regex found something and only return these results
|
||||||
|
return [match[0].replace('_', '/') for match in _tmp if match]
|
||||||
|
|
||||||
|
def ohlcv_store(self, pair: str, timeframe: str, data: pd.DataFrame) -> None:
|
||||||
|
"""
|
||||||
|
Store data in hdf5 file.
|
||||||
|
:param pair: Pair - used to generate filename
|
||||||
|
:timeframe: Timeframe - used to generate filename
|
||||||
|
:data: Dataframe containing OHLCV data
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
key = self._pair_ohlcv_key(pair, timeframe)
|
||||||
|
_data = data.copy()
|
||||||
|
|
||||||
|
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
||||||
|
|
||||||
|
ds = pd.HDFStore(filename, mode='a', complevel=9, complib='blosc')
|
||||||
|
ds.put(key, _data.loc[:, self._columns], format='table', data_columns=['date'])
|
||||||
|
|
||||||
|
ds.close()
|
||||||
|
|
||||||
|
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||||
|
timerange: Optional[TimeRange] = None) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Internal method used to load data for one pair from disk.
|
||||||
|
Implements the loading and conversion to a Pandas dataframe.
|
||||||
|
Timerange trimming and dataframe validation happens outside of this method.
|
||||||
|
:param pair: Pair to load data
|
||||||
|
:param timeframe: Timeframe (e.g. "5m")
|
||||||
|
:param timerange: Limit data to be loaded to this timerange.
|
||||||
|
Optionally implemented by subclasses to avoid loading
|
||||||
|
all data where possible.
|
||||||
|
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||||
|
"""
|
||||||
|
key = self._pair_ohlcv_key(pair, timeframe)
|
||||||
|
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
||||||
|
|
||||||
|
if not filename.exists():
|
||||||
|
return pd.DataFrame(columns=self._columns)
|
||||||
|
where = []
|
||||||
|
if timerange:
|
||||||
|
if timerange.starttype == 'date':
|
||||||
|
where.append(f"date >= Timestamp({timerange.startts * 1e9})")
|
||||||
|
if timerange.stoptype == 'date':
|
||||||
|
where.append(f"date < Timestamp({timerange.stopts * 1e9})")
|
||||||
|
|
||||||
|
pairdata = pd.read_hdf(filename, key=key, mode="r", where=where)
|
||||||
|
|
||||||
|
if list(pairdata.columns) != self._columns:
|
||||||
|
raise ValueError("Wrong dataframe format")
|
||||||
|
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
||||||
|
'low': 'float', 'close': 'float', 'volume': 'float'})
|
||||||
|
return pairdata
|
||||||
|
|
||||||
|
def ohlcv_purge(self, pair: str, timeframe: str) -> bool:
|
||||||
|
"""
|
||||||
|
Remove data for this pair
|
||||||
|
:param pair: Delete data for this pair.
|
||||||
|
:param timeframe: Timeframe (e.g. "5m")
|
||||||
|
:return: True when deleted, false if file did not exist.
|
||||||
|
"""
|
||||||
|
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: pd.DataFrame) -> None:
|
||||||
|
"""
|
||||||
|
Append data to existing data structures
|
||||||
|
:param pair: Pair
|
||||||
|
:param timeframe: Timeframe this ohlcv data is for
|
||||||
|
:param data: Data to append.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs for which trade data is available in this
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:return: List of Pairs
|
||||||
|
"""
|
||||||
|
_tmp = [re.search(r'^(\S+)(?=\-trades.h5)', p.name)
|
||||||
|
for p in datadir.glob("*trades.h5")]
|
||||||
|
# Check if regex found something and only return these results to avoid exceptions.
|
||||||
|
return [match[0].replace('_', '/') for match in _tmp if match]
|
||||||
|
|
||||||
|
def trades_store(self, pair: str, data: TradeList) -> None:
|
||||||
|
"""
|
||||||
|
Store trades data (list of Dicts) to file
|
||||||
|
:param pair: Pair - used for filename
|
||||||
|
:param data: List of Lists containing trade data,
|
||||||
|
column sequence as in DEFAULT_TRADES_COLUMNS
|
||||||
|
"""
|
||||||
|
key = self._pair_trades_key(pair)
|
||||||
|
|
||||||
|
ds = pd.HDFStore(self._pair_trades_filename(self._datadir, pair),
|
||||||
|
mode='a', complevel=9, complib='blosc')
|
||||||
|
ds.put(key, pd.DataFrame(data, columns=DEFAULT_TRADES_COLUMNS),
|
||||||
|
format='table', data_columns=['timestamp'])
|
||||||
|
ds.close()
|
||||||
|
|
||||||
|
def trades_append(self, pair: str, data: TradeList):
|
||||||
|
"""
|
||||||
|
Append data to existing files
|
||||||
|
:param pair: Pair - used for filename
|
||||||
|
:param data: List of Lists containing trade data,
|
||||||
|
column sequence as in DEFAULT_TRADES_COLUMNS
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def _trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> TradeList:
|
||||||
|
"""
|
||||||
|
Load a pair from h5 file.
|
||||||
|
:param pair: Load trades for this pair
|
||||||
|
:param timerange: Timerange to load trades for - currently not implemented
|
||||||
|
:return: List of trades
|
||||||
|
"""
|
||||||
|
key = self._pair_trades_key(pair)
|
||||||
|
filename = self._pair_trades_filename(self._datadir, pair)
|
||||||
|
|
||||||
|
if not filename.exists():
|
||||||
|
return []
|
||||||
|
where = []
|
||||||
|
if timerange:
|
||||||
|
if timerange.starttype == 'date':
|
||||||
|
where.append(f"timestamp >= {timerange.startts * 1e3}")
|
||||||
|
if timerange.stoptype == 'date':
|
||||||
|
where.append(f"timestamp < {timerange.stopts * 1e3}")
|
||||||
|
|
||||||
|
trades: pd.DataFrame = pd.read_hdf(filename, key=key, mode="r", where=where)
|
||||||
|
trades[['id', 'type']] = trades[['id', 'type']].replace({np.nan: None})
|
||||||
|
return trades.values.tolist()
|
||||||
|
|
||||||
|
def trades_purge(self, pair: str) -> bool:
|
||||||
|
"""
|
||||||
|
Remove data for this pair
|
||||||
|
:param pair: Delete data for this pair.
|
||||||
|
:return: True when deleted, false if file did not exist.
|
||||||
|
"""
|
||||||
|
filename = self._pair_trades_filename(self._datadir, pair)
|
||||||
|
if filename.exists():
|
||||||
|
filename.unlink()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _pair_ohlcv_key(cls, pair: str, timeframe: str) -> str:
|
||||||
|
return f"{pair}/ohlcv/tf_{timeframe}"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _pair_trades_key(cls, pair: str) -> str:
|
||||||
|
return f"{pair}/trades"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _pair_data_filename(cls, datadir: Path, pair: str, timeframe: str) -> Path:
|
||||||
|
pair_s = misc.pair_to_filename(pair)
|
||||||
|
filename = datadir.joinpath(f'{pair_s}-{timeframe}.h5')
|
||||||
|
return filename
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _pair_trades_filename(cls, datadir: Path, pair: str) -> Path:
|
||||||
|
pair_s = misc.pair_to_filename(pair)
|
||||||
|
filename = datadir.joinpath(f'{pair_s}-trades.h5')
|
||||||
|
return filename
|
@ -9,14 +9,14 @@ from pandas import DataFrame
|
|||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
||||||
from freqtrade.data.converter import (ohlcv_to_dataframe,
|
from freqtrade.data.converter import (clean_ohlcv_dataframe, ohlcv_to_dataframe,
|
||||||
trades_remove_duplicates,
|
trades_remove_duplicates, trades_to_ohlcv)
|
||||||
trades_to_ohlcv)
|
|
||||||
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
||||||
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
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -135,7 +135,6 @@ def _load_cached_data_for_updating(pair: str, timeframe: str, timerange: Optiona
|
|||||||
start = None
|
start = None
|
||||||
if timerange:
|
if timerange:
|
||||||
if timerange.starttype == 'date':
|
if timerange.starttype == 'date':
|
||||||
# TODO: convert to date for conversion
|
|
||||||
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||||
|
|
||||||
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
||||||
@ -202,7 +201,10 @@ def _download_pair_history(datadir: Path,
|
|||||||
if data.empty:
|
if data.empty:
|
||||||
data = new_dataframe
|
data = new_dataframe
|
||||||
else:
|
else:
|
||||||
data = data.append(new_dataframe)
|
# Run cleaning again to ensure there were no duplicate candles
|
||||||
|
# Especially between existing and new data.
|
||||||
|
data = clean_ohlcv_dataframe(data.append(new_dataframe), timeframe, pair,
|
||||||
|
fill_missing=False, drop_incomplete=False)
|
||||||
|
|
||||||
logger.debug("New Start: %s",
|
logger.debug("New 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')
|
||||||
@ -212,10 +214,9 @@ def _download_pair_history(datadir: Path,
|
|||||||
data_handler.ohlcv_store(pair, timeframe, data=data)
|
data_handler.ohlcv_store(pair, timeframe, data=data)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception:
|
||||||
logger.error(
|
logger.exception(
|
||||||
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}. '
|
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}.'
|
||||||
f'Error: {e}'
|
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@ -270,6 +271,11 @@ def _download_trades_history(exchange: Exchange,
|
|||||||
# DEFAULT_TRADES_COLUMNS: 0 -> timestamp
|
# DEFAULT_TRADES_COLUMNS: 0 -> timestamp
|
||||||
# DEFAULT_TRADES_COLUMNS: 1 -> id
|
# DEFAULT_TRADES_COLUMNS: 1 -> id
|
||||||
|
|
||||||
|
if trades and since < trades[0][0]:
|
||||||
|
# since is before the first trade
|
||||||
|
logger.info(f"Start earlier than available data. Redownloading trades for {pair}...")
|
||||||
|
trades = []
|
||||||
|
|
||||||
from_id = trades[-1][1] if trades else None
|
from_id = trades[-1][1] if trades else None
|
||||||
if trades and since < trades[-1][0]:
|
if trades and since < trades[-1][0]:
|
||||||
# Reset since to the last available point
|
# Reset since to the last available point
|
||||||
@ -297,10 +303,9 @@ def _download_trades_history(exchange: Exchange,
|
|||||||
logger.info(f"New Amount of trades: {len(trades)}")
|
logger.info(f"New Amount of trades: {len(trades)}")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception:
|
||||||
logger.error(
|
logger.exception(
|
||||||
f'Failed to download historic trades for pair: "{pair}". '
|
f'Failed to download historic trades for pair: "{pair}". '
|
||||||
f'Error: {e}'
|
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@ -349,9 +354,12 @@ def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
|||||||
if erase:
|
if erase:
|
||||||
if data_handler_ohlcv.ohlcv_purge(pair, timeframe):
|
if data_handler_ohlcv.ohlcv_purge(pair, timeframe):
|
||||||
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
try:
|
||||||
# Store ohlcv
|
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||||
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv)
|
# Store ohlcv
|
||||||
|
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv)
|
||||||
|
except ValueError:
|
||||||
|
logger.exception(f'Could not convert {pair} to OHLCV.')
|
||||||
|
|
||||||
|
|
||||||
def get_timerange(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
def get_timerange(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||||
|
@ -13,14 +13,12 @@ from typing import List, Optional, Type
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.data.converter import (clean_ohlcv_dataframe,
|
from freqtrade.constants import ListPairsWithTimeframes, TradeList
|
||||||
trades_remove_duplicates, trim_dataframe)
|
from freqtrade.data.converter import clean_ohlcv_dataframe, trades_remove_duplicates, trim_dataframe
|
||||||
from freqtrade.exchange import timeframe_to_seconds
|
from freqtrade.exchange import timeframe_to_seconds
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Type for trades list
|
logger = logging.getLogger(__name__)
|
||||||
TradeList = List[List]
|
|
||||||
|
|
||||||
|
|
||||||
class IDataHandler(ABC):
|
class IDataHandler(ABC):
|
||||||
@ -28,6 +26,14 @@ class IDataHandler(ABC):
|
|||||||
def __init__(self, datadir: Path) -> None:
|
def __init__(self, datadir: Path) -> None:
|
||||||
self._datadir = datadir
|
self._datadir = datadir
|
||||||
|
|
||||||
|
@abstractclassmethod
|
||||||
|
def ohlcv_get_available_data(cls, datadir: Path) -> ListPairsWithTimeframes:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
: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) -> List[str]:
|
||||||
"""
|
"""
|
||||||
@ -41,9 +47,7 @@ class IDataHandler(ABC):
|
|||||||
@abstractmethod
|
@abstractmethod
|
||||||
def ohlcv_store(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
def ohlcv_store(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
||||||
"""
|
"""
|
||||||
Store data in json format "values".
|
Store ohlcv data.
|
||||||
format looks as follows:
|
|
||||||
[[<date>,<open>,<high>,<low>,<close>]]
|
|
||||||
:param pair: Pair - used to generate filename
|
:param pair: Pair - used to generate filename
|
||||||
:timeframe: Timeframe - used to generate filename
|
:timeframe: Timeframe - used to generate filename
|
||||||
:data: Dataframe containing OHLCV data
|
:data: Dataframe containing OHLCV data
|
||||||
@ -230,6 +234,9 @@ def get_datahandlerclass(datatype: str) -> Type[IDataHandler]:
|
|||||||
elif datatype == 'jsongz':
|
elif datatype == 'jsongz':
|
||||||
from .jsondatahandler import JsonGzDataHandler
|
from .jsondatahandler import JsonGzDataHandler
|
||||||
return JsonGzDataHandler
|
return JsonGzDataHandler
|
||||||
|
elif datatype == 'hdf5':
|
||||||
|
from .hdf5datahandler import HDF5DataHandler
|
||||||
|
return HDF5DataHandler
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"No datahandler for datatype {datatype} available.")
|
raise ValueError(f"No datahandler for datatype {datatype} available.")
|
||||||
|
|
||||||
|
@ -8,10 +8,11 @@ from pandas import DataFrame, read_json, to_datetime
|
|||||||
|
|
||||||
from freqtrade import misc
|
from freqtrade import misc
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
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 .idatahandler import IDataHandler, TradeList
|
from .idatahandler import IDataHandler
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -21,6 +22,18 @@ class JsonDataHandler(IDataHandler):
|
|||||||
_use_zip = False
|
_use_zip = False
|
||||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def ohlcv_get_available_data(cls, datadir: Path) -> ListPairsWithTimeframes:
|
||||||
|
"""
|
||||||
|
Returns a list of all pairs with ohlcv data available in this datadir
|
||||||
|
:param datadir: Directory to search for ohlcv files
|
||||||
|
:return: List of Tuples of (pair, timeframe)
|
||||||
|
"""
|
||||||
|
_tmp = [re.search(r'^([a-zA-Z_]+)\-(\d+\S+)(?=.json)', p.name)
|
||||||
|
for p in datadir.glob(f"*.{cls._get_file_extension()}")]
|
||||||
|
return [(match[1].replace('_', '/'), match[2]) 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) -> List[str]:
|
||||||
"""
|
"""
|
||||||
|
@ -9,11 +9,12 @@ import utils_find_1st as utf1st
|
|||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT
|
from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
|
||||||
from freqtrade.exceptions import OperationalException
|
|
||||||
from freqtrade.data.history import get_timerange, load_data, refresh_data
|
from freqtrade.data.history import get_timerange, load_data, refresh_data
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.strategy.interface import SellType
|
from freqtrade.strategy.interface import SellType
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -86,7 +87,7 @@ class Edge:
|
|||||||
heartbeat = self.edge_config.get('process_throttle_secs')
|
heartbeat = self.edge_config.get('process_throttle_secs')
|
||||||
|
|
||||||
if (self._last_updated > 0) and (
|
if (self._last_updated > 0) and (
|
||||||
self._last_updated + heartbeat > arrow.utcnow().timestamp):
|
self._last_updated + heartbeat > arrow.utcnow().int_timestamp):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
data: Dict[str, Any] = {}
|
data: Dict[str, Any] = {}
|
||||||
@ -98,14 +99,14 @@ class Edge:
|
|||||||
datadir=self.config['datadir'],
|
datadir=self.config['datadir'],
|
||||||
pairs=pairs,
|
pairs=pairs,
|
||||||
exchange=self.exchange,
|
exchange=self.exchange,
|
||||||
timeframe=self.strategy.ticker_interval,
|
timeframe=self.strategy.timeframe,
|
||||||
timerange=self._timerange,
|
timerange=self._timerange,
|
||||||
)
|
)
|
||||||
|
|
||||||
data = load_data(
|
data = load_data(
|
||||||
datadir=self.config['datadir'],
|
datadir=self.config['datadir'],
|
||||||
pairs=pairs,
|
pairs=pairs,
|
||||||
timeframe=self.strategy.ticker_interval,
|
timeframe=self.strategy.timeframe,
|
||||||
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'),
|
||||||
@ -121,12 +122,9 @@ class Edge:
|
|||||||
|
|
||||||
# Print timeframe
|
# Print timeframe
|
||||||
min_date, max_date = get_timerange(preprocessed)
|
min_date, max_date = get_timerange(preprocessed)
|
||||||
logger.info(
|
logger.info(f'Measuring data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
|
||||||
'Measuring data from %s up to %s (%s days) ...',
|
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
|
||||||
min_date.isoformat(),
|
f'({(max_date - min_date).days} days)..')
|
||||||
max_date.isoformat(),
|
|
||||||
(max_date - min_date).days
|
|
||||||
)
|
|
||||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'high', 'low']
|
headers = ['date', 'buy', 'open', 'close', 'sell', 'high', 'low']
|
||||||
|
|
||||||
trades: list = []
|
trades: list = []
|
||||||
@ -148,7 +146,7 @@ class Edge:
|
|||||||
# Fill missing, calculable columns, profit, duration , abs etc.
|
# Fill missing, calculable columns, profit, duration , abs etc.
|
||||||
trades_df = self._fill_calculable_fields(DataFrame(trades))
|
trades_df = self._fill_calculable_fields(DataFrame(trades))
|
||||||
self._cached_pairs = self._process_expectancy(trades_df)
|
self._cached_pairs = self._process_expectancy(trades_df)
|
||||||
self._last_updated = arrow.utcnow().timestamp
|
self._last_updated = arrow.utcnow().int_timestamp
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@ -240,7 +238,7 @@ class Edge:
|
|||||||
# All returned values are relative, they are defined as ratios.
|
# All returned values are relative, they are defined as ratios.
|
||||||
stake = 0.015
|
stake = 0.015
|
||||||
|
|
||||||
result['trade_duration'] = result['close_time'] - result['open_time']
|
result['trade_duration'] = result['close_date'] - result['open_date']
|
||||||
|
|
||||||
result['trade_duration'] = result['trade_duration'].map(
|
result['trade_duration'] = result['trade_duration'].map(
|
||||||
lambda x: int(x.total_seconds() / 60))
|
lambda x: int(x.total_seconds() / 60))
|
||||||
@ -281,8 +279,8 @@ class Edge:
|
|||||||
#
|
#
|
||||||
# Removing Pumps
|
# Removing Pumps
|
||||||
if self.edge_config.get('remove_pumps', False):
|
if self.edge_config.get('remove_pumps', False):
|
||||||
results = results.groupby(['pair', 'stoploss']).apply(
|
results = results[results['profit_abs'] < 2 * results['profit_abs'].std()
|
||||||
lambda x: x[x['profit_abs'] < 2 * x['profit_abs'].std() + x['profit_abs'].mean()])
|
+ results['profit_abs'].mean()]
|
||||||
##########################################################################
|
##########################################################################
|
||||||
|
|
||||||
# Removing trades having a duration more than X minutes (set in config)
|
# Removing trades having a duration more than X minutes (set in config)
|
||||||
@ -312,8 +310,10 @@ class Edge:
|
|||||||
|
|
||||||
# Calculating number of losing trades, average win and average loss
|
# Calculating number of losing trades, average win and average loss
|
||||||
df['nb_loss_trades'] = df['nb_trades'] - df['nb_win_trades']
|
df['nb_loss_trades'] = df['nb_trades'] - df['nb_win_trades']
|
||||||
df['average_win'] = df['profit_sum'] / df['nb_win_trades']
|
df['average_win'] = np.where(df['nb_win_trades'] == 0, 0.0,
|
||||||
df['average_loss'] = df['loss_sum'] / df['nb_loss_trades']
|
df['profit_sum'] / df['nb_win_trades'])
|
||||||
|
df['average_loss'] = np.where(df['nb_loss_trades'] == 0, 0.0,
|
||||||
|
df['loss_sum'] / df['nb_loss_trades'])
|
||||||
|
|
||||||
# Win rate = number of profitable trades / number of trades
|
# Win rate = number of profitable trades / number of trades
|
||||||
df['winrate'] = df['nb_win_trades'] / df['nb_trades']
|
df['winrate'] = df['nb_win_trades'] / df['nb_trades']
|
||||||
@ -430,10 +430,8 @@ class Edge:
|
|||||||
'stoploss': stoploss,
|
'stoploss': stoploss,
|
||||||
'profit_ratio': '',
|
'profit_ratio': '',
|
||||||
'profit_abs': '',
|
'profit_abs': '',
|
||||||
'open_time': date_column[open_trade_index],
|
'open_date': date_column[open_trade_index],
|
||||||
'close_time': date_column[exit_index],
|
'close_date': date_column[exit_index],
|
||||||
'open_index': start_point + open_trade_index,
|
|
||||||
'close_index': start_point + exit_index,
|
|
||||||
'trade_duration': '',
|
'trade_duration': '',
|
||||||
'open_rate': round(open_price, 15),
|
'open_rate': round(open_price, 15),
|
||||||
'close_rate': round(exit_price, 15),
|
'close_rate': round(exit_price, 15),
|
||||||
|
@ -29,7 +29,14 @@ class PricingError(DependencyException):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class InvalidOrderException(FreqtradeException):
|
class ExchangeError(DependencyException):
|
||||||
|
"""
|
||||||
|
Error raised out of the exchange.
|
||||||
|
Has multiple Errors to determine the appropriate error.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidOrderException(ExchangeError):
|
||||||
"""
|
"""
|
||||||
This is returned when the order is not valid. Example:
|
This is returned when the order is not valid. Example:
|
||||||
If stoploss on exchange order is hit, then trying to cancel the order
|
If stoploss on exchange order is hit, then trying to cancel the order
|
||||||
@ -37,7 +44,21 @@ class InvalidOrderException(FreqtradeException):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class TemporaryError(FreqtradeException):
|
class RetryableOrderError(InvalidOrderException):
|
||||||
|
"""
|
||||||
|
This is returned when the order is not found.
|
||||||
|
This Error will be repeated with increasing backof (in line with DDosError).
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class InsufficientFundsError(InvalidOrderException):
|
||||||
|
"""
|
||||||
|
This error is used when there are not enough funds available on the exchange
|
||||||
|
to create an order.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class TemporaryError(ExchangeError):
|
||||||
"""
|
"""
|
||||||
Temporary network or exchange related error.
|
Temporary network or exchange related error.
|
||||||
This could happen when an exchange is congested, unavailable, or the user
|
This could happen when an exchange is congested, unavailable, or the user
|
||||||
@ -45,6 +66,13 @@ class TemporaryError(FreqtradeException):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class DDosProtection(TemporaryError):
|
||||||
|
"""
|
||||||
|
Temporary error caused by DDOS protection.
|
||||||
|
Bot will wait for a second and then retry.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
class StrategyError(FreqtradeException):
|
class StrategyError(FreqtradeException):
|
||||||
"""
|
"""
|
||||||
Errors with custom user-code deteced.
|
Errors with custom user-code deteced.
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user