Compare commits
463 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e73f215a67 | |||
| 96c5db3e38 | |||
| c7f248fe3b | |||
| e27636b798 | |||
| 2d56b1bc8c | |||
| 659cbd987a | |||
| aff5372a8f | |||
| 2e7b5e2be9 | |||
| 7971cb29bb | |||
| 154149ff03 | |||
| 92d7f27983 | |||
| 20ea679b2b | |||
| 39ede449a0 | |||
| 37550d3bdb | |||
| b688526623 | |||
| d52d30cfbe | |||
| 9cf08e0434 | |||
| 56a85690b4 | |||
| 0f2612c231 | |||
| f9edc72f35 | |||
| 90475e52db | |||
| 504f51fabb | |||
| a905d1bd67 | |||
| a27baf1a51 | |||
| f174c2e01e | |||
| 3f60b2c140 | |||
| 927d1d2686 | |||
| d04a4db270 | |||
| ed45dcdf8a | |||
| e518e741af | |||
| 56b9c250ba | |||
| a009816ac4 | |||
| c29d2ac05b | |||
| 551d1b0962 | |||
| 5e696f4ea0 | |||
| d8423272da | |||
| b605d4d71f | |||
| c39290d7da | |||
| 4849b23fd6 | |||
| c1beb0ff33 | |||
| d08a015b45 | |||
| 4f7487e931 | |||
| d032aaaba0 | |||
| 073cb0a5a9 | |||
| ce6c44eda0 | |||
| 0099381dd0 | |||
| 7bcb3d5580 | |||
| c15c13a367 | |||
| 53a7273065 | |||
| da9a8b616e | |||
| e6277222ca | |||
| 8002b476ff | |||
| d9b5d05e2a | |||
| f5d7a4417d | |||
| 04b3b1d4d9 | |||
| 38a3ce6164 | |||
| 123e51774e | |||
| 2322d0f3f3 | |||
| 8a5287581f | |||
| 41cdd28f5f | |||
| b387c315da | |||
| 3c647a3794 | |||
| aac9ee0d55 | |||
| 966247baaf | |||
| 589b9858f4 | |||
| c0b2b0b96d | |||
| 6cfc1836a2 | |||
| 35800f3ada | |||
| 9fa365e766 | |||
| a4a3b19566 | |||
| 8452399c12 | |||
| ff8a5ad2e5 | |||
| dda5a59019 | |||
| 30e8466cae | |||
| 3881c51892 | |||
| 4959d124ad | |||
| f133ee3cca | |||
| ef6afaa2cb | |||
| 0e406c4d7d | |||
| b21775142d | |||
| 8ccc66cd97 | |||
| b4e732617e | |||
| 450219c83b | |||
| eb7df30061 | |||
| 9385400000 | |||
| 961f50e335 | |||
| 478e6f1e64 | |||
| a0e115ebd9 | |||
| ce4f1b0709 | |||
| b0c639bac8 | |||
| aba576f79f | |||
| d92a6d7b73 | |||
| 89d47ffd8f | |||
| b9e9f82503 | |||
| 08b94a2077 | |||
| 9f445cb053 | |||
| 1d23ba6e30 | |||
| 28e43a4867 | |||
| 1b28521875 | |||
| 4ba3363bc6 | |||
| f1ed9ed048 | |||
| d465fcffd5 | |||
| 32b0098ec1 | |||
| e77b9de89e | |||
| aec67cda66 | |||
| f3fb801b33 | |||
| fe33088245 | |||
| 4bca8b97f3 | |||
| f62f4f7711 | |||
| 896e2b6285 | |||
| ddb0ae10b4 | |||
| 37fa186c55 | |||
| 979e485f24 | |||
| 1555667da7 | |||
| 8a52a7b50d | |||
| a74b6df14e | |||
| 8600ae0387 | |||
| 02306884f0 | |||
| 82ce5af454 | |||
| 830f2219c8 | |||
| d21f0f4081 | |||
| 8f883f2310 | |||
| 2f63b0199d | |||
| 5a96c775fd | |||
| cfdd9d6be9 | |||
| c749aae19f | |||
| fd4877759c | |||
| 2e7acb4482 | |||
| b43b60b26d | |||
| 5ca8076072 | |||
| 8d3c2470e3 | |||
| 3f85f3cce6 | |||
| 2801bccdc7 | |||
| 22651a8629 | |||
| c7106a6802 | |||
| 6e1f457fb3 | |||
| 533a16658c | |||
| 9b35dae465 | |||
| e6d01b04ea | |||
| d185b2020a | |||
| 74ed0e0b11 | |||
| 75f89ec12f | |||
| f6fce2162c | |||
| 158bf09774 | |||
| 1f1abfe798 | |||
| 29a5e049b9 | |||
| 2bc0c4ecd5 | |||
| 224213840d | |||
| d81fdeb3ed | |||
| 14c5f435aa | |||
| 5745722a37 | |||
| a7cd9d77f2 | |||
| 5b857aeaf0 | |||
| afb1b787c8 | |||
| 659168d341 | |||
| 3f4715ba49 | |||
| 1d0f1bd1ee | |||
| 220bc3c23e | |||
| c90be601f5 | |||
| 5d8e0573f6 | |||
| 3d858f6599 | |||
| 6d2d5f93d0 | |||
| d01bc0fb9f | |||
| 394d758d32 | |||
| 91c710408a | |||
| 3a7f390510 | |||
| a7d6efdcd6 | |||
| fed24c1308 | |||
| ae4021da14 | |||
| 8378a0234d | |||
| d26869ea0a | |||
| cf96ad1d1b | |||
| 3919bf3740 | |||
| 9814cf5360 | |||
| c19fe95d39 | |||
| 383bdb7d56 | |||
| 41765b14dc | |||
| 33bf7f9f30 | |||
| 454c2343a8 | |||
| 6d8bf75572 | |||
| 310c9f6034 | |||
| c0a600858f | |||
| 5b07385414 | |||
| 844ab4aef5 | |||
| 44ca6f1c46 | |||
| 552f947248 | |||
| 7655bf6ea7 | |||
| 25ae25248c | |||
| dd01ae880f | |||
| e0a06ca454 | |||
| a93592c467 | |||
| 08dffc95d8 | |||
| 57800e78c7 | |||
| bd4d7efbc9 | |||
| 5019fb5bf3 | |||
| a0e0d7fe27 | |||
| 6377fd2689 | |||
| bd9ea9bd8c | |||
| cfeefa8754 | |||
| 475d8486bb | |||
| 628963c207 | |||
| 4d1810c2b6 | |||
| 05f0dccb8e | |||
| 6360e7fb15 | |||
| 40695a39d5 | |||
| 008f621211 | |||
| a52cf42218 | |||
| a866b0a35e | |||
| af1054fa70 | |||
| 5608bbde9c | |||
| ee9d2c637a | |||
| f0819d9df1 | |||
| 96e5615d1b | |||
| 4798dea6e1 | |||
| 23a4ff9f25 | |||
| 5ddfbea611 | |||
| e8e67d1c85 | |||
| dc9c31252b | |||
| 82baa3f93f | |||
| 78ca11155b | |||
| 45c90c2013 | |||
| 3a1057e1ff | |||
| e45d5d3594 | |||
| 14ee5a2076 | |||
| da83243eb3 | |||
| 46ec7d5ea6 | |||
| 29fbac9f96 | |||
| 421a6c02a0 | |||
| 2ee152c5a6 | |||
| bef27467b6 | |||
| 52f971cbb7 | |||
| 563e68e894 | |||
| 49b4ab6d3b | |||
| 7455e56a29 | |||
| 245a67e37e | |||
| e76d4241a0 | |||
| 01ff054a0b | |||
| 9e1f7dc6f7 | |||
| 067c9219b6 | |||
| f4e5ce892b | |||
| 830fc7580c | |||
| 21859f79db | |||
| 376b5fce54 | |||
| cb5cd5cd86 | |||
| f8b97b6aa7 | |||
| 7b6e2eac49 | |||
| f13e134e9b | |||
| 97a37198b9 | |||
| 43bb4114d0 | |||
| 8c95207ca4 | |||
| ffaa121bc7 | |||
| 227b194a88 | |||
| 95d8c45481 | |||
| bae4abace2 | |||
| 44461bd1a1 | |||
| 2c095c07f2 | |||
| 9c3656e24e | |||
| 97275f5a46 | |||
| 7ccff18437 | |||
| c5f26e72e1 | |||
| f09c0a5bba | |||
| aba9450098 | |||
| 4ef1647132 | |||
| 6e93bff374 | |||
| 4d20e37f4d | |||
| 20cca01d10 | |||
| 8cbb5d2a93 | |||
| fbae2142d1 | |||
| feea20fb0a | |||
| 2ed52a77e5 | |||
| e854667eb8 | |||
| 7bf20d9060 | |||
| 7c5a11623e | |||
| 783a2d945e | |||
| 2073c71811 | |||
| d8122962db | |||
| 1ea626fb5b | |||
| f66719fc1f | |||
| 4b2813ff37 | |||
| 191c85bccc | |||
| 31816cdb2a | |||
| 574744348a | |||
| efb9975e3e | |||
| cd8743b80c | |||
| 237f3c58c8 | |||
| be7b0e4247 | |||
| 5954e7796c | |||
| f44eef3855 | |||
| 0232eeca54 | |||
| f5f0506a29 | |||
| 39b6a00224 | |||
| 206557d4b7 | |||
| 07e07bd66b | |||
| fac8e0fde5 | |||
| ffb1cf52b1 | |||
| 399f144c27 | |||
| 459b9d80d4 | |||
| 28e685ee2b | |||
| c58a1649cb | |||
| a4512ac791 | |||
| ac6cdb76ce | |||
| 8ac3e8ad5f | |||
| e0f52696a5 | |||
| f75f0ccf2c | |||
| 440f6ab8e1 | |||
| e7daf3177d | |||
| 8ffc0ad9fc | |||
| df83bdea8d | |||
| 420f6fb9a9 | |||
| cea3f7d3fa | |||
| a9f63c6a99 | |||
| 0ada2d9390 | |||
| e1b6b9b5a6 | |||
| 3fea2a35a2 | |||
| 821a598ff4 | |||
| feab5f82c1 | |||
| 607c604a45 | |||
| b77f926cdd | |||
| d2c0e9e438 | |||
| a4077e96ba | |||
| a4fc7ce0c4 | |||
| 00cef56a57 | |||
| d1984945d5 | |||
| 3c20ab683a | |||
| f838bc760f | |||
| 25f5dbfcbd | |||
| be044fbacf | |||
| 7a4276f6c7 | |||
| 925e18368a | |||
| 250e00e6c7 | |||
| 81672da57b | |||
| d68c22b21d | |||
| e806e4a796 | |||
| 6f86e30c7e | |||
| a87404b5a8 | |||
| 0357d373a9 | |||
| 28c62724df | |||
| 1eb90b115b | |||
| d13357bb0c | |||
| 65fe1a671c | |||
| 6429282f05 | |||
| b5fa013600 | |||
| 02bd052e45 | |||
| 4ed46ef6b3 | |||
| 65c7607e36 | |||
| bfc2c70b44 | |||
| 3a6c00dbaf | |||
| 133660ff4e | |||
| 994b2a0f28 | |||
| d4c042c523 | |||
| b48fe4ce51 | |||
| 78f356c0df | |||
| 7263d321f8 | |||
| 1ccbe87f90 | |||
| e7d2a48766 | |||
| c894843d0f | |||
| 23aa8dcd51 | |||
| f3187ddcbf | |||
| 5eb446f1ce | |||
| 5efa40215b | |||
| 1a8b793c0a | |||
| e0e0a25811 | |||
| 99b01a39d1 | |||
| ae08a832c8 | |||
| 2bae4c98b1 | |||
| f717928ae0 | |||
| b66db8e89c | |||
| 3643ad0059 | |||
| 2bdf4c54bd | |||
| 66be4fd159 | |||
| 078a4ca8b6 | |||
| 07ab9bba69 | |||
| a964f56b07 | |||
| 46b8708ffa | |||
| 9136c13cd2 | |||
| 0df9436d06 | |||
| d32aabecd3 | |||
| f2a3dd6414 | |||
| fc23b47c4d | |||
| f256701679 | |||
| c1df94b507 | |||
| f19f3ed4eb | |||
| 2f97b00d31 | |||
| 911e238494 | |||
| 5659ca2ecd | |||
| 0181abc629 | |||
| acda2ff909 | |||
| 43c73c75c5 | |||
| 95daff182d | |||
| b82b77d03f | |||
| 193dcf578d | |||
| 4c0a6611c8 | |||
| 3e986e24fa | |||
| 5cf6f0b491 | |||
| 5ed5907809 | |||
| a78d704998 | |||
| cb85a53042 | |||
| 7f1a81eeed | |||
| 106dffe2c5 | |||
| 070a1990e8 | |||
| ddf79088fb | |||
| 3ed682a9c6 | |||
| 6e32f172be | |||
| bef5e191a4 | |||
| fc60c0df19 | |||
| 62d83b8dbd | |||
| e1eeaa24d2 | |||
| 6249392526 | |||
| 4da8c91161 | |||
| ec8ba821ed | |||
| 6b9547a9ad | |||
| ae9f730624 | |||
| 147cc4f0b6 | |||
| e2274e813a | |||
| d091931279 | |||
| 88925d6c1d | |||
| 2893f0544a | |||
| f397d973f3 | |||
| f224f743da | |||
| be062c5fbe | |||
| 5c0d89feb5 | |||
| 4e6068a923 | |||
| 07c629922a | |||
| 3f506bb474 | |||
| 1c4c2272f5 | |||
| 1ed6f1875b | |||
| ca4ef22d07 | |||
| db5383927c | |||
| 2b88137612 | |||
| 9fddc1499e | |||
| c7f4dc1651 | |||
| 29d77a17e5 | |||
| e34bfa9767 | |||
| d08bad7288 | |||
| ac4e3028d2 | |||
| f1bed95153 | |||
| f3f5b63b7f | |||
| a98e8ef201 | |||
| b031470979 | |||
| 171c4f182d | |||
| 32c919cfad | |||
| bf60f38a23 | |||
| 93994756e8 | |||
| 7c55a2c6e2 | |||
| ee43792566 | |||
| f14b42f202 | |||
| 6e8c765ece | |||
| 5f70406880 | |||
| 069759c7c5 | |||
| ebd5fac91d | |||
| 156c202889 | |||
| 8e0faf4aaa | |||
| 20a2b27498 | |||
| 73d1201ed8 | |||
| fcbacae6f1 | |||
| 60a50a2ea8 | |||
| defa6f45b2 | |||
| 9cdff0b0a5 | |||
| 450fc5763f | |||
| 2495661554 | |||
| ae92557dd7 | |||
| 057f852e06 | |||
| 4874d10455 |
+13
-13
@@ -25,10 +25,10 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ ubuntu-20.04, ubuntu-22.04 ]
|
os: [ ubuntu-20.04, ubuntu-22.04 ]
|
||||||
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
python-version: ["3.9", "3.10", "3.11"]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
@@ -127,10 +127,10 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ macos-latest ]
|
os: [ macos-latest ]
|
||||||
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
python-version: ["3.9", "3.10", "3.11"]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
@@ -237,10 +237,10 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ windows-latest ]
|
os: [ windows-latest ]
|
||||||
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
python-version: ["3.9", "3.10", "3.11"]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
@@ -304,7 +304,7 @@ jobs:
|
|||||||
mypy_version_check:
|
mypy_version_check:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
@@ -319,7 +319,7 @@ jobs:
|
|||||||
pre-commit:
|
pre-commit:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
- uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
@@ -329,7 +329,7 @@ jobs:
|
|||||||
docs_check:
|
docs_check:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Documentation syntax
|
- name: Documentation syntax
|
||||||
run: |
|
run: |
|
||||||
@@ -359,7 +359,7 @@ jobs:
|
|||||||
# Run pytest with "live" checks
|
# Run pytest with "live" checks
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
@@ -443,12 +443,12 @@ jobs:
|
|||||||
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@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: "3.9"
|
python-version: "3.11"
|
||||||
|
|
||||||
- name: Extract branch name
|
- name: Extract branch name
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -515,7 +515,7 @@ jobs:
|
|||||||
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@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Extract branch name
|
- name: Extract branch name
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ jobs:
|
|||||||
dockerHubDescription:
|
dockerHubDescription:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
- name: Docker Hub Description
|
- name: Docker Hub Description
|
||||||
uses: peter-evans/dockerhub-description@v3
|
uses: peter-evans/dockerhub-description@v3
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -83,6 +83,9 @@ instance/
|
|||||||
# Scrapy stuff:
|
# Scrapy stuff:
|
||||||
.scrapy
|
.scrapy
|
||||||
|
|
||||||
|
# memray
|
||||||
|
memray-*
|
||||||
|
|
||||||
# Sphinx documentation
|
# Sphinx documentation
|
||||||
docs/_build/
|
docs/_build/
|
||||||
# Mkdocs documentation
|
# Mkdocs documentation
|
||||||
|
|||||||
@@ -8,17 +8,17 @@ repos:
|
|||||||
# stages: [push]
|
# stages: [push]
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
rev: "v1.5.0"
|
rev: "v1.5.1"
|
||||||
hooks:
|
hooks:
|
||||||
- id: mypy
|
- id: mypy
|
||||||
exclude: build_helpers
|
exclude: build_helpers
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- types-cachetools==5.3.0.6
|
- types-cachetools==5.3.0.6
|
||||||
- types-filelock==3.2.7
|
- types-filelock==3.2.7
|
||||||
- types-requests==2.31.0.2
|
- types-requests==2.31.0.4
|
||||||
- types-tabulate==0.9.0.3
|
- types-tabulate==0.9.0.3
|
||||||
- types-python-dateutil==2.8.19.14
|
- types-python-dateutil==2.8.19.14
|
||||||
- SQLAlchemy==2.0.20
|
- SQLAlchemy==2.0.21
|
||||||
# stages: [push]
|
# stages: [push]
|
||||||
|
|
||||||
- repo: https://github.com/pycqa/isort
|
- repo: https://github.com/pycqa/isort
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM python:3.11.4-slim-bullseye as base
|
FROM python:3.11.5-slim-bullseye as base
|
||||||
|
|
||||||
# Setup env
|
# Setup env
|
||||||
ENV LANG C.UTF-8
|
ENV LANG C.UTF-8
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ Please find the complete documentation on the [freqtrade website](https://www.fr
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- [x] **Based on Python 3.8+**: For botting on any operating system - Windows, macOS and Linux.
|
- [x] **Based on Python 3.9+**: 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 paying money.
|
- [x] **Dry-run**: Run the bot without paying money.
|
||||||
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
- [x] **Backtesting**: Run a simulation of your buy/sell strategy.
|
||||||
@@ -207,7 +207,7 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
|||||||
|
|
||||||
### Software requirements
|
### Software requirements
|
||||||
|
|
||||||
- [Python >= 3.8](http://docs.python-guide.org/en/latest/starting/installation/)
|
- [Python >= 3.9](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://ta-lib.github.io/ta-lib-python/)
|
- [TA-Lib](https://ta-lib.github.io/ta-lib-python/)
|
||||||
|
|||||||
Binary file not shown.
BIN
Binary file not shown.
@@ -32,11 +32,8 @@
|
|||||||
"name": "bittrex",
|
"name": "bittrex",
|
||||||
"key": "your_exchange_key",
|
"key": "your_exchange_key",
|
||||||
"secret": "your_exchange_secret",
|
"secret": "your_exchange_secret",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {},
|
||||||
"enableRateLimit": true,
|
|
||||||
"rateLimit": 500
|
|
||||||
},
|
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
"ETH/BTC",
|
"ETH/BTC",
|
||||||
"LTC/BTC",
|
"LTC/BTC",
|
||||||
|
|||||||
@@ -70,6 +70,7 @@
|
|||||||
},
|
},
|
||||||
"pairlists": [
|
"pairlists": [
|
||||||
{"method": "StaticPairList"},
|
{"method": "StaticPairList"},
|
||||||
|
{"method": "FullTradesFilter"},
|
||||||
{
|
{
|
||||||
"method": "VolumePairList",
|
"method": "VolumePairList",
|
||||||
"number_assets": 20,
|
"number_assets": 20,
|
||||||
|
|||||||
@@ -36,8 +36,9 @@ ENV LD_LIBRARY_PATH /usr/local/lib
|
|||||||
# Install dependencies
|
# Install dependencies
|
||||||
COPY --chown=ftuser:ftuser requirements.txt /freqtrade/
|
COPY --chown=ftuser:ftuser requirements.txt /freqtrade/
|
||||||
USER ftuser
|
USER ftuser
|
||||||
RUN pip install --user --no-cache-dir numpy \
|
RUN pip install --user --no-cache-dir numpy==1.25.2 \
|
||||||
&& pip install --user /tmp/pyarrow-*.whl \
|
&& pip install --user /tmp/pyarrow-*.whl \
|
||||||
|
&& pip install --user --no-build-isolation TA-Lib==0.4.28 \
|
||||||
&& pip install --user --no-cache-dir -r requirements.txt
|
&& pip install --user --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Copy dependencies to runtime-image
|
# Copy dependencies to runtime-image
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|
|||||||
| `exit_pricing.order_book_top` | Bot will use the top N rate in Order Book "price_side" to exit. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in [Order Book Exit](#exit-price-with-orderbook-enabled)<br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
| `exit_pricing.order_book_top` | Bot will use the top N rate in Order Book "price_side" to exit. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in [Order Book Exit](#exit-price-with-orderbook-enabled)<br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||||
| `custom_price_max_distance_ratio` | Configure maximum distance ratio between current and custom entry or exit price. <br>*Defaults to `0.02` 2%).*<br> **Datatype:** Positive float
|
| `custom_price_max_distance_ratio` | Configure maximum distance ratio between current and custom entry or exit price. <br>*Defaults to `0.02` 2%).*<br> **Datatype:** Positive float
|
||||||
| | **TODO**
|
| | **TODO**
|
||||||
| `use_exit_signal` | Use exit signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
| `use_exit_signal` | Use exit signals produced by the strategy in addition to the `minimal_roi`. <br>Setting this to false disables the usage of `"exit_long"` and `"exit_short"` columns. Has no influence on other exit methods (Stoploss, ROI, callbacks). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||||
| `exit_profit_only` | Wait until the bot reaches `exit_profit_offset` before taking an exit decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `exit_profit_only` | Wait until the bot reaches `exit_profit_offset` before taking an exit decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
| `exit_profit_offset` | Exit-signal is only active above this value. Only active in combination with `exit_profit_only=True`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
|
| `exit_profit_offset` | Exit-signal is only active above this value. Only active in combination with `exit_profit_only=True`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
|
||||||
| `ignore_roi_if_entry_signal` | Do not exit if the entry signal is still active. This setting takes preference over `minimal_roi` and `use_exit_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
| `ignore_roi_if_entry_signal` | Do not exit if the entry signal is still active. This setting takes preference over `minimal_roi` and `use_exit_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||||
@@ -613,6 +613,7 @@ Once you will be happy with your bot performance running in the Dry-run mode, yo
|
|||||||
* Orders are simulated, and will not be posted to the exchange.
|
* Orders are simulated, and will not be posted to the exchange.
|
||||||
* Market orders fill based on orderbook volume the moment the order is placed.
|
* Market orders fill based on orderbook volume the moment the order is placed.
|
||||||
* Limit orders fill once the price reaches the defined level - or time out based on `unfilledtimeout` settings.
|
* Limit orders fill once the price reaches the defined level - or time out based on `unfilledtimeout` settings.
|
||||||
|
* Limit orders will be converted to market orders if they cross the price by more than 1%.
|
||||||
* In combination with `stoploss_on_exchange`, the stop_loss price is assumed to be filled.
|
* In combination with `stoploss_on_exchange`, the stop_loss price is assumed to be filled.
|
||||||
* Open orders (not trades, which are stored in the database) are kept open after bot restarts, with the assumption that they were not filled while being offline.
|
* Open orders (not trades, which are stored in the database) are kept open after bot restarts, with the assumption that they were not filled while being offline.
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ You can run this server using the following command: `docker compose -f docker/d
|
|||||||
This will create a dockercontainer running jupyter lab, which will be accessible using `https://127.0.0.1:8888/lab`.
|
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.
|
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.
|
For more information, Please visit the [Data analysis with Docker](docker_quickstart.md#data-analysis-using-docker-compose) section.
|
||||||
|
|
||||||
### Pro tips
|
### Pro tips
|
||||||
|
|
||||||
|
|||||||
@@ -154,13 +154,13 @@ freqtrade download-data --exchange binance --pairs ETH/USDT XRP/USDT BTC/USDT --
|
|||||||
|
|
||||||
Freqtrade currently supports the following data-formats:
|
Freqtrade currently supports the following data-formats:
|
||||||
|
|
||||||
|
* `feather` - a dataformat based on Apache Arrow
|
||||||
* `json` - plain "text" json files
|
* `json` - plain "text" json files
|
||||||
* `jsongz` - a gzip-zipped version of json files
|
* `jsongz` - a gzip-zipped version of json files
|
||||||
* `hdf5` - a high performance datastore
|
* `hdf5` - a high performance datastore
|
||||||
* `feather` - a dataformat based on Apache Arrow
|
|
||||||
* `parquet` - columnar datastore (OHLCV only)
|
* `parquet` - columnar datastore (OHLCV only)
|
||||||
|
|
||||||
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
By default, both OHLCV data and trades data are stored in the `feather` format.
|
||||||
|
|
||||||
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
|
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
|
||||||
To persist this change, you should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
To persist this change, you should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
|
||||||
@@ -203,15 +203,15 @@ time freqtrade list-data --show-timerange --data-format-ohlcv <dataformat>
|
|||||||
|
|
||||||
| Format | Size | timing |
|
| Format | Size | timing |
|
||||||
|------------|-------------|-------------|
|
|------------|-------------|-------------|
|
||||||
|
| `feather` | 72Mb | 3.5s |
|
||||||
| `json` | 149Mb | 25.6s |
|
| `json` | 149Mb | 25.6s |
|
||||||
| `jsongz` | 39Mb | 27s |
|
| `jsongz` | 39Mb | 27s |
|
||||||
| `hdf5` | 145Mb | 3.9s |
|
| `hdf5` | 145Mb | 3.9s |
|
||||||
| `feather` | 72Mb | 3.5s |
|
|
||||||
| `parquet` | 83Mb | 3.8s |
|
| `parquet` | 83Mb | 3.8s |
|
||||||
|
|
||||||
Size has been taken from the BTC/USDT 1m spot combination for the timerange specified above.
|
Size has been taken from the BTC/USDT 1m spot combination for the timerange specified above.
|
||||||
|
|
||||||
To have a best performance/size mix, we recommend the use of either feather or parquet.
|
To have a best performance/size mix, we recommend using the default feather format, or parquet.
|
||||||
|
|
||||||
### Pairs file
|
### Pairs file
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
The `Edge Positioning` module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss.
|
The `Edge Positioning` module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss.
|
||||||
|
|
||||||
|
!!! Danger "Deprecated functionality"
|
||||||
|
`Edge positioning` (or short Edge) is currently in maintenance mode only (we keep existing functionality alive) and should be considered as deprecated.
|
||||||
|
It will currently not receive new features until either someone stepped forward to take up ownership of that module - or we'll decide to remove edge from freqtrade.
|
||||||
|
|
||||||
!!! Warning
|
!!! Warning
|
||||||
When using `Edge positioning` with a dynamic whitelist (VolumePairList), make sure to also use `AgeFilter` and set it to at least `calculate_since_number_of_days` to avoid problems with missing data.
|
When using `Edge positioning` with a dynamic whitelist (VolumePairList), make sure to also use `AgeFilter` and set it to at least `calculate_since_number_of_days` to avoid problems with missing data.
|
||||||
|
|
||||||
|
|||||||
+1
-10
@@ -55,7 +55,7 @@ This configuration enables kraken, as well as rate-limiting to avoid bans from t
|
|||||||
## Binance
|
## Binance
|
||||||
|
|
||||||
!!! Warning "Server location and geo-ip restrictions"
|
!!! Warning "Server location and geo-ip restrictions"
|
||||||
Please be aware that binance restrict api access regarding the server country. The currents and non exhaustive countries blocked are United States, Malaysia (Singapour), Ontario (Canada). Please go to [binance terms > b. Eligibility](https://www.binance.com/en/terms) to find up to date list.
|
Please be aware that Binance restricts API access regarding the server country. The current and non-exhaustive countries blocked are Canada, Malaysia, Netherlands and United States. Please go to [binance terms > b. Eligibility](https://www.binance.com/en/terms) to find up to date list.
|
||||||
|
|
||||||
Binance supports [time_in_force](configuration.md#understand-order_time_in_force).
|
Binance supports [time_in_force](configuration.md#understand-order_time_in_force).
|
||||||
|
|
||||||
@@ -136,15 +136,6 @@ Freqtrade will not attempt to change these settings.
|
|||||||
The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting.
|
The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting.
|
||||||
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
To download data for the Kraken exchange, using `--dl-trades` is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
|
||||||
|
|
||||||
Due to the heavy rate-limiting applied by Kraken, the following configuration section should be used to download data:
|
|
||||||
|
|
||||||
``` json
|
|
||||||
"ccxt_async_config": {
|
|
||||||
"enableRateLimit": true,
|
|
||||||
"rateLimit": 3100
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
!!! Warning "Downloading data from kraken"
|
!!! Warning "Downloading data from kraken"
|
||||||
Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine.
|
Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine.
|
||||||
It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient.
|
It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient.
|
||||||
|
|||||||
@@ -178,7 +178,7 @@ You can ask for each of the defined features to be included also for informative
|
|||||||
|
|
||||||
`include_shifted_candles` indicates the number of previous candles to include in the feature set. For example, `include_shifted_candles: 2` tells FreqAI to include the past 2 candles for each of the features in the feature set.
|
`include_shifted_candles` indicates the number of previous candles to include in the feature set. For example, `include_shifted_candles: 2` tells FreqAI to include the past 2 candles for each of the features in the feature set.
|
||||||
|
|
||||||
In total, the number of features the user of the presented example strat has created is: length of `include_timeframes` * no. features in `feature_engineering_expand_*()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
In total, the number of features the user of the presented example strategy has created is: length of `include_timeframes` * no. features in `feature_engineering_expand_*()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
||||||
$= 3 * 3 * 3 * 2 * 2 = 108$.
|
$= 3 * 3 * 3 * 2 * 2 = 108$.
|
||||||
|
|
||||||
!!! note "Learn more about creative feature engineering"
|
!!! note "Learn more about creative feature engineering"
|
||||||
|
|||||||
@@ -237,11 +237,10 @@ class MyCoolRLModel(ReinforcementLearner):
|
|||||||
Reinforcement Learning models benefit from tracking training metrics. FreqAI has integrated Tensorboard to allow users to track training and evaluation performance across all coins and across all retrainings. Tensorboard is activated via the following command:
|
Reinforcement Learning models benefit from tracking training metrics. FreqAI has integrated Tensorboard to allow users to track training and evaluation performance across all coins and across all retrainings. Tensorboard is activated via the following command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd freqtrade
|
|
||||||
tensorboard --logdir user_data/models/unique-id
|
tensorboard --logdir user_data/models/unique-id
|
||||||
```
|
```
|
||||||
|
|
||||||
where `unique-id` is the `identifier` set in the `freqai` configuration file. This command must be run in a separate shell to view the output in their browser at 127.0.0.1:6006 (6006 is the default port used by Tensorboard).
|
where `unique-id` is the `identifier` set in the `freqai` configuration file. This command must be run in a separate shell to view the output in the browser at 127.0.0.1:6006 (6006 is the default port used by Tensorboard).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ You may also use something like `.*DOWN/BTC` or `.*UP/BTC` to exclude leveraged
|
|||||||
* [`ProducerPairList`](#producerpairlist)
|
* [`ProducerPairList`](#producerpairlist)
|
||||||
* [`RemotePairList`](#remotepairlist)
|
* [`RemotePairList`](#remotepairlist)
|
||||||
* [`AgeFilter`](#agefilter)
|
* [`AgeFilter`](#agefilter)
|
||||||
|
* [`FullTradesFilter`](#fulltradesfilter)
|
||||||
* [`OffsetFilter`](#offsetfilter)
|
* [`OffsetFilter`](#offsetfilter)
|
||||||
* [`PerformanceFilter`](#performancefilter)
|
* [`PerformanceFilter`](#performancefilter)
|
||||||
* [`PrecisionFilter`](#precisionfilter)
|
* [`PrecisionFilter`](#precisionfilter)
|
||||||
@@ -236,6 +237,17 @@ 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 and listed before `max_days_listed`.
|
This filter allows freqtrade to ignore pairs until they have been listed for at least `min_days_listed` days and listed before `max_days_listed`.
|
||||||
|
|
||||||
|
#### FullTradesFilter
|
||||||
|
|
||||||
|
Shrink whitelist to consist only in-trade pairs when the trade slots are full (when `max_open_trades` isn't being set to `-1` in the config).
|
||||||
|
|
||||||
|
When the trade slots are full, there is no need to calculate indicators of the rest of the pairs (except informative pairs) since no new trade can be opened. By shrinking the whitelist to just the in-trade pairs, you can improve calculation speeds and reduce CPU usage. When a trade slot is free (either a trade is closed or `max_open_trades` value in config is increased), then the whitelist will return to normal state.
|
||||||
|
|
||||||
|
When multiple pairlist filters are being used, it's recommended to put this filter at second position directly below the primary pairlist, so when the trade slots are full, the bot doesn't have to download data for the rest of the filters.
|
||||||
|
|
||||||
|
!!! Warning "Backtesting"
|
||||||
|
`FullTradesFilter` does not support backtesting mode.
|
||||||
|
|
||||||
#### OffsetFilter
|
#### OffsetFilter
|
||||||
|
|
||||||
Offsets an incoming pairlist by a given `offset` value.
|
Offsets an incoming pairlist by a given `offset` value.
|
||||||
@@ -376,7 +388,7 @@ If the trading range over the last 10 days is <1% or >99%, remove the pair from
|
|||||||
"lookback_days": 10,
|
"lookback_days": 10,
|
||||||
"min_rate_of_change": 0.01,
|
"min_rate_of_change": 0.01,
|
||||||
"max_rate_of_change": 0.99,
|
"max_rate_of_change": 0.99,
|
||||||
"refresh_period": 1440
|
"refresh_period": 86400
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
@@ -431,7 +443,7 @@ The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets,
|
|||||||
"method": "RangeStabilityFilter",
|
"method": "RangeStabilityFilter",
|
||||||
"lookback_days": 10,
|
"lookback_days": 10,
|
||||||
"min_rate_of_change": 0.01,
|
"min_rate_of_change": 0.01,
|
||||||
"refresh_period": 1440
|
"refresh_period": 86400
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"method": "VolatilityFilter",
|
"method": "VolatilityFilter",
|
||||||
|
|||||||
+1
-1
@@ -83,7 +83,7 @@ To run this bot we recommend you a linux cloud instance with a minimum of:
|
|||||||
|
|
||||||
Alternatively
|
Alternatively
|
||||||
|
|
||||||
- Python 3.8+
|
- Python 3.9+
|
||||||
- pip (pip3)
|
- pip (pip3)
|
||||||
- git
|
- git
|
||||||
- TA-Lib
|
- TA-Lib
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ The easiest way to install and run Freqtrade is to clone the bot Github reposito
|
|||||||
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).
|
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.8 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.9 or higher and the corresponding `pip` are assumed to be available. The install-script will warn you and stop if that's not the case. `git` is also needed to clone the Freqtrade repository.
|
||||||
Also, python headers (`python<yourversion>-dev` / `python<yourversion>-devel`) must be available for the installation to complete successfully.
|
Also, python headers (`python<yourversion>-dev` / `python<yourversion>-devel`) must be available for the installation to complete successfully.
|
||||||
|
|
||||||
!!! Warning "Up-to-date clock"
|
!!! Warning "Up-to-date clock"
|
||||||
@@ -42,7 +42,7 @@ These requirements apply to both [Script Installation](#script-installation) and
|
|||||||
|
|
||||||
### Install guide
|
### Install guide
|
||||||
|
|
||||||
* [Python >= 3.8.x](http://docs.python-guide.org/en/latest/starting/installation/)
|
* [Python >= 3.9](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)
|
||||||
@@ -54,7 +54,7 @@ We've included/collected install instructions for Ubuntu, MacOS, and Windows. Th
|
|||||||
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.8 or higher and the corresponding pip are assumed to be available.
|
Python3.9 or higher and the corresponding pip are assumed to be available.
|
||||||
|
|
||||||
=== "Debian/Ubuntu"
|
=== "Debian/Ubuntu"
|
||||||
#### Install necessary dependencies
|
#### Install necessary dependencies
|
||||||
@@ -169,7 +169,7 @@ You can as well update, configure and reset the codebase of your bot with `./scr
|
|||||||
** --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.8+ installed beforehand for this to work.
|
You will need to have git and python3.9+ installed beforehand for this to work.
|
||||||
|
|
||||||
* Mandatory software as: `ta-lib`
|
* Mandatory software as: `ta-lib`
|
||||||
* Setup your virtualenv under `.venv/`
|
* Setup your virtualenv under `.venv/`
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Recursive analysis
|
||||||
|
|
||||||
|
This page explains how to validate your strategy for inaccuracies due to recursive issues with certain indicators.
|
||||||
|
|
||||||
|
A recursive formula defines any term of a sequence relative to its preceding term(s). An example of a recursive formula is a<sub>n</sub> = a<sub>n-1</sub> + b.
|
||||||
|
|
||||||
|
Why does this matter for Freqtrade? In backtesting, the bot will get full data of the pairs according to the timerange specified. But in a dry/live run, the bot will be limited by the amount of data each exchanges gives.
|
||||||
|
|
||||||
|
For example, to calculate a very basic indicator called `steps`, the first row's value is always 0, while the following rows' values are equal to the value of the previous row plus 1. If I were to calculate it using the latest 1000 candles, then the `steps` value of the first row is 0, and the `steps` value at the last closed candle is 999.
|
||||||
|
|
||||||
|
What happens if the calculation is using only the latest 500 candles? Then instead of 999, the `steps` value at last closed candle is 499. The difference of the value means your backtest result can differ from your dry/live run result.
|
||||||
|
|
||||||
|
The `recursive-analysis` command requires historic data to be available. To learn how to get data for the pairs and exchange you're interested in,
|
||||||
|
head over to the [Data Downloading](data-download.md) section of the documentation.
|
||||||
|
|
||||||
|
This command is built upon preparing different lengths of data and calculates indicators based on them.
|
||||||
|
This does not backtest the strategy itself, but rather only calculates the indicators. After calculating the indicators of different startup candle values (`startup_candle_count`) are done, the values of last rows across all specified `startup_candle_count` are compared to see how much variance they show compared to the base calculation.
|
||||||
|
|
||||||
|
Command settings:
|
||||||
|
|
||||||
|
- Use the `-p` option to set your desired pair to analyze. Since we are only looking at indicator values, using more than one pair is redundant. Preferably use a pair with a relatively high price and at least moderate volatility, such as BTC or ETH, to avoid rounding issues that can make the results inaccurate. If no pair is set on the command, the pair used for this analysis is the first pair in the whitelist.
|
||||||
|
- It is recommended to set a long timerange (at least 5000 candles) so that the initial indicators' calculation that is going to be used as a benchmark has very small or no recursive issues itself. For example, for a 5m timeframe, a timerange of 5000 candles would be equal to 18 days.
|
||||||
|
- `--cache` is forced to "none" to avoid loading previous indicators calculation automatically.
|
||||||
|
|
||||||
|
In addition to the recursive formula check, this command also carries out a simple lookahead bias check on the indicator values only. For a full lookahead check, use [Lookahead-analysis](lookahead-analysis.md).
|
||||||
|
|
||||||
|
## Recursive-analysis command reference
|
||||||
|
|
||||||
|
```
|
||||||
|
usage: freqtrade recursive-analysis [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||||
|
[-d PATH] [--userdir PATH] [-s NAME]
|
||||||
|
[--strategy-path PATH]
|
||||||
|
[--recursive-strategy-search]
|
||||||
|
[--freqaimodel NAME]
|
||||||
|
[--freqaimodel-path PATH] [-i TIMEFRAME]
|
||||||
|
[--timerange TIMERANGE]
|
||||||
|
[--data-format-ohlcv {json,jsongz,hdf5,feather,parquet}]
|
||||||
|
[-p PAIR]
|
||||||
|
[--freqai-backtest-live-models]
|
||||||
|
[--startup-candle STARTUP_CANDLES [STARTUP_CANDLES ...]]
|
||||||
|
|
||||||
|
optional arguments:
|
||||||
|
-p PAIR, --pairs PAIR
|
||||||
|
Limit command to this pair.
|
||||||
|
--startup-candle STARTUP_CANDLE [STARTUP_CANDLE ...]
|
||||||
|
Provide a space-separated list of startup_candle_count to
|
||||||
|
be checked. Default : `199 399 499 999 1999`.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Why are odd-numbered default startup candles used?
|
||||||
|
|
||||||
|
The default value for startup candles are odd numbers. When the bot fetches candle data from the exchange's API, the last candle is the one being checked by the bot and the rest of the data are the "startup candles".
|
||||||
|
|
||||||
|
For example, Binance allows 1000 candles per API call. When the bot receives 1000 candles, the last candle is the "current candle", and the preceding 999 candles are the "startup candles". By setting the startup candle count as 1000 instead of 999, the bot will try to fetch 1001 candles instead. The exchange API will then send candle data in a paginated form, i.e. in case of the Binance API, this will be two groups- one of length 1000 and another of length 1. This results in the bot thinking the strategy needs 1001 candles of data, and so it will download 2000 candles worth of data instead, which means there will be 1 "current candle" and 1999 "startup candles".
|
||||||
|
|
||||||
|
Furthermore, exchanges limit the number of consecutive bulk API calls, e.g. Binance allows 5 calls. In this case, only 5000 candles can be downloaded from Binance API without hitting the API rate limit, which means the max `startup_candle_count` you can have is 4999.
|
||||||
|
|
||||||
|
Please note that this candle limit may be changed in the future by the exchanges without any prior notice.
|
||||||
|
|
||||||
|
### How does the command work?
|
||||||
|
|
||||||
|
- Firstly an initial indicator calculation is carried out using the supplied timerange to generate a benchmark for indicator values.
|
||||||
|
- After setting the benchmark it will then carry out additional runs for each of the different startup candle count values.
|
||||||
|
- The command will then compare the indicator values at the last candle rows and report the differences in a table.
|
||||||
|
|
||||||
|
## Understanding the recursive-analysis output
|
||||||
|
|
||||||
|
This is an example of an output results table where at least one indicator has a recursive formula issue:
|
||||||
|
|
||||||
|
```
|
||||||
|
| indicators | 20 | 40 | 80 | 100 | 150 | 300 | 999 |
|
||||||
|
|--------------+---------+---------+--------+--------+---------+---------+--------|
|
||||||
|
| rsi_30 | nan% | -6.025% | 0.612% | 0.828% | -0.140% | 0.000% | 0.000% |
|
||||||
|
| rsi_14 | 24.141% | -0.876% | 0.070% | 0.007% | -0.000% | -0.000% | - |
|
||||||
|
```
|
||||||
|
|
||||||
|
The column headers indicate the different `startup_candle_count` used in the analysis. The values in the table indicate the variance of the calculated indicators compared to the benchmark value.
|
||||||
|
|
||||||
|
`nan%` means the value of that indicator cannot be calculated due to lack of data. In this example, you cannot calculate RSI with length 30 with just 21 candles (1 current candle + 20 startup candles).
|
||||||
|
|
||||||
|
Users should assess the table per indicator to decide if the specified `startup_candle_count` results in a sufficiently small variance so that the indicator does not have any effect on entries and/or exits.
|
||||||
|
|
||||||
|
As such, aiming for absolute zero variance (shown by `-` value) might not be the best option, because some indicators might require you to use such a long `startup_candle_count` to have zero variance.
|
||||||
|
|
||||||
|
## Caveats
|
||||||
|
|
||||||
|
- `recursive-analysis` will only calculate and compare the indicator values at the last row. The output table reports the percentage differences between the different startup candle count calculations and the original benchmark calculation. Whether it has any actual impact on your entries and exits is not included.
|
||||||
|
- The ideal scenario is that indicators will have no variance (or at least very close to 0%) despite the startup candle being varied. In reality, indicators such as EMA are using a recursive formula to calculate indicator values, so the goal is not necessarily to have zero percentage variance, but to have the variance low enough (and therefore `startup_candle_count` high enough) that the recursion inherent in the indicator will not have any real impact on trading decisions.
|
||||||
|
- `recursive-analysis` will only run calculations on `populate_indicators` and `@informative` decorator(s). If you put any indicator calculation on `populate_entry_trend` or `populate_exit_trend`, it won't be calculated.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
markdown==3.4.4
|
markdown==3.4.4
|
||||||
mkdocs==1.5.2
|
mkdocs==1.5.3
|
||||||
mkdocs-material==9.2.1
|
mkdocs-material==9.4.1
|
||||||
mdx_truly_sane_lists==1.3
|
mdx_truly_sane_lists==1.3
|
||||||
pymdown-extensions==10.1
|
pymdown-extensions==10.3
|
||||||
jinja2==3.1.2
|
jinja2==3.1.2
|
||||||
|
|||||||
@@ -151,6 +151,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
|
|||||||
| `performance` | Show performance of each finished trade grouped by pair.
|
| `performance` | Show performance of each finished trade grouped by pair.
|
||||||
| `balance` | Show account balance per currency.
|
| `balance` | Show account balance per currency.
|
||||||
| `daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7).
|
| `daily <n>` | Shows profit or loss per day, over the last n days (n defaults to 7).
|
||||||
|
| `weekly <n>` | Shows profit or loss per week, over the last n days (n defaults to 4).
|
||||||
|
| `monthly <n>` | Shows profit or loss per month, over the last n days (n defaults to 3).
|
||||||
| `stats` | Display a summary of profit / loss reasons as well as average holding times.
|
| `stats` | Display a summary of profit / loss reasons as well as average holding times.
|
||||||
| `whitelist` | Show the current whitelist.
|
| `whitelist` | Show the current whitelist.
|
||||||
| `blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
| `blacklist [pair]` | Show the current blacklist, or adds a pair to the blacklist.
|
||||||
|
|||||||
+160
-31
@@ -164,6 +164,31 @@ E.g. If the `current_rate` is 200 USD, then returning `0.02` will set the stoplo
|
|||||||
During backtesting, `current_rate` (and `current_profit`) are provided against the candle's high (or low for short trades) - while the resulting stoploss is evaluated against the candle's low (or high for short trades).
|
During backtesting, `current_rate` (and `current_profit`) are provided against the candle's high (or low for short trades) - while the resulting stoploss is evaluated against the candle's low (or high for short trades).
|
||||||
|
|
||||||
The absolute value of the return value is used (the sign is ignored), so returning `0.05` or `-0.05` have the same result, a stoploss 5% below the current price.
|
The absolute value of the return value is used (the sign is ignored), so returning `0.05` or `-0.05` have the same result, a stoploss 5% below the current price.
|
||||||
|
Returning None will be interpreted as "no desire to change", and is the only safe way to return when you'd like to not modify the stoploss.
|
||||||
|
|
||||||
|
Stoploss on exchange works similar to `trailing_stop`, and the stoploss on exchange is updated as configured in `stoploss_on_exchange_interval` ([More details about stoploss on exchange](stoploss.md#stop-loss-on-exchange-freqtrade)).
|
||||||
|
|
||||||
|
!!! Note "Use of dates"
|
||||||
|
All time-based calculations should be done based on `current_time` - using `datetime.now()` or `datetime.utcnow()` is discouraged, as this will break backtesting support.
|
||||||
|
|
||||||
|
!!! Tip "Trailing stoploss"
|
||||||
|
It's recommended to disable `trailing_stop` when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.
|
||||||
|
|
||||||
|
### Adjust stoploss after position adjustments
|
||||||
|
|
||||||
|
Depending on your strategy, you may encounter the need to adjust the stoploss in both directions after a [position adjustment](#adjust-trade-position).
|
||||||
|
For this, freqtrade will make an additional call with `after_fill=True` after an order fills, which will allow the strategy to move the stoploss in any direction (also widening the gap between stoploss and current price, which is otherwise forbidden).
|
||||||
|
|
||||||
|
!!! Note "backwards compatibility"
|
||||||
|
This call will only be made if the `after_fill` parameter is part of the function definition of your `custom_stoploss` function.
|
||||||
|
As such, this will not impact (and with that, surprise) existing, running strategies.
|
||||||
|
|
||||||
|
### Custom stoploss examples
|
||||||
|
|
||||||
|
The next section will show some examples on what's possible with the custom stoploss function.
|
||||||
|
Of course, many more things are possible, and all examples can be combined at will.
|
||||||
|
|
||||||
|
#### Trailing stop via custom stoploss
|
||||||
|
|
||||||
To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:
|
To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:
|
||||||
|
|
||||||
@@ -179,7 +204,8 @@ class AwesomeStrategy(IStrategy):
|
|||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
"""
|
"""
|
||||||
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
||||||
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
||||||
@@ -187,7 +213,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
|
|
||||||
When not implemented by a strategy, returns the initial stoploss value
|
When not implemented by a strategy, returns the initial stoploss value.
|
||||||
Only called when use_custom_stoploss is set to True.
|
Only called when use_custom_stoploss is set to True.
|
||||||
|
|
||||||
:param pair: Pair that's currently analyzed
|
:param pair: Pair that's currently analyzed
|
||||||
@@ -195,25 +221,13 @@ class AwesomeStrategy(IStrategy):
|
|||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
||||||
|
:param after_fill: True if the stoploss is called after the order was filled.
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return float: New stoploss value, relative to the current rate
|
:return float: New stoploss value, relative to the current_rate
|
||||||
"""
|
"""
|
||||||
return -0.04
|
return -0.04
|
||||||
```
|
```
|
||||||
|
|
||||||
Stoploss on exchange works similar to `trailing_stop`, and the stoploss on exchange is updated as configured in `stoploss_on_exchange_interval` ([More details about stoploss on exchange](stoploss.md#stop-loss-on-exchange-freqtrade)).
|
|
||||||
|
|
||||||
!!! Note "Use of dates"
|
|
||||||
All time-based calculations should be done based on `current_time` - using `datetime.now()` or `datetime.utcnow()` is discouraged, as this will break backtesting support.
|
|
||||||
|
|
||||||
!!! Tip "Trailing stoploss"
|
|
||||||
It's recommended to disable `trailing_stop` when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.
|
|
||||||
|
|
||||||
### Custom stoploss examples
|
|
||||||
|
|
||||||
The next section will show some examples on what's possible with the custom stoploss function.
|
|
||||||
Of course, many more things are possible, and all examples can be combined at will.
|
|
||||||
|
|
||||||
#### Time based trailing stop
|
#### Time based trailing stop
|
||||||
|
|
||||||
Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.
|
Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.
|
||||||
@@ -229,14 +243,45 @@ class AwesomeStrategy(IStrategy):
|
|||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
|
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
|
||||||
if current_time - timedelta(minutes=120) > trade.open_date_utc:
|
if current_time - timedelta(minutes=120) > trade.open_date_utc:
|
||||||
return -0.05
|
return -0.05
|
||||||
elif current_time - timedelta(minutes=60) > trade.open_date_utc:
|
elif current_time - timedelta(minutes=60) > trade.open_date_utc:
|
||||||
return -0.10
|
return -0.10
|
||||||
return 1
|
return None
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Time based trailing stop with after-fill adjustments
|
||||||
|
|
||||||
|
Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.
|
||||||
|
If an additional order fills, set stoploss to -10% below the new `open_rate` ([Averaged across all entries](#position-adjust-calculations)).
|
||||||
|
|
||||||
|
``` python
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
|
# ... populate_* methods
|
||||||
|
|
||||||
|
use_custom_stoploss = True
|
||||||
|
|
||||||
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
|
if after_fill:
|
||||||
|
# After an additional order, start with a stoploss of 10% below the new open rate
|
||||||
|
return stoploss_from_open(0.10, current_profit, is_short=trade.is_short, leverage=trade.leverage)
|
||||||
|
# Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
|
||||||
|
if current_time - timedelta(minutes=120) > trade.open_date_utc:
|
||||||
|
return -0.05
|
||||||
|
elif current_time - timedelta(minutes=60) > trade.open_date_utc:
|
||||||
|
return -0.10
|
||||||
|
return None
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Different stoploss per pair
|
#### Different stoploss per pair
|
||||||
@@ -255,7 +300,8 @@ class AwesomeStrategy(IStrategy):
|
|||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
if pair in ('ETH/BTC', 'XRP/BTC'):
|
if pair in ('ETH/BTC', 'XRP/BTC'):
|
||||||
return -0.10
|
return -0.10
|
||||||
@@ -281,7 +327,8 @@ class AwesomeStrategy(IStrategy):
|
|||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
if current_profit < 0.04:
|
if current_profit < 0.04:
|
||||||
return -1 # return a value bigger than the initial stoploss to keep using the initial stoploss
|
return -1 # return a value bigger than the initial stoploss to keep using the initial stoploss
|
||||||
@@ -314,7 +361,8 @@ class AwesomeStrategy(IStrategy):
|
|||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
# evaluate highest to lowest, so that highest possible stop is used
|
# evaluate highest to lowest, so that highest possible stop is used
|
||||||
if current_profit > 0.40:
|
if current_profit > 0.40:
|
||||||
@@ -325,7 +373,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage)
|
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage)
|
||||||
|
|
||||||
# return maximum stoploss value, keeping current stoploss price unchanged
|
# return maximum stoploss value, keeping current stoploss price unchanged
|
||||||
return 1
|
return None
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Custom stoploss using an indicator from dataframe example
|
#### Custom stoploss using an indicator from dataframe example
|
||||||
@@ -342,7 +390,8 @@ class AwesomeStrategy(IStrategy):
|
|||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
last_candle = dataframe.iloc[-1].squeeze()
|
last_candle = dataframe.iloc[-1].squeeze()
|
||||||
@@ -355,7 +404,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
return stoploss_from_absolute(stoploss_price, current_rate, is_short=trade.is_short)
|
return stoploss_from_absolute(stoploss_price, current_rate, is_short=trade.is_short)
|
||||||
|
|
||||||
# return maximum stoploss value, keeping current stoploss price unchanged
|
# return maximum stoploss value, keeping current stoploss price unchanged
|
||||||
return 1
|
return None
|
||||||
```
|
```
|
||||||
|
|
||||||
See [Dataframe access](strategy-advanced.md#dataframe-access) for more information about dataframe use in strategy callbacks.
|
See [Dataframe access](strategy-advanced.md#dataframe-access) for more information about dataframe use in strategy callbacks.
|
||||||
@@ -364,15 +413,89 @@ See [Dataframe access](strategy-advanced.md#dataframe-access) for more informati
|
|||||||
|
|
||||||
#### Stoploss relative to open price
|
#### Stoploss relative to open price
|
||||||
|
|
||||||
Stoploss values returned from `custom_stoploss()` always specify a percentage relative to `current_rate`. In order to set a stoploss relative to the *open* price, we need to use `current_profit` to calculate what percentage relative to the `current_rate` will give you the same result as if the percentage was specified from the open price.
|
Stoploss values returned from `custom_stoploss()` must specify a percentage relative to `current_rate`, but sometimes you may want to specify a stoploss relative to the _entry_ price instead.
|
||||||
|
`stoploss_from_open()` is a helper function to calculate a stoploss value that can be returned from `custom_stoploss` which will be equivalent to the desired trade profit above the entry point.
|
||||||
|
|
||||||
The helper function [`stoploss_from_open()`](strategy-customization.md#stoploss_from_open) can be used to convert from an open price relative stop, to a current price relative stop which can be returned from `custom_stoploss()`.
|
??? Example "Returning a stoploss relative to the open price from the custom stoploss function"
|
||||||
|
|
||||||
|
Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21`).
|
||||||
|
|
||||||
|
If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit, False)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100.
|
||||||
|
|
||||||
|
This function will consider leverage - so at 10x leverage, the actual stoploss would be 0.7% above $100 (0.7% * 10x = 7%).
|
||||||
|
|
||||||
|
|
||||||
|
``` python
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
from freqtrade.strategy import IStrategy, stoploss_from_open
|
||||||
|
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
|
# ... populate_* methods
|
||||||
|
|
||||||
|
use_custom_stoploss = True
|
||||||
|
|
||||||
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
|
||||||
|
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
||||||
|
if current_profit > 0.10:
|
||||||
|
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage)
|
||||||
|
|
||||||
|
return 1
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Full examples can be found in the [Custom stoploss](strategy-advanced.md#custom-stoploss) section of the Documentation.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Providing invalid input to `stoploss_from_open()` may produce "CustomStoploss function did not return valid stoploss" warnings.
|
||||||
|
This may happen if `current_profit` parameter is below specified `open_relative_stop`. Such situations may arise when closing trade
|
||||||
|
is blocked by `confirm_trade_exit()` method. Warnings can be solved by never blocking stop loss sells by checking `exit_reason` in
|
||||||
|
`confirm_trade_exit()`, or by using `return stoploss_from_open(...) or 1` idiom, which will request to not change stop loss when
|
||||||
|
`current_profit < open_relative_stop`.
|
||||||
|
|
||||||
#### Stoploss percentage from absolute price
|
#### Stoploss percentage from absolute price
|
||||||
|
|
||||||
Stoploss values returned from `custom_stoploss()` always specify a percentage relative to `current_rate`. In order to set a stoploss at specified absolute price level, we need to use `stop_rate` to calculate what percentage relative to the `current_rate` will give you the same result as if the percentage was specified from the open price.
|
Stoploss values returned from `custom_stoploss()` always specify a percentage relative to `current_rate`. In order to set a stoploss at specified absolute price level, we need to use `stop_rate` to calculate what percentage relative to the `current_rate` will give you the same result as if the percentage was specified from the open price.
|
||||||
|
|
||||||
The helper function [`stoploss_from_absolute()`](strategy-customization.md#stoploss_from_absolute) can be used to convert from an absolute price, to a current price relative stop which can be returned from `custom_stoploss()`.
|
The helper function `stoploss_from_absolute()` can be used to convert from an absolute price, to a current price relative stop which can be returned from `custom_stoploss()`.
|
||||||
|
|
||||||
|
??? Example "Returning a stoploss using absolute price from the custom stoploss function"
|
||||||
|
|
||||||
|
If we want to trail a stop price at 2xATR below current price we can call `stoploss_from_absolute(current_rate + (side * candle['atr'] * 2), current_rate, is_short=trade.is_short, leverage=trade.leverage)`.
|
||||||
|
For futures, we need to adjust the direction (up or down), as well as adjust for leverage, since the [`custom_stoploss`](strategy-callbacks.md#custom-stoploss) callback returns the ["risk for this trade"](stoploss.md#stoploss-and-leverage) - not the relative price movement.
|
||||||
|
|
||||||
|
``` python
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
from freqtrade.strategy import IStrategy, stoploss_from_absolute, timeframe_to_prev_date
|
||||||
|
|
||||||
|
class AwesomeStrategy(IStrategy):
|
||||||
|
|
||||||
|
use_custom_stoploss = True
|
||||||
|
|
||||||
|
def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
|
||||||
|
return dataframe
|
||||||
|
|
||||||
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||||
|
trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
|
||||||
|
candle = dataframe.iloc[-1].squeeze()
|
||||||
|
sign = 1 if trade.is_short else -1
|
||||||
|
return stoploss_from_absolute(current_rate + (side * candle['atr'] * 2),
|
||||||
|
current_rate, is_short=trade.is_short,
|
||||||
|
leverage=trade.leverage)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -387,6 +510,9 @@ Each of these methods are called right before placing an order on the exchange.
|
|||||||
!!! Note
|
!!! Note
|
||||||
If your custom pricing function return None or an invalid value, price will fall back to `proposed_rate`, which is based on the regular pricing configuration.
|
If your custom pricing function return None or an invalid value, price will fall back to `proposed_rate`, which is based on the regular pricing configuration.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Using custom_entry_price, the Trade object will be available as soon as the first entry order associated with the trade is created, for the first entry, `trade` parameter value will be `None`.
|
||||||
|
|
||||||
### Custom order entry and exit price example
|
### Custom order entry and exit price example
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
@@ -397,7 +523,7 @@ class AwesomeStrategy(IStrategy):
|
|||||||
|
|
||||||
# ... populate_* methods
|
# ... populate_* methods
|
||||||
|
|
||||||
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
def custom_entry_price(self, pair: str, trade: Optional['Trade'], current_time: datetime, proposed_rate: float,
|
||||||
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
|
|
||||||
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
|
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair,
|
||||||
@@ -700,7 +826,7 @@ class DigDeeperStrategy(IStrategy):
|
|||||||
"""
|
"""
|
||||||
Custom trade adjustment logic, returning the stake amount that a trade should be
|
Custom trade adjustment logic, returning the stake amount that a trade should be
|
||||||
increased or decreased.
|
increased or decreased.
|
||||||
This means extra buy or sell orders with additional fees.
|
This means extra entry or exit orders with additional fees.
|
||||||
Only called when `position_adjustment_enable` is set to True.
|
Only called when `position_adjustment_enable` is set to True.
|
||||||
|
|
||||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
@@ -709,8 +835,9 @@ class DigDeeperStrategy(IStrategy):
|
|||||||
|
|
||||||
:param trade: trade object.
|
:param trade: trade object.
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Current buy rate.
|
:param current_rate: Current entry rate (same as current_entry_profit)
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate
|
||||||
|
(same as current_entry_profit).
|
||||||
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
||||||
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
||||||
:param current_entry_rate: Current rate using entry pricing.
|
:param current_entry_rate: Current rate using entry pricing.
|
||||||
@@ -793,6 +920,8 @@ Returning any other price will cancel the existing order, and replace it with a
|
|||||||
The trade open-date (`trade.open_date_utc`) will remain at the time of the very first order placed.
|
The trade open-date (`trade.open_date_utc`) will remain at the time of the very first order placed.
|
||||||
Please make sure to be aware of this - and eventually adjust your logic in other callbacks to account for this, and use the date of the first filled order instead.
|
Please make sure to be aware of this - and eventually adjust your logic in other callbacks to account for this, and use the date of the first filled order instead.
|
||||||
|
|
||||||
|
If the cancellation of the original order fails, then the order will not be replaced - though the order will most likely have been canceled on exchange. Having this happen on initial entries will result in the deletion of the order, while on position adjustment orders, it'll result in the trade size remaining as is.
|
||||||
|
|
||||||
!!! Warning "Regular timeout"
|
!!! Warning "Regular timeout"
|
||||||
Entry `unfilledtimeout` mechanism (as well as `check_entry_timeout()`) takes precedence over this.
|
Entry `unfilledtimeout` mechanism (as well as `check_entry_timeout()`) takes precedence over this.
|
||||||
Entry Orders that are cancelled via the above methods will not have this callback called. Be sure to update timeout values to match your expectations.
|
Entry Orders that are cancelled via the above methods will not have this callback called. Be sure to update timeout values to match your expectations.
|
||||||
|
|||||||
+68
-145
@@ -168,10 +168,12 @@ Most indicators have an instable startup period, in which they are either not av
|
|||||||
To account for this, the strategy can be assigned the `startup_candle_count` attribute.
|
To account for this, the strategy can be assigned the `startup_candle_count` attribute.
|
||||||
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In the case where a user includes higher timeframes with informative pairs, the `startup_candle_count` does not necessarily change. The value is the maximum period (in candles) that any of the informatives timeframes need to compute stable indicators.
|
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In the case where a user includes higher timeframes with informative pairs, the `startup_candle_count` does not necessarily change. The value is the maximum period (in candles) that any of the informatives timeframes need to compute stable indicators.
|
||||||
|
|
||||||
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.
|
You can use [recursive-analysis](recursive-analysis.md) to check and find the correct `startup_candle_count` to be used.
|
||||||
|
|
||||||
|
In this example strategy, this should be set to 400 (`startup_candle_count = 400`), since the minimum needed history for ema100 calculation to make sure the value is correct is 400 candles.
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
|
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=400)
|
||||||
```
|
```
|
||||||
|
|
||||||
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
|
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
|
||||||
@@ -193,11 +195,11 @@ Let's try to backtest 1 month (January 2019) of 5m candles using an example stra
|
|||||||
freqtrade backtesting --timerange 20190101-20190201 --timeframe 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 ~2018-12-31 15:30:00.
|
Assuming `startup_candle_count` is set to 400, backtesting knows it needs 400 candles to generate valid buy signals. It will load data from `20190101 - (400 * 5m)` - which is ~2018-12-30 11:40: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
|
||||||
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
|
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-02 09:20:00.
|
||||||
|
|
||||||
### Entry signal rules
|
### Entry signal rules
|
||||||
|
|
||||||
@@ -264,7 +266,7 @@ def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFram
|
|||||||
### Exit signal rules
|
### Exit signal rules
|
||||||
|
|
||||||
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
|
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
|
||||||
The exit-signal is only used for exits if `use_exit_signal` is set to true in the configuration.
|
The exit-signal can be suppressed by setting `use_exit_signal` to false in the configuration or strategy.
|
||||||
`use_exit_signal` will not influence [signal collision rules](#colliding-signals) - which will still apply and can prevent entries.
|
`use_exit_signal` will not influence [signal collision rules](#colliding-signals) - which will still apply and can prevent entries.
|
||||||
|
|
||||||
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
|
||||||
@@ -586,6 +588,67 @@ for more information.
|
|||||||
will overwrite previously defined method and not produce any errors due to limitations of Python programming language. In such cases you will find that indicators
|
will overwrite previously defined method and not produce any errors due to limitations of Python programming language. In such cases you will find that indicators
|
||||||
created in earlier-defined methods are not available in the dataframe. Carefully review method names and make sure they are unique!
|
created in earlier-defined methods are not available in the dataframe. Carefully review method names and make sure they are unique!
|
||||||
|
|
||||||
|
### *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)
|
||||||
|
|
||||||
|
For a full sample, please refer to the [complete data provider example](#complete-data-provider-sample) below.
|
||||||
|
|
||||||
|
All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
|
||||||
|
|
||||||
|
!!! 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 (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.
|
||||||
@@ -810,146 +873,6 @@ class SampleStrategy(IStrategy):
|
|||||||
|
|
||||||
***
|
***
|
||||||
|
|
||||||
## 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)
|
|
||||||
|
|
||||||
For a full sample, please refer to the [complete data provider example](#complete-data-provider-sample) below.
|
|
||||||
|
|
||||||
All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:
|
|
||||||
|
|
||||||
!!! 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).
|
|
||||||
|
|
||||||
***
|
|
||||||
|
|
||||||
### *stoploss_from_open()*
|
|
||||||
|
|
||||||
Stoploss values returned from `custom_stoploss` must specify a percentage relative to `current_rate`, but sometimes you may want to specify a stoploss relative to the entry point instead. `stoploss_from_open()` is a helper function to calculate a stoploss value that can be returned from `custom_stoploss` which will be equivalent to the desired trade profit above the entry point.
|
|
||||||
|
|
||||||
??? Example "Returning a stoploss relative to the open price from the custom stoploss function"
|
|
||||||
|
|
||||||
Say the open price was $100, and `current_price` is $121 (`current_profit` will be `0.21`).
|
|
||||||
|
|
||||||
If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit, False)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100.
|
|
||||||
|
|
||||||
This function will consider leverage - so at 10x leverage, the actual stoploss would be 0.7% above $100 (0.7% * 10x = 7%).
|
|
||||||
|
|
||||||
|
|
||||||
``` python
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from freqtrade.persistence import Trade
|
|
||||||
from freqtrade.strategy import IStrategy, stoploss_from_open
|
|
||||||
|
|
||||||
class AwesomeStrategy(IStrategy):
|
|
||||||
|
|
||||||
# ... populate_* methods
|
|
||||||
|
|
||||||
use_custom_stoploss = True
|
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
|
||||||
|
|
||||||
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
|
||||||
if current_profit > 0.10:
|
|
||||||
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage)
|
|
||||||
|
|
||||||
return 1
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
Full examples can be found in the [Custom stoploss](strategy-advanced.md#custom-stoploss) section of the Documentation.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Providing invalid input to `stoploss_from_open()` may produce "CustomStoploss function did not return valid stoploss" warnings.
|
|
||||||
This may happen if `current_profit` parameter is below specified `open_relative_stop`. Such situations may arise when closing trade
|
|
||||||
is blocked by `confirm_trade_exit()` method. Warnings can be solved by never blocking stop loss sells by checking `exit_reason` in
|
|
||||||
`confirm_trade_exit()`, or by using `return stoploss_from_open(...) or 1` idiom, which will request to not change stop loss when
|
|
||||||
`current_profit < open_relative_stop`.
|
|
||||||
|
|
||||||
### *stoploss_from_absolute()*
|
|
||||||
|
|
||||||
In some situations it may be confusing to deal with stops relative to current rate. Instead, you may define a stoploss level using an absolute price.
|
|
||||||
|
|
||||||
??? Example "Returning a stoploss using absolute price from the custom stoploss function"
|
|
||||||
|
|
||||||
If we want to trail a stop price at 2xATR below current price we can call `stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short)`.
|
|
||||||
|
|
||||||
``` python
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from freqtrade.persistence import Trade
|
|
||||||
from freqtrade.strategy import IStrategy, stoploss_from_absolute
|
|
||||||
|
|
||||||
class AwesomeStrategy(IStrategy):
|
|
||||||
|
|
||||||
use_custom_stoploss = True
|
|
||||||
|
|
||||||
def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
|
|
||||||
return dataframe
|
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
|
||||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
|
||||||
candle = dataframe.iloc[-1].squeeze()
|
|
||||||
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short)
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## Additional data (Wallets)
|
## Additional data (Wallets)
|
||||||
|
|
||||||
The strategy provides access to the `wallets` object. This contains the current balances on the exchange.
|
The strategy provides access to the `wallets` object. This contains the current balances on the exchange.
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ trades.groupby("pair")["exit_reason"].value_counts()
|
|||||||
# Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day)
|
# Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day)
|
||||||
|
|
||||||
from freqtrade.configuration import Configuration
|
from freqtrade.configuration import Configuration
|
||||||
from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats
|
from freqtrade.data.btanalysis import load_backtest_stats
|
||||||
import plotly.express as px
|
import plotly.express as px
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
@@ -178,20 +178,8 @@ import pandas as pd
|
|||||||
stats = load_backtest_stats(backtest_dir)
|
stats = load_backtest_stats(backtest_dir)
|
||||||
strategy_stats = stats['strategy'][strategy]
|
strategy_stats = stats['strategy'][strategy]
|
||||||
|
|
||||||
dates = []
|
df = pd.DataFrame(columns=['dates','equity'], data=strategy_stats['daily_profit'])
|
||||||
profits = []
|
df['equity_daily'] = df['equity'].cumsum()
|
||||||
for date_profit in strategy_stats['daily_profit']:
|
|
||||||
dates.append(date_profit[0])
|
|
||||||
profits.append(date_profit[1])
|
|
||||||
|
|
||||||
equity = 0
|
|
||||||
equity_daily = []
|
|
||||||
for daily_profit in profits:
|
|
||||||
equity_daily.append(equity)
|
|
||||||
equity += float(daily_profit)
|
|
||||||
|
|
||||||
|
|
||||||
df = pd.DataFrame({'dates': dates,'equity_daily': equity_daily})
|
|
||||||
|
|
||||||
fig = px.line(df, x="dates", y="equity_daily")
|
fig = px.line(df, x="dates", y="equity_daily")
|
||||||
fig.show()
|
fig.show()
|
||||||
|
|||||||
@@ -280,7 +280,7 @@ After:
|
|||||||
|
|
||||||
``` python hl_lines="3"
|
``` python hl_lines="3"
|
||||||
class AwesomeStrategy(IStrategy):
|
class AwesomeStrategy(IStrategy):
|
||||||
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
def custom_entry_price(self, pair: str, trade: Optional[Trade], current_time: datetime, proposed_rate: float,
|
||||||
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
return proposed_rate
|
return proposed_rate
|
||||||
```
|
```
|
||||||
@@ -311,12 +311,13 @@ After:
|
|||||||
|
|
||||||
``` python hl_lines="5 7"
|
``` python hl_lines="5 7"
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_rate: float, current_profit: float, after_fill: bool,
|
||||||
|
**kwargs) -> Optional[float]:
|
||||||
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
# once the profit has risen above 10%, keep the stoploss at 7% above the open price
|
||||||
if current_profit > 0.10:
|
if current_profit > 0.10:
|
||||||
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short)
|
return stoploss_from_open(0.07, current_profit, is_short=trade.is_short)
|
||||||
|
|
||||||
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short)
|
return stoploss_from_absolute(current_rate - (candle['atr'] * 2), current_rate, is_short=trade.is_short, leverage=trade.leverage)
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ git clone https://github.com/freqtrade/freqtrade.git
|
|||||||
|
|
||||||
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7/ta-lib#windows).
|
||||||
|
|
||||||
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), Freqtrade provides these dependencies (in the binary wheel format) for the latest 3 Python versions (3.8, 3.9, 3.10 and 3.11) and for 64bit Windows.
|
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), Freqtrade provides these dependencies (in the binary wheel format) for the latest 3 Python versions (3.9, 3.10 and 3.11) and for 64bit Windows.
|
||||||
These Wheels are also used by CI running on windows, and are therefore tested together with freqtrade.
|
These Wheels are also used by CI running on windows, and are therefore tested together with freqtrade.
|
||||||
|
|
||||||
Other versions must be downloaded from the above link.
|
Other versions must be downloaded from the above link.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
""" Freqtrade bot """
|
""" Freqtrade bot """
|
||||||
__version__ = '2023.8'
|
__version__ = '2023.9'
|
||||||
|
|
||||||
if 'dev' in __version__:
|
if 'dev' in __version__:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
__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.8)
|
> python -m freqtrade (with Python >= 3.9)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from freqtrade import main
|
from freqtrade import main
|
||||||
|
|||||||
@@ -20,7 +20,8 @@ from freqtrade.commands.list_commands import (start_list_exchanges, start_list_f
|
|||||||
start_list_timeframes, start_show_trades)
|
start_list_timeframes, start_show_trades)
|
||||||
from freqtrade.commands.optimize_commands import (start_backtesting, start_backtesting_show,
|
from freqtrade.commands.optimize_commands import (start_backtesting, start_backtesting_show,
|
||||||
start_edge, start_hyperopt,
|
start_edge, start_hyperopt,
|
||||||
start_lookahead_analysis)
|
start_lookahead_analysis,
|
||||||
|
start_recursive_analysis)
|
||||||
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, start_plot_profit
|
from freqtrade.commands.plot_commands import start_plot_dataframe, start_plot_profit
|
||||||
from freqtrade.commands.strategy_utils_commands import start_strategy_update
|
from freqtrade.commands.strategy_utils_commands import start_strategy_update
|
||||||
|
|||||||
@@ -122,6 +122,8 @@ ARGS_LOOKAHEAD_ANALYSIS = [
|
|||||||
a for a in ARGS_BACKTEST if a not in ("position_stacking", "use_max_market_positions", 'cache')
|
a for a in ARGS_BACKTEST if a not in ("position_stacking", "use_max_market_positions", 'cache')
|
||||||
] + ["minimum_trade_amount", "targeted_trade_amount", "lookahead_analysis_exportfilename"]
|
] + ["minimum_trade_amount", "targeted_trade_amount", "lookahead_analysis_exportfilename"]
|
||||||
|
|
||||||
|
ARGS_RECURSIVE_ANALYSIS = ["timeframe", "timerange", "dataformat_ohlcv", "pairs", "startup_candle"]
|
||||||
|
|
||||||
|
|
||||||
class Arguments:
|
class Arguments:
|
||||||
"""
|
"""
|
||||||
@@ -206,8 +208,9 @@ class Arguments:
|
|||||||
start_list_strategies, start_list_timeframes,
|
start_list_strategies, start_list_timeframes,
|
||||||
start_lookahead_analysis, start_new_config,
|
start_lookahead_analysis, start_new_config,
|
||||||
start_new_strategy, start_plot_dataframe, start_plot_profit,
|
start_new_strategy, start_plot_dataframe, start_plot_profit,
|
||||||
start_show_trades, start_strategy_update,
|
start_recursive_analysis, start_show_trades,
|
||||||
start_test_pairlist, start_trading, start_webserver)
|
start_strategy_update, start_test_pairlist, start_trading,
|
||||||
|
start_webserver)
|
||||||
|
|
||||||
subparsers = self.parser.add_subparsers(dest='command',
|
subparsers = self.parser.add_subparsers(dest='command',
|
||||||
# Use custom message when no subhandler is added
|
# Use custom message when no subhandler is added
|
||||||
@@ -467,3 +470,14 @@ class Arguments:
|
|||||||
|
|
||||||
self._build_args(optionlist=ARGS_LOOKAHEAD_ANALYSIS,
|
self._build_args(optionlist=ARGS_LOOKAHEAD_ANALYSIS,
|
||||||
parser=lookahead_analayis_cmd)
|
parser=lookahead_analayis_cmd)
|
||||||
|
|
||||||
|
# Add recursive_analysis subcommand
|
||||||
|
recursive_analayis_cmd = subparsers.add_parser(
|
||||||
|
'recursive-analysis',
|
||||||
|
help="Check for potential recursive formula issue.",
|
||||||
|
parents=[_common_parser, _strategy_parser])
|
||||||
|
|
||||||
|
recursive_analayis_cmd.set_defaults(func=start_recursive_analysis)
|
||||||
|
|
||||||
|
self._build_args(optionlist=ARGS_RECURSIVE_ANALYSIS,
|
||||||
|
parser=recursive_analayis_cmd)
|
||||||
|
|||||||
@@ -705,4 +705,9 @@ AVAILABLE_CLI_OPTIONS = {
|
|||||||
help="Use this csv-filename to store lookahead-analysis-results",
|
help="Use this csv-filename to store lookahead-analysis-results",
|
||||||
type=str
|
type=str
|
||||||
),
|
),
|
||||||
|
"startup_candle": Arg(
|
||||||
|
'--startup-candle',
|
||||||
|
help='Specify startup candles to be checked (`199`, `499`, `999`, `1999`).',
|
||||||
|
nargs='+',
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ from typing import Any, Dict
|
|||||||
|
|
||||||
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||||
from freqtrade.constants import DATETIME_PRINT_FORMAT, DL_DATA_TIMEFRAMES, Config
|
from freqtrade.constants import DATETIME_PRINT_FORMAT, DL_DATA_TIMEFRAMES, Config
|
||||||
from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format
|
from freqtrade.data.converter import (convert_ohlcv_format, convert_trades_format,
|
||||||
from freqtrade.data.history import convert_trades_to_ohlcv, download_data_main
|
convert_trades_to_ohlcv)
|
||||||
|
from freqtrade.data.history import download_data_main
|
||||||
from freqtrade.enums import RunMode, TradingMode
|
from freqtrade.enums import RunMode, TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
|
||||||
from freqtrade.resolvers import ExchangeResolver
|
from freqtrade.resolvers import ExchangeResolver
|
||||||
from freqtrade.util.binance_mig import migrate_binance_futures_data
|
from freqtrade.util.binance_mig import migrate_binance_futures_data
|
||||||
|
|
||||||
@@ -53,28 +53,19 @@ def start_convert_trades(args: Dict[str, Any]) -> None:
|
|||||||
# Remove stake-currency to skip checks which are not relevant for datadownload
|
# Remove stake-currency to skip checks which are not relevant for datadownload
|
||||||
config['stake_currency'] = ''
|
config['stake_currency'] = ''
|
||||||
|
|
||||||
if 'pairs' not in config:
|
|
||||||
raise OperationalException(
|
|
||||||
"Downloading data requires a list of pairs. "
|
|
||||||
"Please check the documentation on how to configure this.")
|
|
||||||
if 'timeframes' not in config:
|
if 'timeframes' not in config:
|
||||||
config['timeframes'] = DL_DATA_TIMEFRAMES
|
config['timeframes'] = DL_DATA_TIMEFRAMES
|
||||||
|
|
||||||
# Init exchange
|
# Init exchange
|
||||||
exchange = ExchangeResolver.load_exchange(config, validate=False)
|
exchange = ExchangeResolver.load_exchange(config, validate=False)
|
||||||
# Manual validations of relevant settings
|
# Manual validations of relevant settings
|
||||||
if not config['exchange'].get('skip_pair_validation', False):
|
|
||||||
exchange.validate_pairs(config['pairs'])
|
|
||||||
expanded_pairs = expand_pairlist(config['pairs'], list(exchange.markets))
|
|
||||||
|
|
||||||
logger.info(f"About to Convert pairs: {expanded_pairs}, "
|
|
||||||
f"intervals: {config['timeframes']} to {config['datadir']}")
|
|
||||||
|
|
||||||
for timeframe in config['timeframes']:
|
for timeframe in config['timeframes']:
|
||||||
exchange.validate_timeframes(timeframe)
|
exchange.validate_timeframes(timeframe)
|
||||||
|
|
||||||
# Convert downloaded trade data to different timeframes
|
# Convert downloaded trade data to different timeframes
|
||||||
convert_trades_to_ohlcv(
|
convert_trades_to_ohlcv(
|
||||||
pairs=expanded_pairs, timeframes=config['timeframes'],
|
pairs=config.get('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'],
|
||||||
|
|||||||
@@ -144,3 +144,15 @@ def start_lookahead_analysis(args: Dict[str, Any]) -> None:
|
|||||||
|
|
||||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
LookaheadAnalysisSubFunctions.start(config)
|
LookaheadAnalysisSubFunctions.start(config)
|
||||||
|
|
||||||
|
|
||||||
|
def start_recursive_analysis(args: Dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
Start the backtest recursive tester script
|
||||||
|
:param args: Cli args from Arguments()
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
from freqtrade.optimize.recursive_analysis_helpers import RecursiveAnalysisSubFunctions
|
||||||
|
|
||||||
|
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||||
|
RecursiveAnalysisSubFunctions.start(config)
|
||||||
|
|||||||
@@ -490,6 +490,9 @@ class Configuration:
|
|||||||
self._args_to_config(config, argname='lookahead_analysis_exportfilename',
|
self._args_to_config(config, argname='lookahead_analysis_exportfilename',
|
||||||
logstring='Path to store lookahead-analysis-results: {}')
|
logstring='Path to store lookahead-analysis-results: {}')
|
||||||
|
|
||||||
|
self._args_to_config(config, argname='startup_candle',
|
||||||
|
logstring='Startup candle to be used on recursive analysis: {}')
|
||||||
|
|
||||||
def _process_runmode(self, config: Config) -> None:
|
def _process_runmode(self, config: Config) -> None:
|
||||||
|
|
||||||
self._args_to_config(config, argname='dry_run',
|
self._args_to_config(config, argname='dry_run',
|
||||||
|
|||||||
+12
-2
@@ -33,7 +33,7 @@ HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
|
|||||||
'MaxDrawDownHyperOptLoss', 'MaxDrawDownRelativeHyperOptLoss',
|
'MaxDrawDownHyperOptLoss', 'MaxDrawDownRelativeHyperOptLoss',
|
||||||
'ProfitDrawDownHyperOptLoss']
|
'ProfitDrawDownHyperOptLoss']
|
||||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'ProducerPairList', 'RemotePairList',
|
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'ProducerPairList', 'RemotePairList',
|
||||||
'AgeFilter', 'OffsetFilter', 'PerformanceFilter',
|
'AgeFilter', "FullTradesFilter", 'OffsetFilter', 'PerformanceFilter',
|
||||||
'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter',
|
'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter',
|
||||||
'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter']
|
'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter']
|
||||||
AVAILABLE_PROTECTIONS = ['CooldownPeriod',
|
AVAILABLE_PROTECTIONS = ['CooldownPeriod',
|
||||||
@@ -77,7 +77,8 @@ DL_DATA_TIMEFRAMES = ['1m', '5m']
|
|||||||
|
|
||||||
ENV_VAR_PREFIX = 'FREQTRADE__'
|
ENV_VAR_PREFIX = 'FREQTRADE__'
|
||||||
|
|
||||||
NON_OPEN_EXCHANGE_STATES = ('cancelled', 'canceled', 'closed', 'expired')
|
CANCELED_EXCHANGE_STATES = ('cancelled', 'canceled', 'expired')
|
||||||
|
NON_OPEN_EXCHANGE_STATES = CANCELED_EXCHANGE_STATES + ('closed',)
|
||||||
|
|
||||||
# Define decimals per coin for outputs
|
# Define decimals per coin for outputs
|
||||||
# Only used for outputs.
|
# Only used for outputs.
|
||||||
@@ -177,6 +178,11 @@ CONF_SCHEMA = {
|
|||||||
'minimum_trade_amount': {'type': 'number', 'default': 10},
|
'minimum_trade_amount': {'type': 'number', 'default': 10},
|
||||||
'targeted_trade_amount': {'type': 'number', 'default': 20},
|
'targeted_trade_amount': {'type': 'number', 'default': 20},
|
||||||
'lookahead_analysis_exportfilename': {'type': 'string'},
|
'lookahead_analysis_exportfilename': {'type': 'string'},
|
||||||
|
'startup_candle': {
|
||||||
|
'type': 'array',
|
||||||
|
'uniqueItems': True,
|
||||||
|
'default': [199, 399, 499, 999, 1999],
|
||||||
|
},
|
||||||
'liquidation_buffer': {'type': 'number', 'minimum': 0.0, 'maximum': 0.99},
|
'liquidation_buffer': {'type': 'number', 'minimum': 0.0, 'maximum': 0.99},
|
||||||
'backtest_breakdown': {
|
'backtest_breakdown': {
|
||||||
'type': 'array',
|
'type': 'array',
|
||||||
@@ -688,6 +694,7 @@ CANCEL_REASON = {
|
|||||||
"CANCELLED_ON_EXCHANGE": "cancelled on exchange",
|
"CANCELLED_ON_EXCHANGE": "cancelled on exchange",
|
||||||
"FORCE_EXIT": "forcesold",
|
"FORCE_EXIT": "forcesold",
|
||||||
"REPLACE": "cancelled to be replaced by new limit order",
|
"REPLACE": "cancelled to be replaced by new limit order",
|
||||||
|
"REPLACE_FAILED": "failed to replace order, deleting Trade",
|
||||||
"USER_CANCEL": "user requested order cancel"
|
"USER_CANCEL": "user requested order cancel"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,3 +716,6 @@ Config = Dict[str, Any]
|
|||||||
# Exchange part of the configuration.
|
# Exchange part of the configuration.
|
||||||
ExchangeConfig = Dict[str, Any]
|
ExchangeConfig = Dict[str, Any]
|
||||||
IntOrInf = float
|
IntOrInf = float
|
||||||
|
|
||||||
|
|
||||||
|
EntryExecuteMode = Literal['initial', 'pos_adjust', 'replace']
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
from freqtrade.data.converter.converter import (clean_ohlcv_dataframe, convert_ohlcv_format,
|
||||||
|
ohlcv_fill_up_missing_data, ohlcv_to_dataframe,
|
||||||
|
order_book_to_dataframe, reduce_dataframe_footprint,
|
||||||
|
trim_dataframe, trim_dataframes)
|
||||||
|
from freqtrade.data.converter.trade_converter import (convert_trades_format,
|
||||||
|
convert_trades_to_ohlcv, trades_convert_types,
|
||||||
|
trades_df_remove_duplicates,
|
||||||
|
trades_dict_to_list, trades_list_to_df,
|
||||||
|
trades_to_ohlcv)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
'clean_ohlcv_dataframe',
|
||||||
|
'convert_ohlcv_format',
|
||||||
|
'ohlcv_fill_up_missing_data',
|
||||||
|
'ohlcv_to_dataframe',
|
||||||
|
'order_book_to_dataframe',
|
||||||
|
'reduce_dataframe_footprint',
|
||||||
|
'trim_dataframe',
|
||||||
|
'trim_dataframes',
|
||||||
|
'convert_trades_format',
|
||||||
|
'convert_trades_to_ohlcv',
|
||||||
|
'trades_convert_types',
|
||||||
|
'trades_df_remove_duplicates',
|
||||||
|
'trades_dict_to_list',
|
||||||
|
'trades_list_to_df',
|
||||||
|
'trades_to_ohlcv',
|
||||||
|
]
|
||||||
@@ -2,14 +2,13 @@
|
|||||||
Functions to convert data from one format to another
|
Functions to convert data from one format to another
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, List
|
from typing import Dict
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas import DataFrame, to_datetime
|
from pandas import DataFrame, to_datetime
|
||||||
|
|
||||||
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TRADES_DTYPES,
|
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, Config
|
||||||
Config, TradeList)
|
|
||||||
from freqtrade.enums import CandleType, TradingMode
|
from freqtrade.enums import CandleType, TradingMode
|
||||||
|
|
||||||
|
|
||||||
@@ -105,7 +104,7 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str)
|
|||||||
df = dataframe.resample(resample_interval, on='date').agg(ohlcv_dict)
|
df = dataframe.resample(resample_interval, on='date').agg(ohlcv_dict)
|
||||||
|
|
||||||
# Forwardfill close for missing columns
|
# Forwardfill close for missing columns
|
||||||
df['close'] = df['close'].fillna(method='ffill')
|
df['close'] = df['close'].ffill()
|
||||||
# Use close for "open, high, low"
|
# Use close for "open, high, low"
|
||||||
df.loc[:, ['open', 'high', 'low']] = df[['open', 'high', 'low']].fillna(
|
df.loc[:, ['open', 'high', 'low']] = df[['open', 'high', 'low']].fillna(
|
||||||
value={'open': df['close'],
|
value={'open': df['close'],
|
||||||
@@ -194,97 +193,6 @@ def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
|||||||
return frame
|
return frame
|
||||||
|
|
||||||
|
|
||||||
def trades_df_remove_duplicates(trades: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
"""
|
|
||||||
Removes duplicates from the trades DataFrame.
|
|
||||||
Uses pandas.DataFrame.drop_duplicates to remove duplicates based on the 'timestamp' column.
|
|
||||||
:param trades: DataFrame with the columns constants.DEFAULT_TRADES_COLUMNS
|
|
||||||
:return: DataFrame with duplicates removed based on the 'timestamp' column
|
|
||||||
"""
|
|
||||||
return trades.drop_duplicates(subset=['timestamp', 'id'])
|
|
||||||
|
|
||||||
|
|
||||||
def trades_dict_to_list(trades: List[Dict]) -> TradeList:
|
|
||||||
"""
|
|
||||||
Convert fetch_trades result into a List (to be more memory efficient).
|
|
||||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
|
||||||
:return: List of Lists, with constants.DEFAULT_TRADES_COLUMNS as columns
|
|
||||||
"""
|
|
||||||
return [[t[col] for col in DEFAULT_TRADES_COLUMNS] for t in trades]
|
|
||||||
|
|
||||||
|
|
||||||
def trades_convert_types(trades: DataFrame) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Convert Trades dtypes and add 'date' column
|
|
||||||
"""
|
|
||||||
trades = trades.astype(TRADES_DTYPES)
|
|
||||||
trades['date'] = to_datetime(trades['timestamp'], unit='ms', utc=True)
|
|
||||||
return trades
|
|
||||||
|
|
||||||
|
|
||||||
def trades_list_to_df(trades: TradeList, convert: bool = True):
|
|
||||||
"""
|
|
||||||
convert trades list to dataframe
|
|
||||||
:param trades: List of Lists with constants.DEFAULT_TRADES_COLUMNS as columns
|
|
||||||
"""
|
|
||||||
if not trades:
|
|
||||||
df = DataFrame(columns=DEFAULT_TRADES_COLUMNS)
|
|
||||||
else:
|
|
||||||
df = DataFrame(trades, columns=DEFAULT_TRADES_COLUMNS)
|
|
||||||
|
|
||||||
if convert:
|
|
||||||
df = trades_convert_types(df)
|
|
||||||
|
|
||||||
return df
|
|
||||||
|
|
||||||
|
|
||||||
def trades_to_ohlcv(trades: DataFrame, timeframe: str) -> DataFrame:
|
|
||||||
"""
|
|
||||||
Converts trades list to OHLCV list
|
|
||||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
|
||||||
:param timeframe: Timeframe to resample data to
|
|
||||||
:return: OHLCV Dataframe.
|
|
||||||
:raises: ValueError if no trades are provided
|
|
||||||
"""
|
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
|
||||||
timeframe_minutes = timeframe_to_minutes(timeframe)
|
|
||||||
if trades.empty:
|
|
||||||
raise ValueError('Trade-list empty.')
|
|
||||||
df = trades.set_index('date', drop=True)
|
|
||||||
|
|
||||||
df_new = df['price'].resample(f'{timeframe_minutes}min').ohlc()
|
|
||||||
df_new['volume'] = df['amount'].resample(f'{timeframe_minutes}min').sum()
|
|
||||||
df_new['date'] = df_new.index
|
|
||||||
# Drop 0 volume rows
|
|
||||||
df_new = df_new.dropna()
|
|
||||||
return df_new.loc[:, DEFAULT_DATAFRAME_COLUMNS]
|
|
||||||
|
|
||||||
|
|
||||||
def convert_trades_format(config: Config, convert_from: str, convert_to: str, erase: bool):
|
|
||||||
"""
|
|
||||||
Convert trades from one format to another format.
|
|
||||||
:param config: Config dictionary
|
|
||||||
:param convert_from: Source format
|
|
||||||
:param convert_to: Target format
|
|
||||||
:param erase: Erase source data (does not apply if source and target format are identical)
|
|
||||||
"""
|
|
||||||
from freqtrade.data.history.idatahandler import get_datahandler
|
|
||||||
src = get_datahandler(config['datadir'], convert_from)
|
|
||||||
trg = get_datahandler(config['datadir'], convert_to)
|
|
||||||
|
|
||||||
if 'pairs' not in config:
|
|
||||||
config['pairs'] = src.trades_get_pairs(config['datadir'])
|
|
||||||
logger.info(f"Converting trades for {config['pairs']}")
|
|
||||||
|
|
||||||
for pair in config['pairs']:
|
|
||||||
data = src.trades_load(pair=pair)
|
|
||||||
logger.info(f"Converting {len(data)} trades for {pair}")
|
|
||||||
trg.trades_store(pair, data)
|
|
||||||
if erase and convert_from != convert_to:
|
|
||||||
logger.info(f"Deleting source Trade data for {pair}.")
|
|
||||||
src.trades_purge(pair=pair)
|
|
||||||
|
|
||||||
|
|
||||||
def convert_ohlcv_format(
|
def convert_ohlcv_format(
|
||||||
config: Config,
|
config: Config,
|
||||||
convert_from: str,
|
convert_from: str,
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"""
|
||||||
|
Functions to convert data from one format to another
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
from pandas import DataFrame, to_datetime
|
||||||
|
|
||||||
|
from freqtrade.configuration import TimeRange
|
||||||
|
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TRADES_DTYPES,
|
||||||
|
Config, TradeList)
|
||||||
|
from freqtrade.enums import CandleType
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def trades_df_remove_duplicates(trades: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Removes duplicates from the trades DataFrame.
|
||||||
|
Uses pandas.DataFrame.drop_duplicates to remove duplicates based on the 'timestamp' column.
|
||||||
|
:param trades: DataFrame with the columns constants.DEFAULT_TRADES_COLUMNS
|
||||||
|
:return: DataFrame with duplicates removed based on the 'timestamp' column
|
||||||
|
"""
|
||||||
|
return trades.drop_duplicates(subset=['timestamp', 'id'])
|
||||||
|
|
||||||
|
|
||||||
|
def trades_dict_to_list(trades: List[Dict]) -> TradeList:
|
||||||
|
"""
|
||||||
|
Convert fetch_trades result into a List (to be more memory efficient).
|
||||||
|
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||||
|
:return: List of Lists, with constants.DEFAULT_TRADES_COLUMNS as columns
|
||||||
|
"""
|
||||||
|
return [[t[col] for col in DEFAULT_TRADES_COLUMNS] for t in trades]
|
||||||
|
|
||||||
|
|
||||||
|
def trades_convert_types(trades: DataFrame) -> DataFrame:
|
||||||
|
"""
|
||||||
|
Convert Trades dtypes and add 'date' column
|
||||||
|
"""
|
||||||
|
trades = trades.astype(TRADES_DTYPES)
|
||||||
|
trades['date'] = to_datetime(trades['timestamp'], unit='ms', utc=True)
|
||||||
|
return trades
|
||||||
|
|
||||||
|
|
||||||
|
def trades_list_to_df(trades: TradeList, convert: bool = True):
|
||||||
|
"""
|
||||||
|
convert trades list to dataframe
|
||||||
|
:param trades: List of Lists with constants.DEFAULT_TRADES_COLUMNS as columns
|
||||||
|
"""
|
||||||
|
if not trades:
|
||||||
|
df = DataFrame(columns=DEFAULT_TRADES_COLUMNS)
|
||||||
|
else:
|
||||||
|
df = DataFrame(trades, columns=DEFAULT_TRADES_COLUMNS)
|
||||||
|
|
||||||
|
if convert:
|
||||||
|
df = trades_convert_types(df)
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
def trades_to_ohlcv(trades: DataFrame, timeframe: str) -> DataFrame:
|
||||||
|
"""
|
||||||
|
Converts trades list to OHLCV list
|
||||||
|
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||||
|
:param timeframe: Timeframe to resample data to
|
||||||
|
:return: OHLCV Dataframe.
|
||||||
|
:raises: ValueError if no trades are provided
|
||||||
|
"""
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
timeframe_minutes = timeframe_to_minutes(timeframe)
|
||||||
|
if trades.empty:
|
||||||
|
raise ValueError('Trade-list empty.')
|
||||||
|
df = trades.set_index('date', drop=True)
|
||||||
|
|
||||||
|
df_new = df['price'].resample(f'{timeframe_minutes}min').ohlc()
|
||||||
|
df_new['volume'] = df['amount'].resample(f'{timeframe_minutes}min').sum()
|
||||||
|
df_new['date'] = df_new.index
|
||||||
|
# Drop 0 volume rows
|
||||||
|
df_new = df_new.dropna()
|
||||||
|
return df_new.loc[:, DEFAULT_DATAFRAME_COLUMNS]
|
||||||
|
|
||||||
|
|
||||||
|
def convert_trades_to_ohlcv(
|
||||||
|
pairs: List[str],
|
||||||
|
timeframes: List[str],
|
||||||
|
datadir: Path,
|
||||||
|
timerange: TimeRange,
|
||||||
|
erase: bool = False,
|
||||||
|
data_format_ohlcv: str = 'feather',
|
||||||
|
data_format_trades: str = 'feather',
|
||||||
|
candle_type: CandleType = CandleType.SPOT
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Convert stored trades data to ohlcv data
|
||||||
|
"""
|
||||||
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
|
data_handler_trades = get_datahandler(datadir, data_format=data_format_trades)
|
||||||
|
data_handler_ohlcv = get_datahandler(datadir, data_format=data_format_ohlcv)
|
||||||
|
if not pairs:
|
||||||
|
pairs = data_handler_trades.trades_get_pairs(datadir)
|
||||||
|
|
||||||
|
logger.info(f"About to convert pairs: '{', '.join(pairs)}', "
|
||||||
|
f"intervals: '{', '.join(timeframes)}' to {datadir}")
|
||||||
|
|
||||||
|
for pair in pairs:
|
||||||
|
trades = data_handler_trades.trades_load(pair)
|
||||||
|
for timeframe in timeframes:
|
||||||
|
if erase:
|
||||||
|
if data_handler_ohlcv.ohlcv_purge(pair, timeframe, candle_type=candle_type):
|
||||||
|
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||||
|
try:
|
||||||
|
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||||
|
# Store ohlcv
|
||||||
|
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv, candle_type=candle_type)
|
||||||
|
except ValueError:
|
||||||
|
logger.exception(f'Could not convert {pair} to OHLCV.')
|
||||||
|
|
||||||
|
|
||||||
|
def convert_trades_format(config: Config, convert_from: str, convert_to: str, erase: bool):
|
||||||
|
"""
|
||||||
|
Convert trades from one format to another format.
|
||||||
|
:param config: Config dictionary
|
||||||
|
:param convert_from: Source format
|
||||||
|
:param convert_to: Target format
|
||||||
|
:param erase: Erase source data (does not apply if source and target format are identical)
|
||||||
|
"""
|
||||||
|
from freqtrade.data.history.idatahandler import get_datahandler
|
||||||
|
src = get_datahandler(config['datadir'], convert_from)
|
||||||
|
trg = get_datahandler(config['datadir'], convert_to)
|
||||||
|
|
||||||
|
if 'pairs' not in config:
|
||||||
|
config['pairs'] = src.trades_get_pairs(config['datadir'])
|
||||||
|
logger.info(f"Converting trades for {config['pairs']}")
|
||||||
|
|
||||||
|
for pair in config['pairs']:
|
||||||
|
data = src.trades_load(pair=pair)
|
||||||
|
logger.info(f"Converting {len(data)} trades for {pair}")
|
||||||
|
trg.trades_store(pair, data)
|
||||||
|
if erase and convert_from != convert_to:
|
||||||
|
logger.info(f"Deleting source Trade data for {pair}.")
|
||||||
|
src.trades_purge(pair=pair)
|
||||||
@@ -119,8 +119,15 @@ def _do_group_table_output(bigdf, glist, csv_path: Path, to_csv=False, ):
|
|||||||
new['avg_win'] = (new['profit_abs_wins'] / new.iloc[:, 1]).fillna(0)
|
new['avg_win'] = (new['profit_abs_wins'] / new.iloc[:, 1]).fillna(0)
|
||||||
new['avg_loss'] = (new['profit_abs_loss'] / new.iloc[:, 2]).fillna(0)
|
new['avg_loss'] = (new['profit_abs_loss'] / new.iloc[:, 2]).fillna(0)
|
||||||
|
|
||||||
new.columns = ['total_num_buys', 'wins', 'losses', 'profit_abs_wins', 'profit_abs_loss',
|
new['exp_ratio'] = (
|
||||||
'profit_tot', 'wl_ratio_pct', 'avg_win', 'avg_loss']
|
(
|
||||||
|
(1 + (new['avg_win'] / abs(new['avg_loss']))) * (new['wl_ratio_pct'] / 100)
|
||||||
|
) - 1).fillna(0)
|
||||||
|
|
||||||
|
new.columns = ['total_num_buys', 'wins', 'losses',
|
||||||
|
'profit_abs_wins', 'profit_abs_loss',
|
||||||
|
'profit_tot', 'wl_ratio_pct',
|
||||||
|
'avg_win', 'avg_loss', 'exp_ratio']
|
||||||
|
|
||||||
sortcols = ['total_num_buys']
|
sortcols = ['total_num_buys']
|
||||||
|
|
||||||
@@ -204,6 +211,7 @@ def prepare_results(analysed_trades, stratname,
|
|||||||
timerange=None):
|
timerange=None):
|
||||||
res_df = pd.DataFrame()
|
res_df = pd.DataFrame()
|
||||||
for pair, trades in analysed_trades[stratname].items():
|
for pair, trades in analysed_trades[stratname].items():
|
||||||
|
trades.dropna(subset=['close_date'], inplace=True)
|
||||||
res_df = pd.concat([res_df, trades], ignore_index=True)
|
res_df = pd.concat([res_df, trades], ignore_index=True)
|
||||||
|
|
||||||
res_df = _select_rows_within_dates(res_df, timerange)
|
res_df = _select_rows_within_dates(res_df, timerange)
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ from pandas import DataFrame, concat
|
|||||||
from freqtrade.configuration import TimeRange
|
from freqtrade.configuration import TimeRange
|
||||||
from freqtrade.constants import (DATETIME_PRINT_FORMAT, DEFAULT_DATAFRAME_COLUMNS,
|
from freqtrade.constants import (DATETIME_PRINT_FORMAT, DEFAULT_DATAFRAME_COLUMNS,
|
||||||
DL_DATA_TIMEFRAMES, Config)
|
DL_DATA_TIMEFRAMES, Config)
|
||||||
from freqtrade.data.converter import (clean_ohlcv_dataframe, ohlcv_to_dataframe,
|
from freqtrade.data.converter import (clean_ohlcv_dataframe, convert_trades_to_ohlcv,
|
||||||
trades_df_remove_duplicates, trades_list_to_df,
|
ohlcv_to_dataframe, trades_df_remove_duplicates,
|
||||||
trades_to_ohlcv)
|
trades_list_to_df)
|
||||||
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
||||||
from freqtrade.enums import CandleType
|
from freqtrade.enums import CandleType
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
@@ -429,36 +429,6 @@ def refresh_backtest_trades_data(exchange: Exchange, pairs: List[str], datadir:
|
|||||||
return pairs_not_available
|
return pairs_not_available
|
||||||
|
|
||||||
|
|
||||||
def convert_trades_to_ohlcv(
|
|
||||||
pairs: List[str],
|
|
||||||
timeframes: List[str],
|
|
||||||
datadir: Path,
|
|
||||||
timerange: TimeRange,
|
|
||||||
erase: bool = False,
|
|
||||||
data_format_ohlcv: str = 'feather',
|
|
||||||
data_format_trades: str = 'feather',
|
|
||||||
candle_type: CandleType = CandleType.SPOT
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Convert stored trades data to ohlcv data
|
|
||||||
"""
|
|
||||||
data_handler_trades = get_datahandler(datadir, data_format=data_format_trades)
|
|
||||||
data_handler_ohlcv = get_datahandler(datadir, data_format=data_format_ohlcv)
|
|
||||||
|
|
||||||
for pair in pairs:
|
|
||||||
trades = data_handler_trades.trades_load(pair)
|
|
||||||
for timeframe in timeframes:
|
|
||||||
if erase:
|
|
||||||
if data_handler_ohlcv.ohlcv_purge(pair, timeframe, candle_type=candle_type):
|
|
||||||
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
|
||||||
try:
|
|
||||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
|
||||||
# Store ohlcv
|
|
||||||
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv, candle_type=candle_type)
|
|
||||||
except ValueError:
|
|
||||||
logger.exception(f'Could not convert {pair} to OHLCV.')
|
|
||||||
|
|
||||||
|
|
||||||
def get_timerange(data: Dict[str, DataFrame]) -> Tuple[datetime, datetime]:
|
def get_timerange(data: Dict[str, DataFrame]) -> Tuple[datetime, datetime]:
|
||||||
"""
|
"""
|
||||||
Get the maximum common timerange for the given backtest data.
|
Get the maximum common timerange for the given backtest data.
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ class Binance(Exchange):
|
|||||||
|
|
||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
|
"stop_price_param": "stopPrice",
|
||||||
|
"stop_price_prop": "stopPrice",
|
||||||
"stoploss_order_types": {"limit": "stop_loss_limit"},
|
"stoploss_order_types": {"limit": "stop_loss_limit"},
|
||||||
"order_time_in_force": ["GTC", "FOK", "IOC", "PO"],
|
"order_time_in_force": ["GTC", "FOK", "IOC", "PO"],
|
||||||
"ohlcv_candle_limit": 1000,
|
"ohlcv_candle_limit": 1000,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,16 @@
|
|||||||
""" Bybit exchange subclass """
|
""" Bybit exchange subclass """
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import ccxt
|
import ccxt
|
||||||
|
|
||||||
from freqtrade.constants import BuySell
|
from freqtrade.constants import BuySell
|
||||||
from freqtrade.enums import MarginMode, PriceType, TradingMode
|
from freqtrade.enums import CandleType, MarginMode, PriceType, TradingMode
|
||||||
from freqtrade.enums.candletype import CandleType
|
|
||||||
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
||||||
from freqtrade.exchange import Exchange
|
from freqtrade.exchange import Exchange
|
||||||
from freqtrade.exchange.common import retrier
|
from freqtrade.exchange.common import retrier
|
||||||
|
from freqtrade.util.datetime_helpers import dt_now, dt_ts
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -36,6 +36,8 @@ class Bybit(Exchange):
|
|||||||
"funding_fee_timeframe": "8h",
|
"funding_fee_timeframe": "8h",
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
||||||
|
# bybit response parsing fails to populate stopLossPrice
|
||||||
|
"stop_price_prop": "stopPrice",
|
||||||
"stop_price_type_field": "triggerBy",
|
"stop_price_type_field": "triggerBy",
|
||||||
"stop_price_type_value_mapping": {
|
"stop_price_type_value_mapping": {
|
||||||
PriceType.LAST: "LastPrice",
|
PriceType.LAST: "LastPrice",
|
||||||
@@ -203,3 +205,31 @@ class Bybit(Exchange):
|
|||||||
return self._fetch_and_calculate_funding_fees(
|
return self._fetch_and_calculate_funding_fees(
|
||||||
pair, amount, is_short, open_date)
|
pair, amount, is_short, open_date)
|
||||||
return 0.0
|
return 0.0
|
||||||
|
|
||||||
|
def fetch_orders(self, pair: str, since: datetime, params: Optional[Dict] = None) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Fetch all orders for a pair "since"
|
||||||
|
:param pair: Pair for the query
|
||||||
|
:param since: Starting time for the query
|
||||||
|
"""
|
||||||
|
# On bybit, the distance between since and "until" can't exceed 7 days.
|
||||||
|
# we therefore need to split the query into multiple queries.
|
||||||
|
orders = []
|
||||||
|
|
||||||
|
while since < dt_now():
|
||||||
|
until = since + timedelta(days=7, minutes=-1)
|
||||||
|
orders += super().fetch_orders(pair, since, params={'until': dt_ts(until)})
|
||||||
|
since = until
|
||||||
|
|
||||||
|
return orders
|
||||||
|
|
||||||
|
def fetch_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict:
|
||||||
|
order = super().fetch_order(order_id, pair, params)
|
||||||
|
if (
|
||||||
|
order.get('status') == 'canceled'
|
||||||
|
and order.get('filled') == 0.0
|
||||||
|
and order.get('remaining') == 0.0
|
||||||
|
):
|
||||||
|
# Canceled orders will have "remaining=0" on bybit.
|
||||||
|
order['remaining'] = None
|
||||||
|
return order
|
||||||
|
|||||||
@@ -23,8 +23,7 @@ from freqtrade.constants import (DEFAULT_AMOUNT_RESERVE_PERCENT, NON_OPEN_EXCHAN
|
|||||||
BuySell, Config, EntryExit, ExchangeConfig,
|
BuySell, Config, EntryExit, ExchangeConfig,
|
||||||
ListPairsWithTimeframes, MakerTaker, OBLiteral, PairWithTimeframe)
|
ListPairsWithTimeframes, MakerTaker, OBLiteral, PairWithTimeframe)
|
||||||
from freqtrade.data.converter import clean_ohlcv_dataframe, ohlcv_to_dataframe, trades_dict_to_list
|
from freqtrade.data.converter import clean_ohlcv_dataframe, ohlcv_to_dataframe, trades_dict_to_list
|
||||||
from freqtrade.enums import OPTIMIZE_MODES, CandleType, MarginMode, TradingMode
|
from freqtrade.enums import OPTIMIZE_MODES, CandleType, MarginMode, PriceType, TradingMode
|
||||||
from freqtrade.enums.pricetype import PriceType
|
|
||||||
from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError,
|
from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError,
|
||||||
InvalidOrderException, OperationalException, PricingError,
|
InvalidOrderException, OperationalException, PricingError,
|
||||||
RetryableOrderError, TemporaryError)
|
RetryableOrderError, TemporaryError)
|
||||||
@@ -62,7 +61,8 @@ class Exchange:
|
|||||||
# or by specifying them in the configuration.
|
# or by specifying them in the configuration.
|
||||||
_ft_has_default: Dict = {
|
_ft_has_default: Dict = {
|
||||||
"stoploss_on_exchange": False,
|
"stoploss_on_exchange": False,
|
||||||
"stop_price_param": "stopPrice",
|
"stop_price_param": "stopLossPrice", # Used for stoploss_on_exchange request
|
||||||
|
"stop_price_prop": "stopLossPrice", # Used for stoploss_on_exchange response parsing
|
||||||
"order_time_in_force": ["GTC"],
|
"order_time_in_force": ["GTC"],
|
||||||
"ohlcv_params": {},
|
"ohlcv_params": {},
|
||||||
"ohlcv_candle_limit": 500,
|
"ohlcv_candle_limit": 500,
|
||||||
@@ -832,7 +832,7 @@ class Exchange:
|
|||||||
rate: float, leverage: float, params: Dict = {},
|
rate: float, leverage: float, params: Dict = {},
|
||||||
stop_loss: bool = False) -> Dict[str, Any]:
|
stop_loss: bool = False) -> Dict[str, Any]:
|
||||||
now = dt_now()
|
now = dt_now()
|
||||||
order_id = f'dry_run_{side}_{now.timestamp()}'
|
order_id = f'dry_run_{side}_{pair}_{now.timestamp()}'
|
||||||
# Rounding here must respect to contract sizes
|
# Rounding here must respect to contract sizes
|
||||||
_amount = self._contracts_to_amount(
|
_amount = self._contracts_to_amount(
|
||||||
pair, self.amount_to_precision(pair, self._amount_to_contracts(pair, amount)))
|
pair, self.amount_to_precision(pair, self._amount_to_contracts(pair, amount)))
|
||||||
@@ -856,15 +856,15 @@ class Exchange:
|
|||||||
}
|
}
|
||||||
if stop_loss:
|
if stop_loss:
|
||||||
dry_order["info"] = {"stopPrice": dry_order["price"]}
|
dry_order["info"] = {"stopPrice": dry_order["price"]}
|
||||||
dry_order[self._ft_has['stop_price_param']] = dry_order["price"]
|
dry_order[self._ft_has['stop_price_prop']] = dry_order["price"]
|
||||||
# Workaround to avoid filling stoploss orders immediately
|
# Workaround to avoid filling stoploss orders immediately
|
||||||
dry_order["ft_order_type"] = "stoploss"
|
dry_order["ft_order_type"] = "stoploss"
|
||||||
orderbook: Optional[OrderBook] = None
|
orderbook: Optional[OrderBook] = None
|
||||||
if self.exchange_has('fetchL2OrderBook'):
|
if self.exchange_has('fetchL2OrderBook'):
|
||||||
orderbook = self.fetch_l2_order_book(pair, 20)
|
orderbook = self.fetch_l2_order_book(pair, 20)
|
||||||
if ordertype == "limit" and orderbook:
|
if ordertype == "limit" and orderbook:
|
||||||
# Allow a 3% price difference
|
# Allow a 1% price difference
|
||||||
allowed_diff = 0.03
|
allowed_diff = 0.01
|
||||||
if self._dry_is_price_crossed(pair, side, rate, orderbook, allowed_diff):
|
if self._dry_is_price_crossed(pair, side, rate, orderbook, allowed_diff):
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Converted order {pair} to market order due to price {rate} crossing spread "
|
f"Converted order {pair} to market order due to price {rate} crossing spread "
|
||||||
@@ -920,7 +920,7 @@ class Exchange:
|
|||||||
max_slippage_val = rate * ((1 + slippage) if side == 'buy' else (1 - slippage))
|
max_slippage_val = rate * ((1 + slippage) if side == 'buy' else (1 - slippage))
|
||||||
|
|
||||||
remaining_amount = amount
|
remaining_amount = amount
|
||||||
filled_amount = 0.0
|
filled_value = 0.0
|
||||||
book_entry_price = 0.0
|
book_entry_price = 0.0
|
||||||
for book_entry in orderbook[ob_type]:
|
for book_entry in orderbook[ob_type]:
|
||||||
book_entry_price = book_entry[0]
|
book_entry_price = book_entry[0]
|
||||||
@@ -928,17 +928,17 @@ class Exchange:
|
|||||||
if remaining_amount > 0:
|
if remaining_amount > 0:
|
||||||
if remaining_amount < book_entry_coin_volume:
|
if remaining_amount < book_entry_coin_volume:
|
||||||
# Orderbook at this slot bigger than remaining amount
|
# Orderbook at this slot bigger than remaining amount
|
||||||
filled_amount += remaining_amount * book_entry_price
|
filled_value += remaining_amount * book_entry_price
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
filled_amount += book_entry_coin_volume * book_entry_price
|
filled_value += book_entry_coin_volume * book_entry_price
|
||||||
remaining_amount -= book_entry_coin_volume
|
remaining_amount -= book_entry_coin_volume
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
# If remaining_amount wasn't consumed completely (break was not called)
|
# If remaining_amount wasn't consumed completely (break was not called)
|
||||||
filled_amount += remaining_amount * book_entry_price
|
filled_value += remaining_amount * book_entry_price
|
||||||
forecast_avg_filled_price = max(filled_amount, 0) / amount
|
forecast_avg_filled_price = max(filled_value, 0) / amount
|
||||||
# Limit max. slippage to specified value
|
# Limit max. slippage to specified value
|
||||||
if side == 'buy':
|
if side == 'buy':
|
||||||
forecast_avg_filled_price = min(forecast_avg_filled_price, max_slippage_val)
|
forecast_avg_filled_price = min(forecast_avg_filled_price, max_slippage_val)
|
||||||
@@ -1008,7 +1008,7 @@ class Exchange:
|
|||||||
from freqtrade.persistence import Order
|
from freqtrade.persistence import Order
|
||||||
order = Order.order_by_id(order_id)
|
order = Order.order_by_id(order_id)
|
||||||
if order:
|
if order:
|
||||||
ccxt_order = order.to_ccxt_object(self._ft_has['stop_price_param'])
|
ccxt_order = order.to_ccxt_object(self._ft_has['stop_price_prop'])
|
||||||
self._dry_run_open_orders[order_id] = ccxt_order
|
self._dry_run_open_orders[order_id] = ccxt_order
|
||||||
return ccxt_order
|
return ccxt_order
|
||||||
# Gracefully handle errors with dry-run orders.
|
# Gracefully handle errors with dry-run orders.
|
||||||
@@ -1080,6 +1080,13 @@ class Exchange:
|
|||||||
rate_for_order,
|
rate_for_order,
|
||||||
params,
|
params,
|
||||||
)
|
)
|
||||||
|
if order.get('status') is None:
|
||||||
|
# Map empty status to open.
|
||||||
|
order['status'] = 'open'
|
||||||
|
|
||||||
|
if order.get('type') is None:
|
||||||
|
order['type'] = ordertype
|
||||||
|
|
||||||
self._log_exchange_response('create_order', order)
|
self._log_exchange_response('create_order', order)
|
||||||
order = self._order_contracts_to_amount(order)
|
order = self._order_contracts_to_amount(order)
|
||||||
return order
|
return order
|
||||||
@@ -1109,7 +1116,7 @@ class Exchange:
|
|||||||
"""
|
"""
|
||||||
if not self._ft_has.get('stoploss_on_exchange'):
|
if not self._ft_has.get('stoploss_on_exchange'):
|
||||||
raise OperationalException(f"stoploss is not implemented for {self.name}.")
|
raise OperationalException(f"stoploss is not implemented for {self.name}.")
|
||||||
price_param = self._ft_has['stop_price_param']
|
price_param = self._ft_has['stop_price_prop']
|
||||||
return (
|
return (
|
||||||
order.get(price_param, None) is None
|
order.get(price_param, None) is None
|
||||||
or ((side == "sell" and stop_loss > float(order[price_param])) or
|
or ((side == "sell" and stop_loss > float(order[price_param])) or
|
||||||
@@ -1421,8 +1428,17 @@ class Exchange:
|
|||||||
except ccxt.BaseError as e:
|
except ccxt.BaseError as e:
|
||||||
raise OperationalException(e) from e
|
raise OperationalException(e) from e
|
||||||
|
|
||||||
|
def _fetch_orders_emulate(self, pair: str, since_ms: int) -> List[Dict]:
|
||||||
|
orders = []
|
||||||
|
if self.exchange_has('fetchClosedOrders'):
|
||||||
|
orders = self._api.fetch_closed_orders(pair, since=since_ms)
|
||||||
|
if self.exchange_has('fetchOpenOrders'):
|
||||||
|
orders_open = self._api.fetch_open_orders(pair, since=since_ms)
|
||||||
|
orders.extend(orders_open)
|
||||||
|
return orders
|
||||||
|
|
||||||
@retrier(retries=0)
|
@retrier(retries=0)
|
||||||
def fetch_orders(self, pair: str, since: datetime) -> List[Dict]:
|
def fetch_orders(self, pair: str, since: datetime, params: Optional[Dict] = None) -> List[Dict]:
|
||||||
"""
|
"""
|
||||||
Fetch all orders for a pair "since"
|
Fetch all orders for a pair "since"
|
||||||
:param pair: Pair for the query
|
:param pair: Pair for the query
|
||||||
@@ -1431,26 +1447,20 @@ class Exchange:
|
|||||||
if self._config['dry_run']:
|
if self._config['dry_run']:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def fetch_orders_emulate() -> List[Dict]:
|
|
||||||
orders = []
|
|
||||||
if self.exchange_has('fetchClosedOrders'):
|
|
||||||
orders = self._api.fetch_closed_orders(pair, since=since_ms)
|
|
||||||
if self.exchange_has('fetchOpenOrders'):
|
|
||||||
orders_open = self._api.fetch_open_orders(pair, since=since_ms)
|
|
||||||
orders.extend(orders_open)
|
|
||||||
return orders
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
since_ms = int((since.timestamp() - 10) * 1000)
|
since_ms = int((since.timestamp() - 10) * 1000)
|
||||||
|
|
||||||
if self.exchange_has('fetchOrders'):
|
if self.exchange_has('fetchOrders'):
|
||||||
|
if not params:
|
||||||
|
params = {}
|
||||||
try:
|
try:
|
||||||
orders: List[Dict] = self._api.fetch_orders(pair, since=since_ms)
|
orders: List[Dict] = self._api.fetch_orders(pair, since=since_ms, params=params)
|
||||||
except ccxt.NotSupported:
|
except ccxt.NotSupported:
|
||||||
# Some exchanges don't support fetchOrders
|
# Some exchanges don't support fetchOrders
|
||||||
# attempt to fetch open and closed orders separately
|
# attempt to fetch open and closed orders separately
|
||||||
orders = fetch_orders_emulate()
|
orders = self._fetch_orders_emulate(pair, since_ms)
|
||||||
else:
|
else:
|
||||||
orders = fetch_orders_emulate()
|
orders = self._fetch_orders_emulate(pair, since_ms)
|
||||||
self._log_exchange_response('fetch_orders', orders)
|
self._log_exchange_response('fetch_orders', orders)
|
||||||
orders = [self._order_contracts_to_amount(o) for o in orders]
|
orders = [self._order_contracts_to_amount(o) for o in orders]
|
||||||
return orders
|
return orders
|
||||||
|
|||||||
@@ -248,6 +248,39 @@ def amount_to_contract_precision(
|
|||||||
return amount
|
return amount
|
||||||
|
|
||||||
|
|
||||||
|
def __price_to_precision_significant_digits(
|
||||||
|
price: float,
|
||||||
|
price_precision: float,
|
||||||
|
*,
|
||||||
|
rounding_mode: int = ROUND,
|
||||||
|
) -> float:
|
||||||
|
"""
|
||||||
|
Implementation of ROUND_UP/Round_down for significant digits mode.
|
||||||
|
"""
|
||||||
|
from decimal import ROUND_DOWN as dec_ROUND_DOWN
|
||||||
|
from decimal import ROUND_UP as dec_ROUND_UP
|
||||||
|
from decimal import Decimal
|
||||||
|
dec = Decimal(str(price))
|
||||||
|
string = f'{dec:f}'
|
||||||
|
precision = round(price_precision)
|
||||||
|
|
||||||
|
q = precision - dec.adjusted() - 1
|
||||||
|
sigfig = Decimal('10') ** -q
|
||||||
|
if q < 0:
|
||||||
|
string_to_precision = string[:precision]
|
||||||
|
# string_to_precision is '' when we have zero precision
|
||||||
|
below = sigfig * Decimal(string_to_precision if string_to_precision else '0')
|
||||||
|
above = below + sigfig
|
||||||
|
res = above if rounding_mode == ROUND_UP else below
|
||||||
|
precise = f'{res:f}'
|
||||||
|
else:
|
||||||
|
precise = '{:f}'.format(dec.quantize(
|
||||||
|
sigfig,
|
||||||
|
rounding=dec_ROUND_DOWN if rounding_mode == ROUND_DOWN else dec_ROUND_UP)
|
||||||
|
)
|
||||||
|
return float(precise)
|
||||||
|
|
||||||
|
|
||||||
def price_to_precision(
|
def price_to_precision(
|
||||||
price: float,
|
price: float,
|
||||||
price_precision: Optional[float],
|
price_precision: Optional[float],
|
||||||
@@ -271,28 +304,39 @@ def price_to_precision(
|
|||||||
:return: price rounded up to the precision the Exchange accepts
|
:return: price rounded up to the precision the Exchange accepts
|
||||||
"""
|
"""
|
||||||
if price_precision is not None and precisionMode is not None:
|
if price_precision is not None and precisionMode is not None:
|
||||||
|
if rounding_mode not in (ROUND_UP, ROUND_DOWN):
|
||||||
|
# Use CCXT code where possible.
|
||||||
|
return float(decimal_to_precision(price, rounding_mode=rounding_mode,
|
||||||
|
precision=price_precision,
|
||||||
|
counting_mode=precisionMode
|
||||||
|
))
|
||||||
|
|
||||||
if precisionMode == TICK_SIZE:
|
if precisionMode == TICK_SIZE:
|
||||||
if rounding_mode == ROUND:
|
|
||||||
ticks = price / price_precision
|
|
||||||
rounded_ticks = round(ticks)
|
|
||||||
return rounded_ticks * price_precision
|
|
||||||
precision = FtPrecise(price_precision)
|
precision = FtPrecise(price_precision)
|
||||||
price_str = FtPrecise(price)
|
price_str = FtPrecise(price)
|
||||||
missing = price_str % precision
|
missing = price_str % precision
|
||||||
if not missing == FtPrecise("0"):
|
if not missing == FtPrecise("0"):
|
||||||
return round(float(str(price_str - missing + precision)), 14)
|
if rounding_mode == ROUND_UP:
|
||||||
|
res = price_str - missing + precision
|
||||||
|
elif rounding_mode == ROUND_DOWN:
|
||||||
|
res = price_str - missing
|
||||||
|
return round(float(str(res)), 14)
|
||||||
return price
|
return price
|
||||||
elif precisionMode in (SIGNIFICANT_DIGITS, DECIMAL_PLACES):
|
elif precisionMode == DECIMAL_PLACES:
|
||||||
|
|
||||||
ndigits = round(price_precision)
|
ndigits = round(price_precision)
|
||||||
if rounding_mode == ROUND:
|
|
||||||
return round(price, ndigits)
|
|
||||||
ticks = price * (10**ndigits)
|
ticks = price * (10**ndigits)
|
||||||
if rounding_mode == ROUND_UP:
|
if rounding_mode == ROUND_UP:
|
||||||
return ceil(ticks) / (10**ndigits)
|
return ceil(ticks) / (10**ndigits)
|
||||||
if rounding_mode == TRUNCATE:
|
|
||||||
return int(ticks) / (10**ndigits)
|
|
||||||
if rounding_mode == ROUND_DOWN:
|
if rounding_mode == ROUND_DOWN:
|
||||||
return floor(ticks) / (10**ndigits)
|
return floor(ticks) / (10**ndigits)
|
||||||
|
|
||||||
raise ValueError(f"Unknown rounding_mode {rounding_mode}")
|
raise ValueError(f"Unknown rounding_mode {rounding_mode}")
|
||||||
|
elif precisionMode == SIGNIFICANT_DIGITS:
|
||||||
|
if rounding_mode in (ROUND_UP, ROUND_DOWN):
|
||||||
|
return __price_to_precision_significant_digits(
|
||||||
|
price, price_precision, rounding_mode=rounding_mode
|
||||||
|
)
|
||||||
|
|
||||||
raise ValueError(f"Unknown precisionMode {precisionMode}")
|
raise ValueError(f"Unknown precisionMode {precisionMode}")
|
||||||
return price
|
return price
|
||||||
|
|||||||
@@ -25,8 +25,10 @@ class Gate(Exchange):
|
|||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"ohlcv_candle_limit": 1000,
|
"ohlcv_candle_limit": 1000,
|
||||||
"order_time_in_force": ['GTC', 'IOC'],
|
"order_time_in_force": ['GTC', 'IOC'],
|
||||||
"stoploss_order_types": {"limit": "limit"},
|
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
|
"stoploss_order_types": {"limit": "limit"},
|
||||||
|
"stop_price_param": "stopPrice",
|
||||||
|
"stop_price_prop": "stopPrice",
|
||||||
"marketOrderRequiresPrice": True,
|
"marketOrderRequiresPrice": True,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ class Huobi(Exchange):
|
|||||||
|
|
||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
|
"stop_price_param": "stopPrice",
|
||||||
|
"stop_price_prop": "stopPrice",
|
||||||
"stoploss_order_types": {"limit": "stop-limit"},
|
"stoploss_order_types": {"limit": "stop-limit"},
|
||||||
"ohlcv_candle_limit": 1000,
|
"ohlcv_candle_limit": 1000,
|
||||||
"l2_limit_range": [5, 10, 20],
|
"l2_limit_range": [5, 10, 20],
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ class Kraken(Exchange):
|
|||||||
_params: Dict = {"trading_agreement": "agree"}
|
_params: Dict = {"trading_agreement": "agree"}
|
||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
|
"stop_price_param": "stopPrice",
|
||||||
|
"stop_price_prop": "stopPrice",
|
||||||
"ohlcv_candle_limit": 720,
|
"ohlcv_candle_limit": 720,
|
||||||
"ohlcv_has_history": False,
|
"ohlcv_has_history": False,
|
||||||
"trades_pagination": "id",
|
"trades_pagination": "id",
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ class Kucoin(Exchange):
|
|||||||
|
|
||||||
_ft_has: Dict = {
|
_ft_has: Dict = {
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
|
"stop_price_param": "stopPrice",
|
||||||
|
"stop_price_prop": "stopPrice",
|
||||||
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
"stoploss_order_types": {"limit": "limit", "market": "market"},
|
||||||
"l2_limit_range": [20, 100],
|
"l2_limit_range": [20, 100],
|
||||||
"l2_limit_range_required": False,
|
"l2_limit_range_required": False,
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
import logging
|
import logging
|
||||||
|
from datetime import timedelta
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import ccxt
|
import ccxt
|
||||||
|
|
||||||
from freqtrade.constants import BuySell
|
from freqtrade.constants import BuySell
|
||||||
from freqtrade.enums import CandleType, MarginMode, TradingMode
|
from freqtrade.enums import CandleType, MarginMode, PriceType, TradingMode
|
||||||
from freqtrade.enums.pricetype import PriceType
|
|
||||||
from freqtrade.exceptions import (DDosProtection, OperationalException, RetryableOrderError,
|
from freqtrade.exceptions import (DDosProtection, OperationalException, RetryableOrderError,
|
||||||
TemporaryError)
|
TemporaryError)
|
||||||
from freqtrade.exchange import Exchange, date_minus_candles
|
from freqtrade.exchange import Exchange, date_minus_candles
|
||||||
from freqtrade.exchange.common import retrier
|
from freqtrade.exchange.common import retrier
|
||||||
from freqtrade.misc import safe_value_fallback2
|
from freqtrade.misc import safe_value_fallback2
|
||||||
|
from freqtrade.util import dt_now, dt_ts
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -28,7 +29,6 @@ class Okx(Exchange):
|
|||||||
"funding_fee_timeframe": "8h",
|
"funding_fee_timeframe": "8h",
|
||||||
"stoploss_order_types": {"limit": "limit"},
|
"stoploss_order_types": {"limit": "limit"},
|
||||||
"stoploss_on_exchange": True,
|
"stoploss_on_exchange": True,
|
||||||
"stop_price_param": "stopLossPrice",
|
|
||||||
}
|
}
|
||||||
_ft_has_futures: Dict = {
|
_ft_has_futures: Dict = {
|
||||||
"tickers_have_quoteVolume": False,
|
"tickers_have_quoteVolume": False,
|
||||||
@@ -187,7 +187,7 @@ class Okx(Exchange):
|
|||||||
|
|
||||||
def _convert_stop_order(self, pair: str, order_id: str, order: Dict) -> Dict:
|
def _convert_stop_order(self, pair: str, order_id: str, order: Dict) -> Dict:
|
||||||
if (
|
if (
|
||||||
order['status'] == 'closed'
|
order.get('status', 'open') == 'closed'
|
||||||
and (real_order_id := order.get('info', {}).get('ordId')) is not None
|
and (real_order_id := order.get('info', {}).get('ordId')) is not None
|
||||||
):
|
):
|
||||||
# Once a order triggered, we fetch the regular followup order.
|
# Once a order triggered, we fetch the regular followup order.
|
||||||
@@ -241,3 +241,18 @@ class Okx(Exchange):
|
|||||||
pair=pair,
|
pair=pair,
|
||||||
params=params1,
|
params=params1,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _fetch_orders_emulate(self, pair: str, since_ms: int) -> List[Dict]:
|
||||||
|
orders = []
|
||||||
|
|
||||||
|
orders = self._api.fetch_closed_orders(pair, since=since_ms)
|
||||||
|
if (since_ms < dt_ts(dt_now() - timedelta(days=6, hours=23))):
|
||||||
|
# Regular fetch_closed_orders only returns 7 days of data.
|
||||||
|
# Force usage of "archive" endpoint, which returns 3 months of data.
|
||||||
|
params = {'method': 'privateGetTradeOrdersHistoryArchive'}
|
||||||
|
orders_hist = self._api.fetch_closed_orders(pair, since=since_ms, params=params)
|
||||||
|
orders.extend(orders_hist)
|
||||||
|
|
||||||
|
orders_open = self._api.fetch_open_orders(pair, since=since_ms)
|
||||||
|
orders.extend(orders_open)
|
||||||
|
return orders
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ logger = logging.getLogger(__name__)
|
|||||||
torch.multiprocessing.set_sharing_strategy('file_system')
|
torch.multiprocessing.set_sharing_strategy('file_system')
|
||||||
|
|
||||||
SB3_MODELS = ['PPO', 'A2C', 'DQN']
|
SB3_MODELS = ['PPO', 'A2C', 'DQN']
|
||||||
SB3_CONTRIB_MODELS = ['TRPO', 'ARS', 'RecurrentPPO', 'MaskablePPO']
|
SB3_CONTRIB_MODELS = ['TRPO', 'ARS', 'RecurrentPPO', 'MaskablePPO', 'QRDQN']
|
||||||
|
|
||||||
|
|
||||||
class BaseReinforcementLearningModel(IFreqaiModel):
|
class BaseReinforcementLearningModel(IFreqaiModel):
|
||||||
|
|||||||
@@ -263,23 +263,46 @@ class FreqaiDataDrawer:
|
|||||||
self.pair_dict[metadata["pair"]] = self.empty_pair_dict.copy()
|
self.pair_dict[metadata["pair"]] = self.empty_pair_dict.copy()
|
||||||
return
|
return
|
||||||
|
|
||||||
def set_initial_return_values(self, pair: str, pred_df: DataFrame) -> None:
|
def set_initial_return_values(self, pair: str,
|
||||||
|
pred_df: DataFrame,
|
||||||
|
dataframe: DataFrame
|
||||||
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Set the initial return values to the historical predictions dataframe. This avoids needing
|
Set the initial return values to the historical predictions dataframe. This avoids needing
|
||||||
to repredict on historical candles, and also stores historical predictions despite
|
to repredict on historical candles, and also stores historical predictions despite
|
||||||
retrainings (so stored predictions are true predictions, not just inferencing on trained
|
retrainings (so stored predictions are true predictions, not just inferencing on trained
|
||||||
data)
|
data).
|
||||||
|
|
||||||
|
We also aim to keep the date from historical predictions so that the FreqUI displays
|
||||||
|
zeros during any downtime (between FreqAI reloads).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
hist_df = self.historic_predictions
|
new_pred = pred_df.copy()
|
||||||
len_diff = len(hist_df[pair].index) - len(pred_df.index)
|
# set new_pred values to nans (we want to signal to user that there was nothing
|
||||||
if len_diff < 0:
|
# historically made during downtime. The newest pred will get appeneded later in
|
||||||
df_concat = pd.concat([pred_df.iloc[:abs(len_diff)], hist_df[pair]],
|
# append_model_predictions)
|
||||||
ignore_index=True, keys=hist_df[pair].keys())
|
new_pred.iloc[:, :] = np.nan
|
||||||
|
new_pred["date_pred"] = dataframe["date"]
|
||||||
|
hist_preds = self.historic_predictions[pair].copy()
|
||||||
|
|
||||||
|
# find the closest common date between new_pred and historic predictions
|
||||||
|
# and cut off the new_pred dataframe at that date
|
||||||
|
common_dates = pd.merge(new_pred, hist_preds, on="date_pred", how="inner")
|
||||||
|
if len(common_dates.index) > 0:
|
||||||
|
new_pred = new_pred.iloc[len(common_dates):]
|
||||||
else:
|
else:
|
||||||
df_concat = hist_df[pair].tail(len(pred_df.index)).reset_index(drop=True)
|
logger.warning("No common dates found between new predictions and historic "
|
||||||
|
"predictions. You likely left your FreqAI instance offline "
|
||||||
|
f"for more than {len(dataframe.index)} candles.")
|
||||||
|
|
||||||
|
df_concat = pd.concat([hist_preds, new_pred], ignore_index=True, keys=hist_preds.keys())
|
||||||
|
# remove last row because we will append that later in append_model_predictions()
|
||||||
|
df_concat = df_concat.iloc[:-1]
|
||||||
|
# any missing values will get zeroed out so users can see the exact
|
||||||
|
# downtime in FreqUI
|
||||||
df_concat = df_concat.fillna(0)
|
df_concat = df_concat.fillna(0)
|
||||||
self.model_return_values[pair] = df_concat
|
self.historic_predictions[pair] = df_concat
|
||||||
|
self.model_return_values[pair] = df_concat.tail(len(dataframe.index)).reset_index(drop=True)
|
||||||
|
|
||||||
def append_model_predictions(self, pair: str, predictions: DataFrame,
|
def append_model_predictions(self, pair: str, predictions: DataFrame,
|
||||||
do_preds: NDArray[np.int_],
|
do_preds: NDArray[np.int_],
|
||||||
|
|||||||
@@ -244,6 +244,14 @@ class FreqaiDataKitchen:
|
|||||||
f"{self.pair}: dropped {len(unfiltered_df) - len(filtered_df)} training points"
|
f"{self.pair}: dropped {len(unfiltered_df) - len(filtered_df)} training points"
|
||||||
f" due to NaNs in populated dataset {len(unfiltered_df)}."
|
f" due to NaNs in populated dataset {len(unfiltered_df)}."
|
||||||
)
|
)
|
||||||
|
if len(unfiltered_df) == 0 and not self.live:
|
||||||
|
raise OperationalException(
|
||||||
|
f"{self.pair}: all training data dropped due to NaNs. "
|
||||||
|
"You likely did not download enough training data prior "
|
||||||
|
"to your backtest timerange. Hint:\n"
|
||||||
|
f"{DOCS_LINK}/freqai-running/"
|
||||||
|
"#downloading-data-to-cover-the-full-backtest-period"
|
||||||
|
)
|
||||||
if (1 - len(filtered_df) / len(unfiltered_df)) > 0.1 and self.live:
|
if (1 - len(filtered_df) / len(unfiltered_df)) > 0.1 and self.live:
|
||||||
worst_indicator = str(unfiltered_df.count().idxmin())
|
worst_indicator = str(unfiltered_df.count().idxmin())
|
||||||
logger.warning(
|
logger.warning(
|
||||||
|
|||||||
@@ -138,7 +138,6 @@ class IFreqaiModel(ABC):
|
|||||||
:param metadata: pair metadata coming from strategy.
|
:param metadata: pair metadata coming from strategy.
|
||||||
:param strategy: Strategy to train on
|
:param strategy: Strategy to train on
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self.live = strategy.dp.runmode in (RunMode.DRY_RUN, RunMode.LIVE)
|
self.live = strategy.dp.runmode in (RunMode.DRY_RUN, RunMode.LIVE)
|
||||||
self.dd.set_pair_dict_info(metadata)
|
self.dd.set_pair_dict_info(metadata)
|
||||||
self.data_provider = strategy.dp
|
self.data_provider = strategy.dp
|
||||||
@@ -394,6 +393,11 @@ class IFreqaiModel(ABC):
|
|||||||
dk: FreqaiDataKitchen = Data management/analysis tool associated to present pair only
|
dk: FreqaiDataKitchen = Data management/analysis tool associated to present pair only
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if not strategy.process_only_new_candles:
|
||||||
|
raise OperationalException("You are trying to use a FreqAI strategy with "
|
||||||
|
"process_only_new_candles = False. This is not supported "
|
||||||
|
"by FreqAI, and it is therefore aborting.")
|
||||||
|
|
||||||
# get the model metadata associated with the current pair
|
# get the model metadata associated with the current pair
|
||||||
(_, trained_timestamp) = self.dd.get_pair_dict_info(metadata["pair"])
|
(_, trained_timestamp) = self.dd.get_pair_dict_info(metadata["pair"])
|
||||||
|
|
||||||
@@ -453,7 +457,7 @@ class IFreqaiModel(ABC):
|
|||||||
pred_df, do_preds = self.predict(dataframe, dk)
|
pred_df, do_preds = self.predict(dataframe, dk)
|
||||||
if pair not in self.dd.historic_predictions:
|
if pair not in self.dd.historic_predictions:
|
||||||
self.set_initial_historic_predictions(pred_df, dk, pair, dataframe)
|
self.set_initial_historic_predictions(pred_df, dk, pair, dataframe)
|
||||||
self.dd.set_initial_return_values(pair, pred_df)
|
self.dd.set_initial_return_values(pair, pred_df, dataframe)
|
||||||
|
|
||||||
dk.return_dataframe = self.dd.attach_return_values_to_return_dataframe(pair, dataframe)
|
dk.return_dataframe = self.dd.attach_return_values_to_return_dataframe(pair, dataframe)
|
||||||
return
|
return
|
||||||
@@ -645,11 +649,11 @@ class IFreqaiModel(ABC):
|
|||||||
If the user reuses an identifier on a subsequent instance,
|
If the user reuses an identifier on a subsequent instance,
|
||||||
this function will not be called. In that case, "real" predictions
|
this function will not be called. In that case, "real" predictions
|
||||||
will be appended to the loaded set of historic predictions.
|
will be appended to the loaded set of historic predictions.
|
||||||
:param df: DataFrame = the dataframe containing the training feature data
|
:param pred_df: DataFrame = the dataframe containing the predictions coming
|
||||||
:param model: Any = A model which was `fit` using a common library such as
|
out of a model
|
||||||
catboost or lightgbm
|
|
||||||
:param dk: FreqaiDataKitchen = object containing methods for data analysis
|
:param dk: FreqaiDataKitchen = object containing methods for data analysis
|
||||||
:param pair: str = current pair
|
:param pair: str = current pair
|
||||||
|
:param strat_df: DataFrame = dataframe coming from strategy
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self.dd.historic_predictions[pair] = pred_df
|
self.dd.historic_predictions[pair] = pred_df
|
||||||
|
|||||||
+210
-149
@@ -7,13 +7,14 @@ from copy import deepcopy
|
|||||||
from datetime import datetime, time, timedelta, timezone
|
from datetime import datetime, time, timedelta, timezone
|
||||||
from math import isclose
|
from math import isclose
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
|
from time import sleep
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
from schedule import Scheduler
|
from schedule import Scheduler
|
||||||
|
|
||||||
from freqtrade import constants
|
from freqtrade import constants
|
||||||
from freqtrade.configuration import validate_config_consistency
|
from freqtrade.configuration import validate_config_consistency
|
||||||
from freqtrade.constants import BuySell, Config, ExchangeConfig, LongShort
|
from freqtrade.constants import BuySell, Config, EntryExecuteMode, ExchangeConfig, LongShort
|
||||||
from freqtrade.data.converter import order_book_to_dataframe
|
from freqtrade.data.converter import order_book_to_dataframe
|
||||||
from freqtrade.data.dataprovider import DataProvider
|
from freqtrade.data.dataprovider import DataProvider
|
||||||
from freqtrade.edge import Edge
|
from freqtrade.edge import Edge
|
||||||
@@ -21,9 +22,8 @@ from freqtrade.enums import (ExitCheckTuple, ExitType, RPCMessageType, RunMode,
|
|||||||
State, TradingMode)
|
State, TradingMode)
|
||||||
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
|
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
|
||||||
InvalidOrderException, PricingError)
|
InvalidOrderException, PricingError)
|
||||||
from freqtrade.exchange import (ROUND_DOWN, ROUND_UP, timeframe_to_minutes, timeframe_to_next_date,
|
from freqtrade.exchange import (ROUND_DOWN, ROUND_UP, remove_exchange_credentials,
|
||||||
timeframe_to_seconds)
|
timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds)
|
||||||
from freqtrade.exchange.common import remove_exchange_credentials
|
|
||||||
from freqtrade.misc import safe_value_fallback, safe_value_fallback2
|
from freqtrade.misc import safe_value_fallback, safe_value_fallback2
|
||||||
from freqtrade.mixins import LoggingMixin
|
from freqtrade.mixins import LoggingMixin
|
||||||
from freqtrade.persistence import Order, PairLocks, Trade, init_db
|
from freqtrade.persistence import Order, PairLocks, Trade, init_db
|
||||||
@@ -373,7 +373,10 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
"Order is older than 5 days. Assuming order was fully cancelled.")
|
"Order is older than 5 days. Assuming order was fully cancelled.")
|
||||||
fo = order.to_ccxt_object()
|
fo = order.to_ccxt_object()
|
||||||
fo['status'] = 'canceled'
|
fo['status'] = 'canceled'
|
||||||
self.handle_cancel_order(fo, order.trade, constants.CANCEL_REASON['TIMEOUT'])
|
self.handle_cancel_order(
|
||||||
|
fo, order.order_id, order.trade,
|
||||||
|
constants.CANCEL_REASON['TIMEOUT']
|
||||||
|
)
|
||||||
|
|
||||||
except ExchangeError as e:
|
except ExchangeError as e:
|
||||||
|
|
||||||
@@ -440,13 +443,6 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
if fo and fo['status'] == 'open':
|
if fo and fo['status'] == 'open':
|
||||||
# Assume this as the open stoploss order
|
# Assume this as the open stoploss order
|
||||||
trade.stoploss_order_id = order.order_id
|
trade.stoploss_order_id = order.order_id
|
||||||
elif order.ft_order_side == trade.exit_side:
|
|
||||||
if fo and fo['status'] == 'open':
|
|
||||||
# Assume this as the open order
|
|
||||||
trade.open_order_id = order.order_id
|
|
||||||
elif order.ft_order_side == trade.entry_side:
|
|
||||||
if fo and fo['status'] == 'open':
|
|
||||||
trade.open_order_id = order.order_id
|
|
||||||
if fo:
|
if fo:
|
||||||
logger.info(f"Found {order} for trade {trade}.")
|
logger.info(f"Found {order} for trade {trade}.")
|
||||||
self.update_trade_state(trade, order.order_id, fo,
|
self.update_trade_state(trade, order.order_id, fo,
|
||||||
@@ -461,36 +457,48 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
Only used balance disappeared, which would make exiting impossible.
|
Only used balance disappeared, which would make exiting impossible.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
orders = self.exchange.fetch_orders(trade.pair, trade.open_date_utc)
|
orders = self.exchange.fetch_orders(
|
||||||
|
trade.pair, trade.open_date_utc - timedelta(seconds=10))
|
||||||
|
prev_exit_reason = trade.exit_reason
|
||||||
|
prev_trade_state = trade.is_open
|
||||||
for order in orders:
|
for order in orders:
|
||||||
trade_order = [o for o in trade.orders if o.order_id == order['id']]
|
trade_order = [o for o in trade.orders if o.order_id == order['id']]
|
||||||
if trade_order:
|
|
||||||
continue
|
|
||||||
logger.info(f"Found previously unknown order {order['id']} for {trade.pair}.")
|
|
||||||
|
|
||||||
order_obj = Order.parse_from_ccxt_object(order, trade.pair, order['side'])
|
if trade_order:
|
||||||
order_obj.order_filled_date = datetime.fromtimestamp(
|
# We knew this order, but didn't have it updated properly
|
||||||
safe_value_fallback(order, 'lastTradeTimestamp', 'timestamp') // 1000,
|
order_obj = trade_order[0]
|
||||||
tz=timezone.utc)
|
else:
|
||||||
trade.orders.append(order_obj)
|
logger.info(f"Found previously unknown order {order['id']} for {trade.pair}.")
|
||||||
# TODO: how do we handle open_order_id ...
|
|
||||||
Trade.commit()
|
order_obj = Order.parse_from_ccxt_object(order, trade.pair, order['side'])
|
||||||
prev_exit_reason = trade.exit_reason
|
order_obj.order_filled_date = datetime.fromtimestamp(
|
||||||
trade.exit_reason = ExitType.SOLD_ON_EXCHANGE.value
|
safe_value_fallback(order, 'lastTradeTimestamp', 'timestamp') // 1000,
|
||||||
self.update_trade_state(trade, order['id'], order)
|
tz=timezone.utc)
|
||||||
|
trade.orders.append(order_obj)
|
||||||
|
Trade.commit()
|
||||||
|
trade.exit_reason = ExitType.SOLD_ON_EXCHANGE.value
|
||||||
|
|
||||||
|
self.update_trade_state(trade, order['id'], order, send_msg=False)
|
||||||
|
|
||||||
logger.info(f"handled order {order['id']}")
|
logger.info(f"handled order {order['id']}")
|
||||||
if not trade.is_open:
|
|
||||||
# Trade was just closed
|
# Refresh trade from database
|
||||||
trade.close_date = order_obj.order_filled_date
|
Trade.session.refresh(trade)
|
||||||
Trade.commit()
|
if not trade.is_open:
|
||||||
break
|
# Trade was just closed
|
||||||
else:
|
trade.close_date = trade.date_last_filled_utc
|
||||||
trade.exit_reason = prev_exit_reason
|
self.order_close_notify(trade, order_obj,
|
||||||
Trade.commit()
|
order_obj.ft_order_side == 'stoploss',
|
||||||
|
send_msg=prev_trade_state != trade.is_open)
|
||||||
|
else:
|
||||||
|
trade.exit_reason = prev_exit_reason
|
||||||
|
Trade.commit()
|
||||||
|
|
||||||
except ExchangeError:
|
except ExchangeError:
|
||||||
logger.warning("Error finding onexchange order")
|
logger.warning("Error finding onexchange order.")
|
||||||
|
except Exception:
|
||||||
|
# catching https://github.com/freqtrade/freqtrade/issues/9025
|
||||||
|
logger.warning("Error finding onexchange order", exc_info=True)
|
||||||
#
|
#
|
||||||
# BUY / enter positions / open trades logic and methods
|
# BUY / enter positions / open trades logic and methods
|
||||||
#
|
#
|
||||||
@@ -612,7 +620,8 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# Walk through each pair and check if it needs changes
|
# Walk through each pair and check if it needs changes
|
||||||
for trade in Trade.get_open_trades():
|
for trade in Trade.get_open_trades():
|
||||||
# If there is any open orders, wait for them to finish.
|
# If there is any open orders, wait for them to finish.
|
||||||
if trade.open_order_id is None:
|
# TODO Remove to allow mul open orders
|
||||||
|
if not trade.has_open_orders:
|
||||||
# Do a wallets update (will be ratelimited to once per hour)
|
# Do a wallets update (will be ratelimited to once per hour)
|
||||||
self.wallets.update(False)
|
self.wallets.update(False)
|
||||||
try:
|
try:
|
||||||
@@ -662,7 +671,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
else:
|
else:
|
||||||
logger.debug("Max adjustment entries is set to unlimited.")
|
logger.debug("Max adjustment entries is set to unlimited.")
|
||||||
self.execute_entry(trade.pair, stake_amount, price=current_entry_rate,
|
self.execute_entry(trade.pair, stake_amount, price=current_entry_rate,
|
||||||
trade=trade, is_short=trade.is_short)
|
trade=trade, is_short=trade.is_short, mode='pos_adjust')
|
||||||
|
|
||||||
if stake_amount is not None and stake_amount < 0.0:
|
if stake_amount is not None and stake_amount < 0.0:
|
||||||
# We should decrease our position
|
# We should decrease our position
|
||||||
@@ -732,7 +741,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
ordertype: Optional[str] = None,
|
ordertype: Optional[str] = None,
|
||||||
enter_tag: Optional[str] = None,
|
enter_tag: Optional[str] = None,
|
||||||
trade: Optional[Trade] = None,
|
trade: Optional[Trade] = None,
|
||||||
order_adjust: bool = False,
|
mode: EntryExecuteMode = 'initial',
|
||||||
leverage_: Optional[float] = None,
|
leverage_: Optional[float] = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
@@ -749,22 +758,25 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
pos_adjust = trade is not None
|
pos_adjust = trade is not None
|
||||||
|
|
||||||
enter_limit_requested, stake_amount, leverage = self.get_valid_enter_price_and_stake(
|
enter_limit_requested, stake_amount, leverage = self.get_valid_enter_price_and_stake(
|
||||||
pair, price, stake_amount, trade_side, enter_tag, trade, order_adjust, leverage_,
|
pair, price, stake_amount, trade_side, enter_tag, trade, mode, leverage_)
|
||||||
pos_adjust)
|
|
||||||
|
|
||||||
if not stake_amount:
|
if not stake_amount:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
msg = (f"Position adjust: about to create a new order for {pair} with stake: "
|
msg = (f"Position adjust: about to create a new order for {pair} with stake_amount: "
|
||||||
f"{stake_amount} for {trade}" if pos_adjust
|
f"{stake_amount} for {trade}" if mode == 'pos_adjust'
|
||||||
else
|
else
|
||||||
f"{name} signal found: about create a new trade for {pair} with stake_amount: "
|
(f"Replacing {side} order: about create a new order for {pair} with stake_amount: "
|
||||||
f"{stake_amount} ...")
|
f"{stake_amount} ..."
|
||||||
|
if mode == 'replace' else
|
||||||
|
f"{name} signal found: about create a new trade for {pair} with stake_amount: "
|
||||||
|
f"{stake_amount} ..."
|
||||||
|
))
|
||||||
logger.info(msg)
|
logger.info(msg)
|
||||||
amount = (stake_amount / enter_limit_requested) * leverage
|
amount = (stake_amount / enter_limit_requested) * leverage
|
||||||
order_type = ordertype or self.strategy.order_types['entry']
|
order_type = ordertype or self.strategy.order_types['entry']
|
||||||
|
|
||||||
if not pos_adjust and not strategy_safe_wrapper(
|
if mode == 'initial' and not strategy_safe_wrapper(
|
||||||
self.strategy.confirm_trade_entry, default_retval=True)(
|
self.strategy.confirm_trade_entry, default_retval=True)(
|
||||||
pair=pair, order_type=order_type, amount=amount, rate=enter_limit_requested,
|
pair=pair, order_type=order_type, amount=amount, rate=enter_limit_requested,
|
||||||
time_in_force=time_in_force, current_time=datetime.now(timezone.utc),
|
time_in_force=time_in_force, current_time=datetime.now(timezone.utc),
|
||||||
@@ -784,7 +796,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
order_obj = Order.parse_from_ccxt_object(order, pair, side, amount, enter_limit_requested)
|
order_obj = Order.parse_from_ccxt_object(order, pair, side, amount, enter_limit_requested)
|
||||||
order_id = order['id']
|
order_id = order['id']
|
||||||
order_status = order.get('status')
|
order_status = order.get('status')
|
||||||
logger.info(f"Order #{order_id} was created for {pair} and status is {order_status}.")
|
logger.info(f"Order {order_id} was created for {pair} and status is {order_status}.")
|
||||||
|
|
||||||
# we assume the order is executed at the price requested
|
# we assume the order is executed at the price requested
|
||||||
enter_limit_filled_price = enter_limit_requested
|
enter_limit_filled_price = enter_limit_requested
|
||||||
@@ -846,7 +858,6 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
open_rate_requested=enter_limit_requested,
|
open_rate_requested=enter_limit_requested,
|
||||||
open_date=open_date,
|
open_date=open_date,
|
||||||
exchange=self.exchange.id,
|
exchange=self.exchange.id,
|
||||||
open_order_id=order_id,
|
|
||||||
strategy=self.strategy.get_strategy_name(),
|
strategy=self.strategy.get_strategy_name(),
|
||||||
enter_tag=enter_tag,
|
enter_tag=enter_tag,
|
||||||
timeframe=timeframe_to_minutes(self.config['timeframe']),
|
timeframe=timeframe_to_minutes(self.config['timeframe']),
|
||||||
@@ -867,7 +878,6 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trade.is_open = True
|
trade.is_open = True
|
||||||
trade.fee_open_currency = None
|
trade.fee_open_currency = None
|
||||||
trade.open_rate_requested = enter_limit_requested
|
trade.open_rate_requested = enter_limit_requested
|
||||||
trade.open_order_id = order_id
|
|
||||||
|
|
||||||
trade.orders.append(order_obj)
|
trade.orders.append(order_obj)
|
||||||
trade.recalc_trade_from_orders()
|
trade.recalc_trade_from_orders()
|
||||||
@@ -913,9 +923,8 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trade_side: LongShort,
|
trade_side: LongShort,
|
||||||
entry_tag: Optional[str],
|
entry_tag: Optional[str],
|
||||||
trade: Optional[Trade],
|
trade: Optional[Trade],
|
||||||
order_adjust: bool,
|
mode: EntryExecuteMode,
|
||||||
leverage_: Optional[float],
|
leverage_: Optional[float],
|
||||||
pos_adjust: bool,
|
|
||||||
) -> Tuple[float, float, float]:
|
) -> Tuple[float, float, float]:
|
||||||
"""
|
"""
|
||||||
Validate and eventually adjust (within limits) limit, amount and leverage
|
Validate and eventually adjust (within limits) limit, amount and leverage
|
||||||
@@ -928,11 +937,12 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# Calculate price
|
# Calculate price
|
||||||
enter_limit_requested = self.exchange.get_rate(
|
enter_limit_requested = self.exchange.get_rate(
|
||||||
pair, side='entry', is_short=(trade_side == 'short'), refresh=True)
|
pair, side='entry', is_short=(trade_side == 'short'), refresh=True)
|
||||||
if not order_adjust:
|
if mode != 'replace':
|
||||||
# Don't call custom_entry_price in order-adjust scenario
|
# Don't call custom_entry_price in order-adjust scenario
|
||||||
custom_entry_price = strategy_safe_wrapper(self.strategy.custom_entry_price,
|
custom_entry_price = strategy_safe_wrapper(self.strategy.custom_entry_price,
|
||||||
default_retval=enter_limit_requested)(
|
default_retval=enter_limit_requested)(
|
||||||
pair=pair, current_time=datetime.now(timezone.utc),
|
pair=pair, trade=trade,
|
||||||
|
current_time=datetime.now(timezone.utc),
|
||||||
proposed_rate=enter_limit_requested, entry_tag=entry_tag,
|
proposed_rate=enter_limit_requested, entry_tag=entry_tag,
|
||||||
side=trade_side,
|
side=trade_side,
|
||||||
)
|
)
|
||||||
@@ -967,7 +977,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# edge-case for now.
|
# edge-case for now.
|
||||||
min_stake_amount = self.exchange.get_min_pair_stake_amount(
|
min_stake_amount = self.exchange.get_min_pair_stake_amount(
|
||||||
pair, enter_limit_requested,
|
pair, enter_limit_requested,
|
||||||
self.strategy.stoploss if not pos_adjust else 0.0,
|
self.strategy.stoploss if not mode != 'pos_adjust' else 0.0,
|
||||||
leverage)
|
leverage)
|
||||||
max_stake_amount = self.exchange.get_max_pair_stake_amount(
|
max_stake_amount = self.exchange.get_max_pair_stake_amount(
|
||||||
pair, enter_limit_requested, leverage)
|
pair, enter_limit_requested, leverage)
|
||||||
@@ -1077,7 +1087,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trades_closed = 0
|
trades_closed = 0
|
||||||
for trade in trades:
|
for trade in trades:
|
||||||
|
|
||||||
if trade.open_order_id is None and not self.wallets.check_exit_amount(trade):
|
if not trade.has_open_orders and not self.wallets.check_exit_amount(trade):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'Not enough {trade.safe_base_currency} in wallet to exit {trade}. '
|
f'Not enough {trade.safe_base_currency} in wallet to exit {trade}. '
|
||||||
'Trying to recover.')
|
'Trying to recover.')
|
||||||
@@ -1095,7 +1105,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
logger.warning(
|
logger.warning(
|
||||||
f'Unable to handle stoploss on exchange for {trade.pair}: {exception}')
|
f'Unable to handle stoploss on exchange for {trade.pair}: {exception}')
|
||||||
# Check if we can sell our current pair
|
# Check if we can sell our current pair
|
||||||
if trade.open_order_id is None and trade.is_open and self.handle_trade(trade):
|
if not trade.has_open_orders and trade.is_open and self.handle_trade(trade):
|
||||||
trades_closed += 1
|
trades_closed += 1
|
||||||
|
|
||||||
except DependencyException as exception:
|
except DependencyException as exception:
|
||||||
@@ -1214,7 +1224,6 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
logger.debug('Handling stoploss on exchange %s ...', trade)
|
logger.debug('Handling stoploss on exchange %s ...', trade)
|
||||||
|
|
||||||
stoploss_order = None
|
stoploss_order = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -1237,7 +1246,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
self.handle_protections(trade.pair, trade.trade_direction)
|
self.handle_protections(trade.pair, trade.trade_direction)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
if trade.open_order_id or not trade.is_open:
|
if trade.has_open_orders or not trade.is_open:
|
||||||
# Trade has an open Buy or Sell order, Stoploss-handling can't happen in this case
|
# Trade has an open Buy or Sell order, Stoploss-handling can't happen in this case
|
||||||
# as the Amount on the exchange is tied up in another trade.
|
# as the Amount on the exchange is tied up in another trade.
|
||||||
# The trade can be closed already (sell-order fill confirmation came in this iteration)
|
# The trade can be closed already (sell-order fill confirmation came in this iteration)
|
||||||
@@ -1321,27 +1330,33 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
Timeout setting takes priority over limit order adjustment request.
|
Timeout setting takes priority over limit order adjustment request.
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
for trade in Trade.get_open_order_trades():
|
for trade in Trade.get_open_trades():
|
||||||
try:
|
for open_order in trade.open_orders:
|
||||||
if not trade.open_order_id:
|
try:
|
||||||
|
order = self.exchange.fetch_order(open_order.order_id, trade.pair)
|
||||||
|
|
||||||
|
except (ExchangeError):
|
||||||
|
logger.info(
|
||||||
|
'Cannot query order for %s due to %s', trade, traceback.format_exc()
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
order = self.exchange.fetch_order(trade.open_order_id, trade.pair)
|
|
||||||
except (ExchangeError):
|
|
||||||
logger.info('Cannot query order for %s due to %s', trade, traceback.format_exc())
|
|
||||||
continue
|
|
||||||
|
|
||||||
fully_cancelled = self.update_trade_state(trade, trade.open_order_id, order)
|
fully_cancelled = self.update_trade_state(trade, open_order.order_id, order)
|
||||||
not_closed = order['status'] == 'open' or fully_cancelled
|
not_closed = order['status'] == 'open' or fully_cancelled
|
||||||
order_obj = trade.select_order_by_order_id(trade.open_order_id)
|
|
||||||
|
|
||||||
if not_closed:
|
if not_closed:
|
||||||
if fully_cancelled or (order_obj and self.strategy.ft_check_timed_out(
|
if fully_cancelled or (
|
||||||
trade, order_obj, datetime.now(timezone.utc))):
|
open_order and self.strategy.ft_check_timed_out(
|
||||||
self.handle_cancel_order(order, trade, constants.CANCEL_REASON['TIMEOUT'])
|
trade, open_order, datetime.now(timezone.utc)
|
||||||
else:
|
)
|
||||||
self.replace_order(order, order_obj, trade)
|
):
|
||||||
|
self.handle_cancel_order(
|
||||||
|
order, open_order.order_id, trade, constants.CANCEL_REASON['TIMEOUT']
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.replace_order(order, open_order, trade)
|
||||||
|
|
||||||
def handle_cancel_order(self, order: Dict, trade: Trade, reason: str) -> None:
|
def handle_cancel_order(self, order: Dict, order_id: str, trade: Trade, reason: str) -> None:
|
||||||
"""
|
"""
|
||||||
Check if current analyzed order timed out and cancel if necessary.
|
Check if current analyzed order timed out and cancel if necessary.
|
||||||
:param order: Order dict grabbed with exchange.fetch_order()
|
:param order: Order dict grabbed with exchange.fetch_order()
|
||||||
@@ -1349,25 +1364,44 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
if order['side'] == trade.entry_side:
|
if order['side'] == trade.entry_side:
|
||||||
self.handle_cancel_enter(trade, order, reason)
|
self.handle_cancel_enter(trade, order, order_id, reason)
|
||||||
else:
|
else:
|
||||||
canceled = self.handle_cancel_exit(trade, order, reason)
|
canceled = self.handle_cancel_exit(trade, order, order_id, reason)
|
||||||
canceled_count = trade.get_exit_order_count()
|
canceled_count = trade.get_canceled_exit_order_count()
|
||||||
max_timeouts = self.config.get('unfilledtimeout', {}).get('exit_timeout_count', 0)
|
max_timeouts = self.config.get('unfilledtimeout', {}).get('exit_timeout_count', 0)
|
||||||
if canceled and max_timeouts > 0 and canceled_count >= max_timeouts:
|
if (canceled and max_timeouts > 0 and canceled_count >= max_timeouts):
|
||||||
logger.warning(f'Emergency exiting trade {trade}, as the exit order '
|
logger.warning(f"Emergency exiting trade {trade}, as the exit order "
|
||||||
f'timed out {max_timeouts} times.')
|
f"timed out {max_timeouts} times. force selling {order['amount']}.")
|
||||||
self.emergency_exit(trade, order['price'])
|
self.emergency_exit(trade, order['price'], order['amount'])
|
||||||
|
|
||||||
def emergency_exit(self, trade: Trade, price: float) -> None:
|
def emergency_exit(
|
||||||
|
self, trade: Trade, price: float, sub_trade_amt: Optional[float] = None) -> None:
|
||||||
try:
|
try:
|
||||||
self.execute_trade_exit(
|
self.execute_trade_exit(
|
||||||
trade, price,
|
trade, price,
|
||||||
exit_check=ExitCheckTuple(exit_type=ExitType.EMERGENCY_EXIT))
|
exit_check=ExitCheckTuple(exit_type=ExitType.EMERGENCY_EXIT),
|
||||||
|
sub_trade_amt=sub_trade_amt
|
||||||
|
)
|
||||||
except DependencyException as exception:
|
except DependencyException as exception:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f'Unable to emergency exit trade {trade.pair}: {exception}')
|
f'Unable to emergency exit trade {trade.pair}: {exception}')
|
||||||
|
|
||||||
|
def replace_order_failed(self, trade: Trade, msg: str) -> None:
|
||||||
|
"""
|
||||||
|
Order replacement fail handling.
|
||||||
|
Deletes the trade if necessary.
|
||||||
|
:param trade: Trade object.
|
||||||
|
:param msg: Error message.
|
||||||
|
"""
|
||||||
|
logger.warning(msg)
|
||||||
|
if trade.nr_of_successful_entries == 0:
|
||||||
|
# this is the first entry and we didn't get filled yet, delete trade
|
||||||
|
logger.warning(f"Removing {trade} from database.")
|
||||||
|
self._notify_enter_cancel(
|
||||||
|
trade, order_type=self.strategy.order_types['entry'],
|
||||||
|
reason=constants.CANCEL_REASON['REPLACE_FAILED'])
|
||||||
|
trade.delete()
|
||||||
|
|
||||||
def replace_order(self, order: Dict, order_obj: Optional[Order], trade: Trade) -> None:
|
def replace_order(self, order: Dict, order_obj: Optional[Order], trade: Trade) -> None:
|
||||||
"""
|
"""
|
||||||
Check if current analyzed entry order should be replaced or simply cancelled.
|
Check if current analyzed entry order should be replaced or simply cancelled.
|
||||||
@@ -1406,19 +1440,24 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
cancel_reason = constants.CANCEL_REASON['USER_CANCEL']
|
cancel_reason = constants.CANCEL_REASON['USER_CANCEL']
|
||||||
if order_obj.price != adjusted_entry_price:
|
if order_obj.price != adjusted_entry_price:
|
||||||
# cancel existing order if new price is supplied or None
|
# cancel existing order if new price is supplied or None
|
||||||
self.handle_cancel_enter(trade, order, cancel_reason,
|
res = self.handle_cancel_enter(trade, order, order_obj.order_id, cancel_reason,
|
||||||
replacing=replacing)
|
replacing=replacing)
|
||||||
|
if not res:
|
||||||
|
self.replace_order_failed(
|
||||||
|
trade, f"Could not cancel order for {trade}, therefore not replacing.")
|
||||||
|
return
|
||||||
if adjusted_entry_price:
|
if adjusted_entry_price:
|
||||||
# place new order only if new price is supplied
|
# place new order only if new price is supplied
|
||||||
self.execute_entry(
|
if not self.execute_entry(
|
||||||
pair=trade.pair,
|
pair=trade.pair,
|
||||||
stake_amount=(
|
stake_amount=(
|
||||||
order_obj.safe_remaining * order_obj.safe_price / trade.leverage),
|
order_obj.safe_remaining * order_obj.safe_price / trade.leverage),
|
||||||
price=adjusted_entry_price,
|
price=adjusted_entry_price,
|
||||||
trade=trade,
|
trade=trade,
|
||||||
is_short=trade.is_short,
|
is_short=trade.is_short,
|
||||||
order_adjust=True,
|
mode='replace',
|
||||||
)
|
):
|
||||||
|
self.replace_order_failed(trade, f"Could not replace order for {trade}.")
|
||||||
|
|
||||||
def cancel_all_open_orders(self) -> None:
|
def cancel_all_open_orders(self) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -1426,25 +1465,28 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for trade in Trade.get_open_order_trades():
|
for trade in Trade.get_open_trades():
|
||||||
if not trade.open_order_id:
|
for open_order in trade.open_orders:
|
||||||
continue
|
try:
|
||||||
try:
|
order = self.exchange.fetch_order(open_order.order_id, trade.pair)
|
||||||
order = self.exchange.fetch_order(trade.open_order_id, trade.pair)
|
except (ExchangeError):
|
||||||
except (ExchangeError):
|
logger.info("Can't query order for %s due to %s", trade, traceback.format_exc())
|
||||||
logger.info('Cannot query order for %s due to %s', trade, traceback.format_exc())
|
continue
|
||||||
continue
|
|
||||||
|
|
||||||
if order['side'] == trade.entry_side:
|
if order['side'] == trade.entry_side:
|
||||||
self.handle_cancel_enter(trade, order, constants.CANCEL_REASON['ALL_CANCELLED'])
|
self.handle_cancel_enter(
|
||||||
|
trade, order, open_order.order_id, constants.CANCEL_REASON['ALL_CANCELLED']
|
||||||
|
)
|
||||||
|
|
||||||
elif order['side'] == trade.exit_side:
|
elif order['side'] == trade.exit_side:
|
||||||
self.handle_cancel_exit(trade, order, constants.CANCEL_REASON['ALL_CANCELLED'])
|
self.handle_cancel_exit(
|
||||||
|
trade, order, open_order.order_id, constants.CANCEL_REASON['ALL_CANCELLED']
|
||||||
|
)
|
||||||
Trade.commit()
|
Trade.commit()
|
||||||
|
|
||||||
def handle_cancel_enter(
|
def handle_cancel_enter(
|
||||||
self, trade: Trade, order: Dict, reason: str,
|
self, trade: Trade, order: Dict, order_id: str,
|
||||||
replacing: Optional[bool] = False
|
reason: str, replacing: Optional[bool] = False
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
entry cancel - cancel order
|
entry cancel - cancel order
|
||||||
@@ -1453,11 +1495,10 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
"""
|
"""
|
||||||
was_trade_fully_canceled = False
|
was_trade_fully_canceled = False
|
||||||
side = trade.entry_side.capitalize()
|
side = trade.entry_side.capitalize()
|
||||||
if not trade.open_order_id:
|
if not trade.has_open_orders:
|
||||||
logger.warning(f"No open order for {trade}.")
|
logger.warning(f"No open order for {trade}.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Cancelled orders may have the status of 'canceled' or 'closed'
|
|
||||||
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
||||||
filled_val: float = order.get('filled', 0.0) or 0.0
|
filled_val: float = order.get('filled', 0.0) or 0.0
|
||||||
filled_stake = filled_val * trade.open_rate
|
filled_stake = filled_val * trade.open_rate
|
||||||
@@ -1466,16 +1507,27 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
|
|
||||||
if filled_val > 0 and minstake and filled_stake < minstake:
|
if filled_val > 0 and minstake and filled_stake < minstake:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Order {trade.open_order_id} for {trade.pair} not cancelled, "
|
f"Order {order_id} for {trade.pair} not cancelled, "
|
||||||
f"as the filled amount of {filled_val} would result in an unexitable trade.")
|
f"as the filled amount of {filled_val} would result in an unexitable trade.")
|
||||||
return False
|
return False
|
||||||
corder = self.exchange.cancel_order_with_result(trade.open_order_id, trade.pair,
|
corder = self.exchange.cancel_order_with_result(order_id, trade.pair,
|
||||||
trade.amount)
|
trade.amount)
|
||||||
|
# if replacing, retry fetching the order 3 times if the status is not what we need
|
||||||
|
if replacing:
|
||||||
|
retry_count = 0
|
||||||
|
while (
|
||||||
|
corder.get('status') not in constants.NON_OPEN_EXCHANGE_STATES
|
||||||
|
and retry_count < 3
|
||||||
|
):
|
||||||
|
sleep(0.5)
|
||||||
|
corder = self.exchange.fetch_order(order_id, trade.pair)
|
||||||
|
retry_count += 1
|
||||||
|
|
||||||
# Avoid race condition where the order could not be cancelled coz its already filled.
|
# Avoid race condition where the order could not be cancelled coz its already filled.
|
||||||
# Simply bailing here is the only safe way - as this order will then be
|
# Simply bailing here is the only safe way - as this order will then be
|
||||||
# handled in the next iteration.
|
# handled in the next iteration.
|
||||||
if corder.get('status') not in constants.NON_OPEN_EXCHANGE_STATES:
|
if corder.get('status') not in constants.NON_OPEN_EXCHANGE_STATES:
|
||||||
logger.warning(f"Order {trade.open_order_id} for {trade.pair} not cancelled.")
|
logger.warning(f"Order {order_id} for {trade.pair} not cancelled.")
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
# Order was cancelled already, so we can reuse the existing dict
|
# Order was cancelled already, so we can reuse the existing dict
|
||||||
@@ -1487,22 +1539,22 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# Using filled to determine the filled amount
|
# Using filled to determine the filled amount
|
||||||
filled_amount = safe_value_fallback2(corder, order, 'filled', 'filled')
|
filled_amount = safe_value_fallback2(corder, order, 'filled', 'filled')
|
||||||
if isclose(filled_amount, 0.0, abs_tol=constants.MATH_CLOSE_PREC):
|
if isclose(filled_amount, 0.0, abs_tol=constants.MATH_CLOSE_PREC):
|
||||||
|
was_trade_fully_canceled = True
|
||||||
# if trade is not partially completed and it's the only order, just delete the trade
|
# if trade is not partially completed and it's the only order, just delete the trade
|
||||||
open_order_count = len([order for order in trade.orders if order.status == 'open'])
|
open_order_count = len([
|
||||||
if open_order_count <= 1 and trade.nr_of_successful_entries == 0 and not replacing:
|
order for order in trade.orders if order.ft_is_open and order.order_id != order_id
|
||||||
|
])
|
||||||
|
if open_order_count < 1 and trade.nr_of_successful_entries == 0 and not replacing:
|
||||||
logger.info(f'{side} order fully cancelled. Removing {trade} from database.')
|
logger.info(f'{side} order fully cancelled. Removing {trade} from database.')
|
||||||
trade.delete()
|
trade.delete()
|
||||||
was_trade_fully_canceled = True
|
|
||||||
reason += f", {constants.CANCEL_REASON['FULLY_CANCELLED']}"
|
reason += f", {constants.CANCEL_REASON['FULLY_CANCELLED']}"
|
||||||
else:
|
else:
|
||||||
self.update_trade_state(trade, trade.open_order_id, corder)
|
self.update_trade_state(trade, order_id, corder)
|
||||||
trade.open_order_id = None
|
|
||||||
logger.info(f'{side} Order timeout for {trade}.')
|
logger.info(f'{side} Order timeout for {trade}.')
|
||||||
else:
|
else:
|
||||||
# update_trade_state (and subsequently recalc_trade_from_orders) will handle updates
|
# update_trade_state (and subsequently recalc_trade_from_orders) will handle updates
|
||||||
# to the trade object
|
# to the trade object
|
||||||
self.update_trade_state(trade, trade.open_order_id, corder)
|
self.update_trade_state(trade, order_id, corder)
|
||||||
trade.open_order_id = None
|
|
||||||
|
|
||||||
logger.info(f'Partial {trade.entry_side} order timeout for {trade}.')
|
logger.info(f'Partial {trade.entry_side} order timeout for {trade}.')
|
||||||
reason += f", {constants.CANCEL_REASON['PARTIALLY_FILLED']}"
|
reason += f", {constants.CANCEL_REASON['PARTIALLY_FILLED']}"
|
||||||
@@ -1512,7 +1564,10 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
reason=reason)
|
reason=reason)
|
||||||
return was_trade_fully_canceled
|
return was_trade_fully_canceled
|
||||||
|
|
||||||
def handle_cancel_exit(self, trade: Trade, order: Dict, reason: str) -> bool:
|
def handle_cancel_exit(
|
||||||
|
self, trade: Trade, order: Dict, order_id: str,
|
||||||
|
reason: str
|
||||||
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
exit order cancel - cancel order and update trade
|
exit order cancel - cancel order and update trade
|
||||||
:return: True if exit order was cancelled, false otherwise
|
:return: True if exit order was cancelled, false otherwise
|
||||||
@@ -1520,17 +1575,18 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
cancelled = False
|
cancelled = False
|
||||||
# Cancelled orders may have the status of 'canceled' or 'closed'
|
# Cancelled orders may have the status of 'canceled' or 'closed'
|
||||||
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES:
|
||||||
filled_val: float = order.get('filled', 0.0) or 0.0
|
filled_amt: float = order.get('filled', 0.0) or 0.0
|
||||||
filled_rem_stake = trade.stake_amount - filled_val * trade.open_rate
|
# Filled val is in quote currency (after leverage)
|
||||||
|
filled_rem_stake = trade.stake_amount - (filled_amt * trade.open_rate / trade.leverage)
|
||||||
minstake = self.exchange.get_min_pair_stake_amount(
|
minstake = self.exchange.get_min_pair_stake_amount(
|
||||||
trade.pair, trade.open_rate, self.strategy.stoploss)
|
trade.pair, trade.open_rate, self.strategy.stoploss)
|
||||||
# Double-check remaining amount
|
# Double-check remaining amount
|
||||||
if filled_val > 0:
|
if filled_amt > 0:
|
||||||
reason = constants.CANCEL_REASON['PARTIALLY_FILLED']
|
reason = constants.CANCEL_REASON['PARTIALLY_FILLED']
|
||||||
if minstake and filled_rem_stake < minstake:
|
if minstake and filled_rem_stake < minstake:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Order {trade.open_order_id} for {trade.pair} not cancelled, as "
|
f"Order {order_id} for {trade.pair} not cancelled, as "
|
||||||
f"the filled amount of {filled_val} would result in an unexitable trade.")
|
f"the filled amount of {filled_amt} would result in an unexitable trade.")
|
||||||
reason = constants.CANCEL_REASON['PARTIALLY_FILLED_KEEP_OPEN']
|
reason = constants.CANCEL_REASON['PARTIALLY_FILLED_KEEP_OPEN']
|
||||||
|
|
||||||
self._notify_exit_cancel(
|
self._notify_exit_cancel(
|
||||||
@@ -1546,7 +1602,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
order['id'], trade.pair, trade.amount)
|
order['id'], trade.pair, trade.amount)
|
||||||
except InvalidOrderException:
|
except InvalidOrderException:
|
||||||
logger.exception(
|
logger.exception(
|
||||||
f"Could not cancel {trade.exit_side} order {trade.open_order_id}")
|
f"Could not cancel {trade.exit_side} order {order_id}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Set exit_reason for fill message
|
# Set exit_reason for fill message
|
||||||
@@ -1555,14 +1611,12 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
# Order might be filled above in odd timing issues.
|
# Order might be filled above in odd timing issues.
|
||||||
if order.get('status') in ('canceled', 'cancelled'):
|
if order.get('status') in ('canceled', 'cancelled'):
|
||||||
trade.exit_reason = None
|
trade.exit_reason = None
|
||||||
trade.open_order_id = None
|
|
||||||
else:
|
else:
|
||||||
trade.exit_reason = exit_reason_prev
|
trade.exit_reason = exit_reason_prev
|
||||||
cancelled = True
|
cancelled = True
|
||||||
else:
|
else:
|
||||||
reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
|
reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
|
||||||
trade.exit_reason = None
|
trade.exit_reason = None
|
||||||
trade.open_order_id = None
|
|
||||||
|
|
||||||
self.update_trade_state(trade, order['id'], order)
|
self.update_trade_state(trade, order['id'], order)
|
||||||
|
|
||||||
@@ -1696,7 +1750,6 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
order_obj = Order.parse_from_ccxt_object(order, trade.pair, trade.exit_side, amount, limit)
|
order_obj = Order.parse_from_ccxt_object(order, trade.pair, trade.exit_side, amount, limit)
|
||||||
trade.orders.append(order_obj)
|
trade.orders.append(order_obj)
|
||||||
|
|
||||||
trade.open_order_id = order['id']
|
|
||||||
trade.exit_order_status = ''
|
trade.exit_order_status = ''
|
||||||
trade.close_rate_requested = limit
|
trade.close_rate_requested = limit
|
||||||
trade.exit_reason = exit_reason
|
trade.exit_reason = exit_reason
|
||||||
@@ -1704,7 +1757,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj)
|
self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj)
|
||||||
# In case of market sell orders the order can be closed immediately
|
# In case of market sell orders the order can be closed immediately
|
||||||
if order.get('status', 'unknown') in ('closed', 'expired'):
|
if order.get('status', 'unknown') in ('closed', 'expired'):
|
||||||
self.update_trade_state(trade, trade.open_order_id, order)
|
self.update_trade_state(trade, order_obj.order_id, order)
|
||||||
Trade.commit()
|
Trade.commit()
|
||||||
|
|
||||||
return True
|
return True
|
||||||
@@ -1723,14 +1776,12 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
amount = order.safe_filled if fill else order.safe_amount
|
amount = order.safe_filled if fill else order.safe_amount
|
||||||
order_rate: float = order.safe_price
|
order_rate: float = order.safe_price
|
||||||
|
|
||||||
profit = trade.calc_profit(rate=order_rate, amount=amount, open_rate=trade.open_rate)
|
profit = trade.calculate_profit(order_rate, amount, trade.open_rate)
|
||||||
profit_ratio = trade.calc_profit_ratio(order_rate, amount, trade.open_rate)
|
|
||||||
else:
|
else:
|
||||||
order_rate = trade.safe_close_rate
|
order_rate = trade.safe_close_rate
|
||||||
profit = trade.calc_profit(rate=order_rate) + (0.0 if fill else trade.realized_profit)
|
profit = trade.calculate_profit(rate=order_rate)
|
||||||
profit_ratio = trade.calc_profit_ratio(order_rate)
|
|
||||||
amount = trade.amount
|
amount = trade.amount
|
||||||
gain = "profit" if profit_ratio > 0 else "loss"
|
gain = "profit" if profit.profit_ratio > 0 else "loss"
|
||||||
|
|
||||||
msg: RPCSellMsg = {
|
msg: RPCSellMsg = {
|
||||||
'type': (RPCMessageType.EXIT_FILL if fill
|
'type': (RPCMessageType.EXIT_FILL if fill
|
||||||
@@ -1748,8 +1799,8 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
'open_rate': trade.open_rate,
|
'open_rate': trade.open_rate,
|
||||||
'close_rate': order_rate,
|
'close_rate': order_rate,
|
||||||
'current_rate': current_rate,
|
'current_rate': current_rate,
|
||||||
'profit_amount': profit,
|
'profit_amount': profit.profit_abs if fill else profit.total_profit,
|
||||||
'profit_ratio': profit_ratio,
|
'profit_ratio': profit.profit_ratio,
|
||||||
'buy_tag': trade.enter_tag,
|
'buy_tag': trade.enter_tag,
|
||||||
'enter_tag': trade.enter_tag,
|
'enter_tag': trade.enter_tag,
|
||||||
'sell_reason': trade.exit_reason, # Deprecated
|
'sell_reason': trade.exit_reason, # Deprecated
|
||||||
@@ -1781,11 +1832,10 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
order = self.order_obj_or_raise(order_id, order_or_none)
|
order = self.order_obj_or_raise(order_id, order_or_none)
|
||||||
|
|
||||||
profit_rate: float = trade.safe_close_rate
|
profit_rate: float = trade.safe_close_rate
|
||||||
profit_trade = trade.calc_profit(rate=profit_rate)
|
profit = trade.calculate_profit(rate=profit_rate)
|
||||||
current_rate = self.exchange.get_rate(
|
current_rate = self.exchange.get_rate(
|
||||||
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
||||||
profit_ratio = trade.calc_profit_ratio(profit_rate)
|
gain = "profit" if profit.profit_ratio > 0 else "loss"
|
||||||
gain = "profit" if profit_ratio > 0 else "loss"
|
|
||||||
|
|
||||||
msg: RPCSellCancelMsg = {
|
msg: RPCSellCancelMsg = {
|
||||||
'type': RPCMessageType.EXIT_CANCEL,
|
'type': RPCMessageType.EXIT_CANCEL,
|
||||||
@@ -1800,8 +1850,8 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
'amount': order.safe_amount_after_fee,
|
'amount': order.safe_amount_after_fee,
|
||||||
'open_rate': trade.open_rate,
|
'open_rate': trade.open_rate,
|
||||||
'current_rate': current_rate,
|
'current_rate': current_rate,
|
||||||
'profit_amount': profit_trade,
|
'profit_amount': profit.profit_abs,
|
||||||
'profit_ratio': profit_ratio,
|
'profit_ratio': profit.profit_ratio,
|
||||||
'buy_tag': trade.enter_tag,
|
'buy_tag': trade.enter_tag,
|
||||||
'enter_tag': trade.enter_tag,
|
'enter_tag': trade.enter_tag,
|
||||||
'sell_reason': trade.exit_reason, # Deprecated
|
'sell_reason': trade.exit_reason, # Deprecated
|
||||||
@@ -1831,7 +1881,7 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
|
|
||||||
def update_trade_state(
|
def update_trade_state(
|
||||||
self, trade: Trade, order_id: Optional[str],
|
self, trade: Trade, order_id: Optional[str],
|
||||||
action_order: Optional[Dict[str, Any]] = None,
|
action_order: Optional[Dict[str, Any]] = None, *,
|
||||||
stoploss_order: bool = False, send_msg: bool = True) -> bool:
|
stoploss_order: bool = False, send_msg: bool = True) -> bool:
|
||||||
"""
|
"""
|
||||||
Checks trades with open orders and updates the amount if necessary
|
Checks trades with open orders and updates the amount if necessary
|
||||||
@@ -1868,17 +1918,25 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
|
|
||||||
self.handle_order_fee(trade, order_obj, order)
|
self.handle_order_fee(trade, order_obj, order)
|
||||||
|
|
||||||
trade.update_trade(order_obj)
|
trade.update_trade(order_obj, not send_msg)
|
||||||
|
|
||||||
if order.get('status') in constants.NON_OPEN_EXCHANGE_STATES:
|
trade = self._update_trade_after_fill(trade, order_obj)
|
||||||
|
Trade.commit()
|
||||||
|
|
||||||
|
self.order_close_notify(trade, order_obj, stoploss_order, send_msg)
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _update_trade_after_fill(self, trade: Trade, order: Order) -> Trade:
|
||||||
|
if order.status in constants.NON_OPEN_EXCHANGE_STATES:
|
||||||
# If a entry order was closed, force update on stoploss on exchange
|
# If a entry order was closed, force update on stoploss on exchange
|
||||||
if order.get('side') == trade.entry_side:
|
if order.ft_order_side == trade.entry_side:
|
||||||
trade = self.cancel_stoploss_on_exchange(trade)
|
trade = self.cancel_stoploss_on_exchange(trade)
|
||||||
if not self.edge:
|
if not self.edge:
|
||||||
# TODO: should shorting/leverage be supported by Edge,
|
# TODO: should shorting/leverage be supported by Edge,
|
||||||
# then this will need to be fixed.
|
# then this will need to be fixed.
|
||||||
trade.adjust_stop_loss(trade.open_rate, self.strategy.stoploss, initial=True)
|
trade.adjust_stop_loss(trade.open_rate, self.strategy.stoploss, initial=True)
|
||||||
if order.get('side') == trade.entry_side or (trade.amount > 0 and trade.is_open):
|
if order.ft_order_side == trade.entry_side or (trade.amount > 0 and trade.is_open):
|
||||||
# Must also run for partial exits
|
# Must also run for partial exits
|
||||||
# TODO: Margin will need to use interest_rate as well.
|
# TODO: Margin will need to use interest_rate as well.
|
||||||
# interest_rate = self.exchange.get_interest_rate()
|
# interest_rate = self.exchange.get_interest_rate()
|
||||||
@@ -1894,13 +1952,16 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
))
|
))
|
||||||
except DependencyException:
|
except DependencyException:
|
||||||
logger.warning('Unable to calculate liquidation price')
|
logger.warning('Unable to calculate liquidation price')
|
||||||
|
if self.strategy.use_custom_stoploss:
|
||||||
|
current_rate = self.exchange.get_rate(
|
||||||
|
trade.pair, side='exit', is_short=trade.is_short, refresh=True)
|
||||||
|
profit = trade.calc_profit_ratio(current_rate)
|
||||||
|
self.strategy.ft_stoploss_adjust(current_rate, trade,
|
||||||
|
datetime.now(timezone.utc), profit, 0,
|
||||||
|
after_fill=True)
|
||||||
# Updating wallets when order is closed
|
# Updating wallets when order is closed
|
||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
Trade.commit()
|
return trade
|
||||||
|
|
||||||
self.order_close_notify(trade, order_obj, stoploss_order, send_msg)
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
def order_close_notify(
|
def order_close_notify(
|
||||||
self, trade: Trade, order: Order, stoploss_order: bool, send_msg: bool):
|
self, trade: Trade, order: Order, stoploss_order: bool, send_msg: bool):
|
||||||
@@ -1910,11 +1971,11 @@ class FreqtradeBot(LoggingMixin):
|
|||||||
trade.amount, abs_tol=constants.MATH_CLOSE_PREC)
|
trade.amount, abs_tol=constants.MATH_CLOSE_PREC)
|
||||||
if order.ft_order_side == trade.exit_side:
|
if order.ft_order_side == trade.exit_side:
|
||||||
# Exit notification
|
# Exit notification
|
||||||
if send_msg and not stoploss_order and not trade.open_order_id:
|
if send_msg and not stoploss_order and order.order_id not in trade.open_orders_ids:
|
||||||
self._notify_exit(trade, '', fill=True, sub_trade=sub_trade, order=order)
|
self._notify_exit(trade, '', fill=True, sub_trade=sub_trade, order=order)
|
||||||
if not trade.is_open:
|
if not trade.is_open:
|
||||||
self.handle_protections(trade.pair, trade.trade_direction)
|
self.handle_protections(trade.pair, trade.trade_direction)
|
||||||
elif send_msg and not trade.open_order_id and not stoploss_order:
|
elif send_msg and order.order_id not in trade.open_orders_ids and not stoploss_order:
|
||||||
# Enter fill
|
# Enter fill
|
||||||
self._notify_enter(trade, order, order.order_type, fill=True, sub_trade=sub_trade)
|
self._notify_enter(trade, order, order.order_type, fill=True, sub_trade=sub_trade)
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -11,8 +11,8 @@ from freqtrade.util.gc_setup import gc_set_threshold
|
|||||||
|
|
||||||
|
|
||||||
# check min. python version
|
# check min. python version
|
||||||
if sys.version_info < (3, 8): # pragma: no cover
|
if sys.version_info < (3, 9): # pragma: no cover
|
||||||
sys.exit("Freqtrade requires Python version >= 3.8")
|
sys.exit("Freqtrade requires Python version >= 3.9")
|
||||||
|
|
||||||
from freqtrade import __version__
|
from freqtrade import __version__
|
||||||
from freqtrade.commands import Arguments
|
from freqtrade.commands import Arguments
|
||||||
|
|||||||
+2
-2
@@ -156,7 +156,7 @@ def round_dict(d, n):
|
|||||||
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
||||||
|
|
||||||
|
|
||||||
def safe_value_fallback(obj: dict, key1: str, key2: str, default_value=None):
|
def safe_value_fallback(obj: dict, key1: str, key2: Optional[str] = None, default_value=None):
|
||||||
"""
|
"""
|
||||||
Search a value in obj, return this if it's not None.
|
Search a value in obj, return this if it's not None.
|
||||||
Then search key2 in obj - return that if it's not none - then use default_value.
|
Then search key2 in obj - return that if it's not none - then use default_value.
|
||||||
@@ -165,7 +165,7 @@ def safe_value_fallback(obj: dict, key1: str, key2: str, default_value=None):
|
|||||||
if key1 in obj and obj[key1] is not None:
|
if key1 in obj and obj[key1] is not None:
|
||||||
return obj[key1]
|
return obj[key1]
|
||||||
else:
|
else:
|
||||||
if key2 in obj and obj[key2] is not None:
|
if key2 and key2 in obj and obj[key2] is not None:
|
||||||
return obj[key2]
|
return obj[key2]
|
||||||
return default_value
|
return default_value
|
||||||
|
|
||||||
|
|||||||
@@ -116,6 +116,7 @@ class Backtesting:
|
|||||||
raise OperationalException("Timeframe needs to be set in either "
|
raise OperationalException("Timeframe needs to be set in either "
|
||||||
"configuration or as cli argument `--timeframe 5m`")
|
"configuration or as cli argument `--timeframe 5m`")
|
||||||
self.timeframe = str(self.config.get('timeframe'))
|
self.timeframe = str(self.config.get('timeframe'))
|
||||||
|
self.disable_database_use()
|
||||||
self.timeframe_min = timeframe_to_minutes(self.timeframe)
|
self.timeframe_min = timeframe_to_minutes(self.timeframe)
|
||||||
self.init_backtest_detail()
|
self.init_backtest_detail()
|
||||||
self.pairlists = PairListManager(self.exchange, self.config, self.dataprovider)
|
self.pairlists = PairListManager(self.exchange, self.config, self.dataprovider)
|
||||||
@@ -318,13 +319,16 @@ class Backtesting:
|
|||||||
else:
|
else:
|
||||||
self.futures_data = {}
|
self.futures_data = {}
|
||||||
|
|
||||||
|
def disable_database_use(self):
|
||||||
|
PairLocks.use_db = False
|
||||||
|
PairLocks.timeframe = self.timeframe
|
||||||
|
Trade.use_db = False
|
||||||
|
|
||||||
def prepare_backtest(self, enable_protections):
|
def prepare_backtest(self, enable_protections):
|
||||||
"""
|
"""
|
||||||
Backtesting setup method - called once for every call to "backtest()".
|
Backtesting setup method - called once for every call to "backtest()".
|
||||||
"""
|
"""
|
||||||
PairLocks.use_db = False
|
self.disable_database_use()
|
||||||
PairLocks.timeframe = self.config['timeframe']
|
|
||||||
Trade.use_db = False
|
|
||||||
PairLocks.reset_locks()
|
PairLocks.reset_locks()
|
||||||
Trade.reset_trades()
|
Trade.reset_trades()
|
||||||
self.rejected_trades = 0
|
self.rejected_trades = 0
|
||||||
@@ -579,6 +583,11 @@ class Backtesting:
|
|||||||
""" Rate is within candle, therefore filled"""
|
""" Rate is within candle, therefore filled"""
|
||||||
return row[LOW_IDX] <= rate <= row[HIGH_IDX]
|
return row[LOW_IDX] <= rate <= row[HIGH_IDX]
|
||||||
|
|
||||||
|
def _call_adjust_stop(self, current_date: datetime, trade: LocalTrade, current_rate: float):
|
||||||
|
profit = trade.calc_profit_ratio(current_rate)
|
||||||
|
self.strategy.ft_stoploss_adjust(current_rate, trade, # type: ignore
|
||||||
|
current_date, profit, 0, after_fill=True)
|
||||||
|
|
||||||
def _try_close_open_order(
|
def _try_close_open_order(
|
||||||
self, order: Optional[Order], trade: LocalTrade, current_date: datetime,
|
self, order: Optional[Order], trade: LocalTrade, current_date: datetime,
|
||||||
row: Tuple) -> bool:
|
row: Tuple) -> bool:
|
||||||
@@ -588,7 +597,19 @@ class Backtesting:
|
|||||||
"""
|
"""
|
||||||
if order and self._get_order_filled(order.ft_price, row):
|
if order and self._get_order_filled(order.ft_price, row):
|
||||||
order.close_bt_order(current_date, trade)
|
order.close_bt_order(current_date, trade)
|
||||||
trade.open_order_id = None
|
if not (order.ft_order_side == trade.exit_side and order.safe_amount == trade.amount):
|
||||||
|
# trade is still open
|
||||||
|
trade.set_liquidation_price(self.exchange.get_liquidation_price(
|
||||||
|
pair=trade.pair,
|
||||||
|
open_rate=trade.open_rate,
|
||||||
|
is_short=trade.is_short,
|
||||||
|
amount=trade.amount,
|
||||||
|
stake_amount=trade.stake_amount,
|
||||||
|
leverage=trade.leverage,
|
||||||
|
wallet_balance=trade.stake_amount,
|
||||||
|
))
|
||||||
|
self._call_adjust_stop(current_date, trade, order.ft_price)
|
||||||
|
# pass
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -731,7 +752,9 @@ class Backtesting:
|
|||||||
if order_type == 'limit':
|
if order_type == 'limit':
|
||||||
new_rate = strategy_safe_wrapper(self.strategy.custom_entry_price,
|
new_rate = strategy_safe_wrapper(self.strategy.custom_entry_price,
|
||||||
default_retval=propose_rate)(
|
default_retval=propose_rate)(
|
||||||
pair=pair, current_time=current_time,
|
pair=pair,
|
||||||
|
trade=trade, # type: ignore[arg-type]
|
||||||
|
current_time=current_time,
|
||||||
proposed_rate=propose_rate, entry_tag=entry_tag,
|
proposed_rate=propose_rate, entry_tag=entry_tag,
|
||||||
side=direction,
|
side=direction,
|
||||||
) # default value is the open rate
|
) # default value is the open rate
|
||||||
@@ -854,7 +877,6 @@ class Backtesting:
|
|||||||
self.trade_id_counter += 1
|
self.trade_id_counter += 1
|
||||||
trade = LocalTrade(
|
trade = LocalTrade(
|
||||||
id=self.trade_id_counter,
|
id=self.trade_id_counter,
|
||||||
open_order_id=self.order_id_counter,
|
|
||||||
pair=pair,
|
pair=pair,
|
||||||
base_currency=base_currency,
|
base_currency=base_currency,
|
||||||
stake_currency=self.config['stake_currency'],
|
stake_currency=self.config['stake_currency'],
|
||||||
@@ -882,16 +904,6 @@ class Backtesting:
|
|||||||
|
|
||||||
trade.adjust_stop_loss(trade.open_rate, self.strategy.stoploss, initial=True)
|
trade.adjust_stop_loss(trade.open_rate, self.strategy.stoploss, initial=True)
|
||||||
|
|
||||||
trade.set_liquidation_price(self.exchange.get_liquidation_price(
|
|
||||||
pair=pair,
|
|
||||||
open_rate=propose_rate,
|
|
||||||
amount=amount,
|
|
||||||
stake_amount=trade.stake_amount,
|
|
||||||
leverage=trade.leverage,
|
|
||||||
wallet_balance=trade.stake_amount,
|
|
||||||
is_short=is_short,
|
|
||||||
))
|
|
||||||
|
|
||||||
order = Order(
|
order = Order(
|
||||||
id=self.order_id_counter,
|
id=self.order_id_counter,
|
||||||
ft_trade_id=trade.id,
|
ft_trade_id=trade.id,
|
||||||
@@ -916,8 +928,7 @@ class Backtesting:
|
|||||||
)
|
)
|
||||||
order._trade_bt = trade
|
order._trade_bt = trade
|
||||||
trade.orders.append(order)
|
trade.orders.append(order)
|
||||||
if not self._try_close_open_order(order, trade, current_time, row):
|
self._try_close_open_order(order, trade, current_time, row)
|
||||||
trade.open_order_id = str(self.order_id_counter)
|
|
||||||
trade.recalc_trade_from_orders()
|
trade.recalc_trade_from_orders()
|
||||||
|
|
||||||
return trade
|
return trade
|
||||||
@@ -929,7 +940,7 @@ class Backtesting:
|
|||||||
"""
|
"""
|
||||||
for pair in open_trades.keys():
|
for pair in open_trades.keys():
|
||||||
for trade in list(open_trades[pair]):
|
for trade in list(open_trades[pair]):
|
||||||
if trade.open_order_id and trade.nr_of_successful_entries == 0:
|
if trade.has_open_orders and trade.nr_of_successful_entries == 0:
|
||||||
# Ignore trade if entry-order did not fill yet
|
# Ignore trade if entry-order did not fill yet
|
||||||
continue
|
continue
|
||||||
exit_row = data[pair][-1]
|
exit_row = data[pair][-1]
|
||||||
@@ -1006,13 +1017,11 @@ class Backtesting:
|
|||||||
else:
|
else:
|
||||||
# Close additional entry order
|
# Close additional entry order
|
||||||
del trade.orders[trade.orders.index(order)]
|
del trade.orders[trade.orders.index(order)]
|
||||||
trade.open_order_id = None
|
|
||||||
return False
|
return False
|
||||||
if order.side == trade.exit_side:
|
if order.side == trade.exit_side:
|
||||||
self.timedout_exit_orders += 1
|
self.timedout_exit_orders += 1
|
||||||
# Close exit order and retry exiting on next signal.
|
# Close exit order and retry exiting on next signal.
|
||||||
del trade.orders[trade.orders.index(order)]
|
del trade.orders[trade.orders.index(order)]
|
||||||
trade.open_order_id = None
|
|
||||||
return False
|
return False
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -1040,7 +1049,6 @@ class Backtesting:
|
|||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
del trade.orders[trade.orders.index(order)]
|
del trade.orders[trade.orders.index(order)]
|
||||||
trade.open_order_id = None
|
|
||||||
self.canceled_entry_orders += 1
|
self.canceled_entry_orders += 1
|
||||||
|
|
||||||
# place new order if result was not None
|
# place new order if result was not None
|
||||||
@@ -1051,7 +1059,7 @@ class Backtesting:
|
|||||||
order.safe_remaining * order.ft_price / trade.leverage),
|
order.safe_remaining * order.ft_price / trade.leverage),
|
||||||
direction='short' if trade.is_short else 'long')
|
direction='short' if trade.is_short else 'long')
|
||||||
# Delete trade if no successful entries happened (if placing the new order failed)
|
# Delete trade if no successful entries happened (if placing the new order failed)
|
||||||
if trade.open_order_id is None and trade.nr_of_successful_entries == 0:
|
if not trade.has_open_orders and trade.nr_of_successful_entries == 0:
|
||||||
return True
|
return True
|
||||||
self.replaced_entry_orders += 1
|
self.replaced_entry_orders += 1
|
||||||
else:
|
else:
|
||||||
@@ -1136,7 +1144,7 @@ class Backtesting:
|
|||||||
self.wallets.update()
|
self.wallets.update()
|
||||||
|
|
||||||
# 4. Create exit orders (if any)
|
# 4. Create exit orders (if any)
|
||||||
if not trade.open_order_id:
|
if not trade.has_open_orders:
|
||||||
self._check_trade_exit(trade, row) # Place exit order if necessary
|
self._check_trade_exit(trade, row) # Place exit order if necessary
|
||||||
|
|
||||||
# 5. Process exit orders.
|
# 5. Process exit orders.
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import logging
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
from freqtrade.configuration import TimeRange
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class VarHolder:
|
||||||
|
timerange: TimeRange
|
||||||
|
data: DataFrame
|
||||||
|
indicators: Dict[str, DataFrame]
|
||||||
|
result: DataFrame
|
||||||
|
compared: DataFrame
|
||||||
|
from_dt: datetime
|
||||||
|
to_dt: datetime
|
||||||
|
compared_dt: datetime
|
||||||
|
timeframe: str
|
||||||
|
startup_candle: int
|
||||||
|
|
||||||
|
|
||||||
|
class BaseAnalysis:
|
||||||
|
|
||||||
|
def __init__(self, config: Dict[str, Any], strategy_obj: Dict):
|
||||||
|
self.failed_bias_check = True
|
||||||
|
self.full_varHolder = VarHolder()
|
||||||
|
self.exchange: Optional[Any] = None
|
||||||
|
self._fee = None
|
||||||
|
|
||||||
|
# pull variables the scope of the lookahead_analysis-instance
|
||||||
|
self.local_config = deepcopy(config)
|
||||||
|
self.local_config['strategy'] = strategy_obj['name']
|
||||||
|
self.strategy_obj = strategy_obj
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def dt_to_timestamp(dt: datetime):
|
||||||
|
timestamp = int(dt.replace(tzinfo=timezone.utc).timestamp())
|
||||||
|
return timestamp
|
||||||
|
|
||||||
|
def fill_full_varholder(self):
|
||||||
|
self.full_varHolder = VarHolder()
|
||||||
|
|
||||||
|
# define datetime in human-readable format
|
||||||
|
parsed_timerange = TimeRange.parse_timerange(self.local_config['timerange'])
|
||||||
|
|
||||||
|
if parsed_timerange.startdt is None:
|
||||||
|
self.full_varHolder.from_dt = datetime.fromtimestamp(0, tz=timezone.utc)
|
||||||
|
else:
|
||||||
|
self.full_varHolder.from_dt = parsed_timerange.startdt
|
||||||
|
|
||||||
|
if parsed_timerange.stopdt is None:
|
||||||
|
self.full_varHolder.to_dt = datetime.utcnow()
|
||||||
|
else:
|
||||||
|
self.full_varHolder.to_dt = parsed_timerange.stopdt
|
||||||
|
|
||||||
|
self.prepare_data(self.full_varHolder, self.local_config['pairs'])
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
|
||||||
|
# first make a single backtest
|
||||||
|
self.fill_full_varholder()
|
||||||
@@ -52,7 +52,7 @@ class SortinoHyperOptLossDaily(IHyperOptLoss):
|
|||||||
total_profit = sum_daily["profit_ratio_after_slippage"] - minimum_acceptable_return
|
total_profit = sum_daily["profit_ratio_after_slippage"] - minimum_acceptable_return
|
||||||
expected_returns_mean = total_profit.mean()
|
expected_returns_mean = total_profit.mean()
|
||||||
|
|
||||||
sum_daily['downside_returns'] = 0
|
sum_daily['downside_returns'] = 0.0
|
||||||
sum_daily.loc[total_profit < 0, 'downside_returns'] = total_profit
|
sum_daily.loc[total_profit < 0, 'downside_returns'] = total_profit
|
||||||
total_downside = sum_daily['downside_returns']
|
total_downside = sum_daily['downside_returns']
|
||||||
# Here total_downside contains min(0, P - MAR) values,
|
# Here total_downside contains min(0, P - MAR) values,
|
||||||
|
|||||||
@@ -1,35 +1,23 @@
|
|||||||
import logging
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
from pandas import DataFrame
|
from pandas import DataFrame
|
||||||
|
|
||||||
from freqtrade.configuration import TimeRange
|
|
||||||
from freqtrade.data.history import get_timerange
|
from freqtrade.data.history import get_timerange
|
||||||
from freqtrade.exchange import timeframe_to_minutes
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
from freqtrade.loggers.set_log_levels import (reduce_verbosity_for_bias_tester,
|
from freqtrade.loggers.set_log_levels import (reduce_verbosity_for_bias_tester,
|
||||||
restore_verbosity_for_bias_tester)
|
restore_verbosity_for_bias_tester)
|
||||||
from freqtrade.optimize.backtesting import Backtesting
|
from freqtrade.optimize.backtesting import Backtesting
|
||||||
|
from freqtrade.optimize.base_analysis import BaseAnalysis, VarHolder
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class VarHolder:
|
|
||||||
timerange: TimeRange
|
|
||||||
data: DataFrame
|
|
||||||
indicators: Dict[str, DataFrame]
|
|
||||||
result: DataFrame
|
|
||||||
compared: DataFrame
|
|
||||||
from_dt: datetime
|
|
||||||
to_dt: datetime
|
|
||||||
compared_dt: datetime
|
|
||||||
timeframe: str
|
|
||||||
|
|
||||||
|
|
||||||
class Analysis:
|
class Analysis:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.total_signals = 0
|
self.total_signals = 0
|
||||||
@@ -39,29 +27,18 @@ class Analysis:
|
|||||||
self.has_bias = False
|
self.has_bias = False
|
||||||
|
|
||||||
|
|
||||||
class LookaheadAnalysis:
|
class LookaheadAnalysis(BaseAnalysis):
|
||||||
|
|
||||||
def __init__(self, config: Dict[str, Any], strategy_obj: Dict):
|
def __init__(self, config: Dict[str, Any], strategy_obj: Dict):
|
||||||
self.failed_bias_check = True
|
|
||||||
self.full_varHolder = VarHolder()
|
super().__init__(config, strategy_obj)
|
||||||
|
|
||||||
self.entry_varHolders: List[VarHolder] = []
|
self.entry_varHolders: List[VarHolder] = []
|
||||||
self.exit_varHolders: List[VarHolder] = []
|
self.exit_varHolders: List[VarHolder] = []
|
||||||
self.exchange: Optional[Any] = None
|
|
||||||
self._fee = None
|
|
||||||
|
|
||||||
# pull variables the scope of the lookahead_analysis-instance
|
|
||||||
self.local_config = deepcopy(config)
|
|
||||||
self.local_config['strategy'] = strategy_obj['name']
|
|
||||||
self.current_analysis = Analysis()
|
self.current_analysis = Analysis()
|
||||||
self.minimum_trade_amount = config['minimum_trade_amount']
|
self.minimum_trade_amount = config['minimum_trade_amount']
|
||||||
self.targeted_trade_amount = config['targeted_trade_amount']
|
self.targeted_trade_amount = config['targeted_trade_amount']
|
||||||
self.strategy_obj = strategy_obj
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def dt_to_timestamp(dt: datetime):
|
|
||||||
timestamp = int(dt.replace(tzinfo=timezone.utc).timestamp())
|
|
||||||
return timestamp
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_result(backtesting: Backtesting, processed: DataFrame):
|
def get_result(backtesting: Backtesting, processed: DataFrame):
|
||||||
@@ -162,24 +139,6 @@ class LookaheadAnalysis:
|
|||||||
varholder.indicators = backtesting.strategy.advise_all_indicators(varholder.data)
|
varholder.indicators = backtesting.strategy.advise_all_indicators(varholder.data)
|
||||||
varholder.result = self.get_result(backtesting, varholder.indicators)
|
varholder.result = self.get_result(backtesting, varholder.indicators)
|
||||||
|
|
||||||
def fill_full_varholder(self):
|
|
||||||
self.full_varHolder = VarHolder()
|
|
||||||
|
|
||||||
# define datetime in human-readable format
|
|
||||||
parsed_timerange = TimeRange.parse_timerange(self.local_config['timerange'])
|
|
||||||
|
|
||||||
if parsed_timerange.startdt is None:
|
|
||||||
self.full_varHolder.from_dt = datetime.fromtimestamp(0, tz=timezone.utc)
|
|
||||||
else:
|
|
||||||
self.full_varHolder.from_dt = parsed_timerange.startdt
|
|
||||||
|
|
||||||
if parsed_timerange.stopdt is None:
|
|
||||||
self.full_varHolder.to_dt = datetime.utcnow()
|
|
||||||
else:
|
|
||||||
self.full_varHolder.to_dt = parsed_timerange.stopdt
|
|
||||||
|
|
||||||
self.prepare_data(self.full_varHolder, self.local_config['pairs'])
|
|
||||||
|
|
||||||
def fill_entry_and_exit_varHolders(self, result_row):
|
def fill_entry_and_exit_varHolders(self, result_row):
|
||||||
# entry_varHolder
|
# entry_varHolder
|
||||||
entry_varHolder = VarHolder()
|
entry_varHolder = VarHolder()
|
||||||
@@ -246,8 +205,7 @@ class LookaheadAnalysis:
|
|||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
|
|
||||||
# first make a single backtest
|
super().start()
|
||||||
self.fill_full_varholder()
|
|
||||||
|
|
||||||
reduce_verbosity_for_bias_tester()
|
reduce_verbosity_for_bias_tester()
|
||||||
|
|
||||||
|
|||||||
@@ -184,12 +184,12 @@ class LookaheadAnalysisSubFunctions:
|
|||||||
|
|
||||||
lookaheadAnalysis_instances = []
|
lookaheadAnalysis_instances = []
|
||||||
|
|
||||||
# unify --strategy and --strategy_list to one list
|
# unify --strategy and --strategy-list to one list
|
||||||
if not (strategy_list := config.get('strategy_list', [])):
|
if not (strategy_list := config.get('strategy_list', [])):
|
||||||
if config.get('strategy') is None:
|
if config.get('strategy') is None:
|
||||||
raise OperationalException(
|
raise OperationalException(
|
||||||
"No Strategy specified. Please specify a strategy via --strategy or "
|
"No Strategy specified. Please specify a strategy via --strategy or "
|
||||||
"--strategy_list"
|
"--strategy-list"
|
||||||
)
|
)
|
||||||
strategy_list = [config['strategy']]
|
strategy_list = [config['strategy']]
|
||||||
|
|
||||||
@@ -211,5 +211,5 @@ class LookaheadAnalysisSubFunctions:
|
|||||||
else:
|
else:
|
||||||
logger.error("There were no strategies specified neither through "
|
logger.error("There were no strategies specified neither through "
|
||||||
"--strategy nor through "
|
"--strategy nor through "
|
||||||
"--strategy_list "
|
"--strategy-list "
|
||||||
"or timeframe was not specified.")
|
"or timeframe was not specified.")
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from pandas import DataFrame
|
||||||
|
|
||||||
|
from freqtrade.exchange import timeframe_to_minutes
|
||||||
|
from freqtrade.loggers.set_log_levels import (reduce_verbosity_for_bias_tester,
|
||||||
|
restore_verbosity_for_bias_tester)
|
||||||
|
from freqtrade.optimize.backtesting import Backtesting
|
||||||
|
from freqtrade.optimize.base_analysis import BaseAnalysis, VarHolder
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RecursiveAnalysis(BaseAnalysis):
|
||||||
|
|
||||||
|
def __init__(self, config: Dict[str, Any], strategy_obj: Dict):
|
||||||
|
|
||||||
|
self._startup_candle = config.get('startup_candle', [199, 399, 499, 999, 1999])
|
||||||
|
|
||||||
|
super().__init__(config, strategy_obj)
|
||||||
|
|
||||||
|
self.partial_varHolder_array: List[VarHolder] = []
|
||||||
|
self.partial_varHolder_lookahead_array: List[VarHolder] = []
|
||||||
|
|
||||||
|
self.dict_recursive: Dict[str, Any] = dict()
|
||||||
|
|
||||||
|
# For recursive bias check
|
||||||
|
# analyzes two data frames with processed indicators and shows differences between them.
|
||||||
|
def analyze_indicators(self):
|
||||||
|
|
||||||
|
pair_to_check = self.local_config['pairs'][0]
|
||||||
|
logger.info("Start checking for recursive bias")
|
||||||
|
|
||||||
|
# check and report signals
|
||||||
|
base_last_row = self.full_varHolder.indicators[pair_to_check].iloc[-1]
|
||||||
|
|
||||||
|
for part in self.partial_varHolder_array:
|
||||||
|
part_last_row = part.indicators[pair_to_check].iloc[-1]
|
||||||
|
|
||||||
|
compare_df = base_last_row.compare(part_last_row)
|
||||||
|
if compare_df.shape[0] > 0:
|
||||||
|
# print(compare_df)
|
||||||
|
for col_name, values in compare_df.items():
|
||||||
|
# print(col_name)
|
||||||
|
if 'other' == col_name:
|
||||||
|
continue
|
||||||
|
indicators = values.index
|
||||||
|
|
||||||
|
for indicator in indicators:
|
||||||
|
if (indicator not in self.dict_recursive):
|
||||||
|
self.dict_recursive[indicator] = {}
|
||||||
|
|
||||||
|
values_diff = compare_df.loc[indicator]
|
||||||
|
values_diff_self = values_diff.loc['self']
|
||||||
|
values_diff_other = values_diff.loc['other']
|
||||||
|
diff = (values_diff_other - values_diff_self) / values_diff_self * 100
|
||||||
|
|
||||||
|
self.dict_recursive[indicator][part.startup_candle] = f"{diff:.3f}%"
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.info("No difference found. Stop the process.")
|
||||||
|
break
|
||||||
|
|
||||||
|
# For lookahead bias check
|
||||||
|
# analyzes two data frames with processed indicators and shows differences between them.
|
||||||
|
def analyze_indicators_lookahead(self):
|
||||||
|
|
||||||
|
pair_to_check = self.local_config['pairs'][0]
|
||||||
|
logger.info("Start checking for lookahead bias on indicators only")
|
||||||
|
|
||||||
|
part = self.partial_varHolder_lookahead_array[0]
|
||||||
|
part_last_row = part.indicators[pair_to_check].iloc[-1]
|
||||||
|
date_to_check = part_last_row['date']
|
||||||
|
index_to_get = (self.full_varHolder.indicators[pair_to_check]['date'] == date_to_check)
|
||||||
|
base_row_check = self.full_varHolder.indicators[pair_to_check].loc[index_to_get].iloc[-1]
|
||||||
|
|
||||||
|
check_time = part.to_dt.strftime('%Y-%m-%dT%H:%M:%S')
|
||||||
|
|
||||||
|
logger.info(f"Check indicators at {check_time}")
|
||||||
|
# logger.info(f"vs {part_timerange} with {part.startup_candle} startup candle")
|
||||||
|
|
||||||
|
compare_df = base_row_check.compare(part_last_row)
|
||||||
|
if compare_df.shape[0] > 0:
|
||||||
|
# print(compare_df)
|
||||||
|
for col_name, values in compare_df.items():
|
||||||
|
# print(col_name)
|
||||||
|
if 'other' == col_name:
|
||||||
|
continue
|
||||||
|
indicators = values.index
|
||||||
|
|
||||||
|
for indicator in indicators:
|
||||||
|
logger.info(f"=> found lookahead in indicator {indicator}")
|
||||||
|
# logger.info("base value {:.5f}".format(values_diff_self))
|
||||||
|
# logger.info("part value {:.5f}".format(values_diff_other))
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.info("No lookahead bias on indicators found. Stop the process.")
|
||||||
|
|
||||||
|
def prepare_data(self, varholder: VarHolder, pairs_to_load: List[DataFrame]):
|
||||||
|
|
||||||
|
if 'freqai' in self.local_config and 'identifier' in self.local_config['freqai']:
|
||||||
|
# purge previous data if the freqai model is defined
|
||||||
|
# (to be sure nothing is carried over from older backtests)
|
||||||
|
path_to_current_identifier = (
|
||||||
|
Path(f"{self.local_config['user_data_dir']}/models/"
|
||||||
|
f"{self.local_config['freqai']['identifier']}").resolve())
|
||||||
|
# remove folder and its contents
|
||||||
|
if Path.exists(path_to_current_identifier):
|
||||||
|
shutil.rmtree(path_to_current_identifier)
|
||||||
|
|
||||||
|
prepare_data_config = deepcopy(self.local_config)
|
||||||
|
prepare_data_config['timerange'] = (str(self.dt_to_timestamp(varholder.from_dt)) + "-" +
|
||||||
|
str(self.dt_to_timestamp(varholder.to_dt)))
|
||||||
|
prepare_data_config['exchange']['pair_whitelist'] = pairs_to_load
|
||||||
|
|
||||||
|
backtesting = Backtesting(prepare_data_config, self.exchange)
|
||||||
|
backtesting._set_strategy(backtesting.strategylist[0])
|
||||||
|
|
||||||
|
varholder.data, varholder.timerange = backtesting.load_bt_data()
|
||||||
|
backtesting.load_bt_data_detail()
|
||||||
|
varholder.timeframe = backtesting.timeframe
|
||||||
|
|
||||||
|
varholder.indicators = backtesting.strategy.advise_all_indicators(varholder.data)
|
||||||
|
|
||||||
|
def fill_partial_varholder(self, start_date, startup_candle):
|
||||||
|
logger.info(f"Calculating indicators using startup candle of {startup_candle}.")
|
||||||
|
partial_varHolder = VarHolder()
|
||||||
|
|
||||||
|
partial_varHolder.from_dt = start_date
|
||||||
|
partial_varHolder.to_dt = self.full_varHolder.to_dt
|
||||||
|
partial_varHolder.startup_candle = startup_candle
|
||||||
|
|
||||||
|
self.local_config['startup_candle_count'] = startup_candle
|
||||||
|
|
||||||
|
self.prepare_data(partial_varHolder, self.local_config['pairs'])
|
||||||
|
|
||||||
|
self.partial_varHolder_array.append(partial_varHolder)
|
||||||
|
|
||||||
|
def fill_partial_varholder_lookahead(self, end_date):
|
||||||
|
logger.info("Calculating indicators to test lookahead on indicators.")
|
||||||
|
|
||||||
|
partial_varHolder = VarHolder()
|
||||||
|
|
||||||
|
partial_varHolder.from_dt = self.full_varHolder.from_dt
|
||||||
|
partial_varHolder.to_dt = end_date
|
||||||
|
|
||||||
|
self.prepare_data(partial_varHolder, self.local_config['pairs'])
|
||||||
|
|
||||||
|
self.partial_varHolder_lookahead_array.append(partial_varHolder)
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
|
||||||
|
super().start()
|
||||||
|
|
||||||
|
reduce_verbosity_for_bias_tester()
|
||||||
|
start_date_full = self.full_varHolder.from_dt
|
||||||
|
end_date_full = self.full_varHolder.to_dt
|
||||||
|
|
||||||
|
timeframe_minutes = timeframe_to_minutes(self.full_varHolder.timeframe)
|
||||||
|
|
||||||
|
end_date_partial = start_date_full + timedelta(minutes=int(timeframe_minutes * 10))
|
||||||
|
|
||||||
|
self.fill_partial_varholder_lookahead(end_date_partial)
|
||||||
|
|
||||||
|
# restore_verbosity_for_bias_tester()
|
||||||
|
|
||||||
|
start_date_partial = end_date_full - timedelta(minutes=int(timeframe_minutes))
|
||||||
|
|
||||||
|
for startup_candle in self._startup_candle:
|
||||||
|
self.fill_partial_varholder(start_date_partial, int(startup_candle))
|
||||||
|
|
||||||
|
# Restore verbosity, so it's not too quiet for the next strategy
|
||||||
|
restore_verbosity_for_bias_tester()
|
||||||
|
|
||||||
|
self.analyze_indicators()
|
||||||
|
self.analyze_indicators_lookahead()
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from freqtrade.constants import Config
|
||||||
|
from freqtrade.exceptions import OperationalException
|
||||||
|
from freqtrade.optimize.recursive_analysis import RecursiveAnalysis
|
||||||
|
from freqtrade.resolvers import StrategyResolver
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RecursiveAnalysisSubFunctions:
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def text_table_recursive_analysis_instances(
|
||||||
|
recursive_instances: List[RecursiveAnalysis]):
|
||||||
|
startups = recursive_instances[0]._startup_candle
|
||||||
|
headers = ['indicators']
|
||||||
|
for candle in startups:
|
||||||
|
headers.append(candle)
|
||||||
|
|
||||||
|
data = []
|
||||||
|
for inst in recursive_instances:
|
||||||
|
if len(inst.dict_recursive) > 0:
|
||||||
|
for indicator, values in inst.dict_recursive.items():
|
||||||
|
temp_data = [indicator]
|
||||||
|
for candle in startups:
|
||||||
|
temp_data.append(values.get(int(candle), '-'))
|
||||||
|
data.append(temp_data)
|
||||||
|
|
||||||
|
from tabulate import tabulate
|
||||||
|
table = tabulate(data, headers=headers, tablefmt="orgtbl")
|
||||||
|
print(table)
|
||||||
|
return table, headers, data
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def calculate_config_overrides(config: Config):
|
||||||
|
if 'timerange' not in config:
|
||||||
|
# setting a timerange is enforced here
|
||||||
|
raise OperationalException(
|
||||||
|
"Please set a timerange. "
|
||||||
|
"A timerange of 5000 candles are enough for recursive analysis."
|
||||||
|
)
|
||||||
|
|
||||||
|
if config.get('backtest_cache') is None:
|
||||||
|
config['backtest_cache'] = 'none'
|
||||||
|
elif config['backtest_cache'] != 'none':
|
||||||
|
logger.info(f"backtest_cache = "
|
||||||
|
f"{config['backtest_cache']} detected. "
|
||||||
|
f"Inside recursive-analysis it is enforced to be 'none'. "
|
||||||
|
f"Changed it to 'none'")
|
||||||
|
config['backtest_cache'] = 'none'
|
||||||
|
return config
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def initialize_single_recursive_analysis(config: Config, strategy_obj: Dict[str, Any]):
|
||||||
|
|
||||||
|
logger.info(f"Recursive test of {Path(strategy_obj['location']).name} started.")
|
||||||
|
start = time.perf_counter()
|
||||||
|
current_instance = RecursiveAnalysis(config, strategy_obj)
|
||||||
|
current_instance.start()
|
||||||
|
elapsed = time.perf_counter() - start
|
||||||
|
logger.info(f"Checking recursive and indicator-only lookahead bias of indicators "
|
||||||
|
f"of {Path(strategy_obj['location']).name} "
|
||||||
|
f"took {elapsed:.0f} seconds.")
|
||||||
|
return current_instance
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def start(config: Config):
|
||||||
|
config = RecursiveAnalysisSubFunctions.calculate_config_overrides(config)
|
||||||
|
|
||||||
|
strategy_objs = StrategyResolver.search_all_objects(
|
||||||
|
config, enum_failed=False, recursive=config.get('recursive_strategy_search', False))
|
||||||
|
|
||||||
|
RecursiveAnalysis_instances = []
|
||||||
|
|
||||||
|
# unify --strategy and --strategy-list to one list
|
||||||
|
if not (strategy_list := config.get('strategy_list', [])):
|
||||||
|
if config.get('strategy') is None:
|
||||||
|
raise OperationalException(
|
||||||
|
"No Strategy specified. Please specify a strategy via --strategy or "
|
||||||
|
"--strategy-list"
|
||||||
|
)
|
||||||
|
strategy_list = [config['strategy']]
|
||||||
|
|
||||||
|
# check if strategies can be properly loaded, only check them if they can be.
|
||||||
|
for strat in strategy_list:
|
||||||
|
for strategy_obj in strategy_objs:
|
||||||
|
if strategy_obj['name'] == strat and strategy_obj not in strategy_list:
|
||||||
|
RecursiveAnalysis_instances.append(
|
||||||
|
RecursiveAnalysisSubFunctions.initialize_single_recursive_analysis(
|
||||||
|
config, strategy_obj))
|
||||||
|
break
|
||||||
|
|
||||||
|
# report the results
|
||||||
|
if RecursiveAnalysis_instances:
|
||||||
|
RecursiveAnalysisSubFunctions.text_table_recursive_analysis_instances(
|
||||||
|
RecursiveAnalysis_instances)
|
||||||
|
else:
|
||||||
|
logger.error("There were no strategies specified neither through "
|
||||||
|
"--strategy nor through "
|
||||||
|
"--strategy-list "
|
||||||
|
"or timeframe was not specified.")
|
||||||
@@ -88,6 +88,9 @@ def migrate_trades_and_orders_table(
|
|||||||
stop_loss_pct = get_column_def(cols, 'stop_loss_pct', 'null')
|
stop_loss_pct = get_column_def(cols, 'stop_loss_pct', 'null')
|
||||||
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
||||||
initial_stop_loss_pct = get_column_def(cols, 'initial_stop_loss_pct', 'null')
|
initial_stop_loss_pct = get_column_def(cols, 'initial_stop_loss_pct', 'null')
|
||||||
|
is_stop_loss_trailing = get_column_def(
|
||||||
|
cols, 'is_stop_loss_trailing',
|
||||||
|
f'coalesce({stop_loss_pct}, 0.0) <> coalesce({initial_stop_loss_pct}, 0.0)')
|
||||||
stoploss_order_id = get_column_def(cols, 'stoploss_order_id', 'null')
|
stoploss_order_id = get_column_def(cols, 'stoploss_order_id', 'null')
|
||||||
stoploss_last_update = get_column_def(cols, 'stoploss_last_update', 'null')
|
stoploss_last_update = get_column_def(cols, 'stoploss_last_update', 'null')
|
||||||
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
||||||
@@ -154,9 +157,9 @@ def migrate_trades_and_orders_table(
|
|||||||
fee_open, fee_open_cost, fee_open_currency,
|
fee_open, fee_open_cost, fee_open_currency,
|
||||||
fee_close, fee_close_cost, fee_close_currency, open_rate,
|
fee_close, fee_close_cost, fee_close_currency, open_rate,
|
||||||
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
||||||
stake_amount, amount, amount_requested, open_date, close_date, open_order_id,
|
stake_amount, amount, amount_requested, open_date, close_date,
|
||||||
stop_loss, stop_loss_pct, initial_stop_loss, initial_stop_loss_pct,
|
stop_loss, stop_loss_pct, initial_stop_loss, initial_stop_loss_pct,
|
||||||
stoploss_order_id, stoploss_last_update,
|
is_stop_loss_trailing, stoploss_order_id, stoploss_last_update,
|
||||||
max_rate, min_rate, exit_reason, exit_order_status, strategy, enter_tag,
|
max_rate, min_rate, exit_reason, exit_order_status, strategy, enter_tag,
|
||||||
timeframe, open_trade_value, close_profit_abs,
|
timeframe, open_trade_value, close_profit_abs,
|
||||||
trading_mode, leverage, liquidation_price, is_short,
|
trading_mode, leverage, liquidation_price, is_short,
|
||||||
@@ -171,10 +174,11 @@ def migrate_trades_and_orders_table(
|
|||||||
{fee_close_cost} fee_close_cost, {fee_close_currency} fee_close_currency,
|
{fee_close_cost} fee_close_cost, {fee_close_currency} fee_close_currency,
|
||||||
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
||||||
{close_rate_requested} close_rate_requested, close_profit,
|
{close_rate_requested} close_rate_requested, close_profit,
|
||||||
stake_amount, amount, {amount_requested}, open_date, close_date, open_order_id,
|
stake_amount, amount, {amount_requested}, open_date, close_date,
|
||||||
{stop_loss} stop_loss, {stop_loss_pct} stop_loss_pct,
|
{stop_loss} stop_loss, {stop_loss_pct} stop_loss_pct,
|
||||||
{initial_stop_loss} initial_stop_loss,
|
{initial_stop_loss} initial_stop_loss,
|
||||||
{initial_stop_loss_pct} initial_stop_loss_pct,
|
{initial_stop_loss_pct} initial_stop_loss_pct,
|
||||||
|
{is_stop_loss_trailing} is_stop_loss_trailing,
|
||||||
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
||||||
{max_rate} max_rate, {min_rate} min_rate,
|
{max_rate} max_rate, {min_rate} min_rate,
|
||||||
case when {exit_reason} = 'sell_signal' then 'exit_signal'
|
case when {exit_reason} = 'sell_signal' then 'exit_signal'
|
||||||
@@ -268,6 +272,13 @@ def set_sqlite_to_wal(engine):
|
|||||||
|
|
||||||
def fix_old_dry_orders(engine):
|
def fix_old_dry_orders(engine):
|
||||||
with engine.begin() as connection:
|
with engine.begin() as connection:
|
||||||
|
|
||||||
|
# Update current dry-run Orders where
|
||||||
|
# - current Order is open
|
||||||
|
# - current Trade is closed
|
||||||
|
# - current Order trade_id not equal to current Trade.id
|
||||||
|
# - current Order not stoploss
|
||||||
|
|
||||||
stmt = update(Order).where(
|
stmt = update(Order).where(
|
||||||
Order.ft_is_open.is_(True),
|
Order.ft_is_open.is_(True),
|
||||||
tuple_(Order.ft_trade_id, Order.order_id).not_in(
|
tuple_(Order.ft_trade_id, Order.order_id).not_in(
|
||||||
@@ -281,12 +292,13 @@ def fix_old_dry_orders(engine):
|
|||||||
).values(ft_is_open=False)
|
).values(ft_is_open=False)
|
||||||
connection.execute(stmt)
|
connection.execute(stmt)
|
||||||
|
|
||||||
|
# Close dry-run orders for closed trades.
|
||||||
stmt = update(Order).where(
|
stmt = update(Order).where(
|
||||||
Order.ft_is_open.is_(True),
|
Order.ft_is_open.is_(True),
|
||||||
tuple_(Order.ft_trade_id, Order.order_id).not_in(
|
Order.ft_trade_id.not_in(
|
||||||
select(
|
select(
|
||||||
Trade.id, Trade.open_order_id
|
Trade.id
|
||||||
).where(Trade.open_order_id.is_not(None))
|
).where(Trade.is_open.is_(True))
|
||||||
),
|
),
|
||||||
Order.ft_order_side != 'stoploss',
|
Order.ft_order_side != 'stoploss',
|
||||||
Order.order_id.like('dry%')
|
Order.order_id.like('dry%')
|
||||||
@@ -316,8 +328,8 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
|
|||||||
# if ('orders' not in previous_tables
|
# if ('orders' not in previous_tables
|
||||||
# or not has_column(cols_orders, 'funding_fee')):
|
# or not has_column(cols_orders, 'funding_fee')):
|
||||||
migrating = False
|
migrating = False
|
||||||
# if not has_column(cols_trades, 'max_stake_amount'):
|
# if not has_column(cols_orders, 'ft_price'):
|
||||||
if not has_column(cols_orders, 'ft_price'):
|
if not has_column(cols_trades, 'is_stop_loss_trailing'):
|
||||||
migrating = True
|
migrating = True
|
||||||
logger.info(f"Running database migration for trades - "
|
logger.info(f"Running database migration for trades - "
|
||||||
f"backup: {table_back_name}, {order_table_bak_name}")
|
f"backup: {table_back_name}, {order_table_bak_name}")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ This module contains the class to persist trades into SQLite
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from math import isclose
|
from math import isclose
|
||||||
from typing import Any, ClassVar, Dict, List, Optional, Sequence, cast
|
from typing import Any, ClassVar, Dict, List, Optional, Sequence, cast
|
||||||
@@ -12,20 +13,30 @@ from sqlalchemy import (Enum, Float, ForeignKey, Integer, ScalarResult, Select,
|
|||||||
from sqlalchemy.orm import Mapped, lazyload, mapped_column, relationship, validates
|
from sqlalchemy.orm import Mapped, lazyload, mapped_column, relationship, validates
|
||||||
from typing_extensions import Self
|
from typing_extensions import Self
|
||||||
|
|
||||||
from freqtrade.constants import (CUSTOM_TAG_MAX_LENGTH, DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC,
|
from freqtrade.constants import (CANCELED_EXCHANGE_STATES, CUSTOM_TAG_MAX_LENGTH,
|
||||||
NON_OPEN_EXCHANGE_STATES, BuySell, LongShort)
|
DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES,
|
||||||
|
BuySell, LongShort)
|
||||||
from freqtrade.enums import ExitType, TradingMode
|
from freqtrade.enums import ExitType, TradingMode
|
||||||
from freqtrade.exceptions import DependencyException, OperationalException
|
from freqtrade.exceptions import DependencyException, OperationalException
|
||||||
from freqtrade.exchange import (ROUND_DOWN, ROUND_UP, amount_to_contract_precision,
|
from freqtrade.exchange import (ROUND_DOWN, ROUND_UP, amount_to_contract_precision,
|
||||||
price_to_precision)
|
price_to_precision)
|
||||||
from freqtrade.leverage import interest
|
from freqtrade.leverage import interest
|
||||||
|
from freqtrade.misc import safe_value_fallback
|
||||||
from freqtrade.persistence.base import ModelBase, SessionType
|
from freqtrade.persistence.base import ModelBase, SessionType
|
||||||
from freqtrade.util import FtPrecise, dt_now
|
from freqtrade.util import FtPrecise, dt_from_ts, dt_now, dt_ts
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ProfitStruct:
|
||||||
|
profit_abs: float
|
||||||
|
profit_ratio: float
|
||||||
|
total_profit: float
|
||||||
|
total_profit_ratio: float
|
||||||
|
|
||||||
|
|
||||||
class Order(ModelBase):
|
class Order(ModelBase):
|
||||||
"""
|
"""
|
||||||
Order database model
|
Order database model
|
||||||
@@ -167,7 +178,9 @@ class Order(ModelBase):
|
|||||||
# (represents the funding fee since the last order)
|
# (represents the funding fee since the last order)
|
||||||
self.funding_fee = self.trade.funding_fees
|
self.funding_fee = self.trade.funding_fees
|
||||||
if (order.get('filled', 0.0) or 0.0) > 0 and not self.order_filled_date:
|
if (order.get('filled', 0.0) or 0.0) > 0 and not self.order_filled_date:
|
||||||
self.order_filled_date = datetime.now(timezone.utc)
|
self.order_filled_date = dt_from_ts(
|
||||||
|
safe_value_fallback(order, 'lastTradeTimestamp', default_value=dt_ts())
|
||||||
|
)
|
||||||
self.order_update_date = datetime.now(timezone.utc)
|
self.order_update_date = datetime.now(timezone.utc)
|
||||||
|
|
||||||
def to_ccxt_object(self, stopPriceName: str = 'stopPrice') -> Dict[str, Any]:
|
def to_ccxt_object(self, stopPriceName: str = 'stopPrice') -> Dict[str, Any]:
|
||||||
@@ -240,7 +253,10 @@ class Order(ModelBase):
|
|||||||
if (self.ft_order_side == trade.entry_side and self.price):
|
if (self.ft_order_side == trade.entry_side and self.price):
|
||||||
trade.open_rate = self.price
|
trade.open_rate = self.price
|
||||||
trade.recalc_trade_from_orders()
|
trade.recalc_trade_from_orders()
|
||||||
trade.adjust_stop_loss(trade.open_rate, trade.stop_loss_pct, refresh=True)
|
if trade.nr_of_successful_entries == 1:
|
||||||
|
trade.initial_stop_loss_pct = None
|
||||||
|
trade.is_stop_loss_trailing = False
|
||||||
|
trade.adjust_stop_loss(trade.open_rate, trade.stop_loss_pct)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def update_orders(orders: List['Order'], order: Dict[str, Any]):
|
def update_orders(orders: List['Order'], order: Dict[str, Any]):
|
||||||
@@ -340,7 +356,6 @@ class LocalTrade:
|
|||||||
amount_requested: Optional[float] = None
|
amount_requested: Optional[float] = None
|
||||||
open_date: datetime
|
open_date: datetime
|
||||||
close_date: Optional[datetime] = None
|
close_date: Optional[datetime] = None
|
||||||
open_order_id: Optional[str] = None
|
|
||||||
# absolute value of the stop loss
|
# absolute value of the stop loss
|
||||||
stop_loss: float = 0.0
|
stop_loss: float = 0.0
|
||||||
# percentage value of the stop loss
|
# percentage value of the stop loss
|
||||||
@@ -349,6 +364,7 @@ class LocalTrade:
|
|||||||
initial_stop_loss: Optional[float] = 0.0
|
initial_stop_loss: Optional[float] = 0.0
|
||||||
# percentage value of the initial stop loss
|
# percentage value of the initial stop loss
|
||||||
initial_stop_loss_pct: Optional[float] = None
|
initial_stop_loss_pct: Optional[float] = None
|
||||||
|
is_stop_loss_trailing: bool = False
|
||||||
# stoploss order id which is on exchange
|
# stoploss order id which is on exchange
|
||||||
stoploss_order_id: Optional[str] = None
|
stoploss_order_id: Optional[str] = None
|
||||||
# last update time of the stoploss order on exchange
|
# last update time of the stoploss order on exchange
|
||||||
@@ -418,13 +434,20 @@ class LocalTrade:
|
|||||||
return self.amount
|
return self.amount
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def date_last_filled_utc(self) -> datetime:
|
def _date_last_filled_utc(self) -> Optional[datetime]:
|
||||||
""" Date of the last filled order"""
|
""" Date of the last filled order"""
|
||||||
orders = self.select_filled_orders()
|
orders = self.select_filled_orders()
|
||||||
if not orders:
|
if orders:
|
||||||
|
return max(o.order_filled_utc for o in orders if o.order_filled_utc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def date_last_filled_utc(self) -> datetime:
|
||||||
|
""" Date of the last filled order - or open_date if no orders are filled"""
|
||||||
|
dt_last_filled = self._date_last_filled_utc
|
||||||
|
if not dt_last_filled:
|
||||||
return self.open_date_utc
|
return self.open_date_utc
|
||||||
return max([self.open_date_utc,
|
return max([self.open_date_utc, dt_last_filled])
|
||||||
max(o.order_filled_utc for o in orders if o.order_filled_utc)])
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def open_date_utc(self):
|
def open_date_utc(self):
|
||||||
@@ -481,6 +504,32 @@ class LocalTrade:
|
|||||||
except IndexError:
|
except IndexError:
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
@property
|
||||||
|
def open_orders(self) -> List[Order]:
|
||||||
|
"""
|
||||||
|
All open orders for this trade excluding stoploss orders
|
||||||
|
"""
|
||||||
|
return [o for o in self.orders if o.ft_is_open and o.ft_order_side != 'stoploss']
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_open_orders(self) -> int:
|
||||||
|
"""
|
||||||
|
True if there are open orders for this trade excluding stoploss orders
|
||||||
|
"""
|
||||||
|
open_orders_wo_sl = [
|
||||||
|
o for o in self.orders
|
||||||
|
if o.ft_order_side not in ['stoploss'] and o.ft_is_open
|
||||||
|
]
|
||||||
|
return len(open_orders_wo_sl) > 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def open_orders_ids(self) -> List[str]:
|
||||||
|
open_orders_ids_wo_sl = [
|
||||||
|
oo.order_id for oo in self.open_orders
|
||||||
|
if oo.ft_order_side not in ['stoploss']
|
||||||
|
]
|
||||||
|
return open_orders_ids_wo_sl
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
for key in kwargs:
|
for key in kwargs:
|
||||||
setattr(self, key, kwargs[key])
|
setattr(self, key, kwargs[key])
|
||||||
@@ -499,8 +548,8 @@ class LocalTrade:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def to_json(self, minified: bool = False) -> Dict[str, Any]:
|
def to_json(self, minified: bool = False) -> Dict[str, Any]:
|
||||||
filled_orders = self.select_filled_or_open_orders()
|
filled_or_open_orders = self.select_filled_or_open_orders()
|
||||||
orders = [order.to_json(self.entry_side, minified) for order in filled_orders]
|
orders_json = [order.to_json(self.entry_side, minified) for order in filled_or_open_orders]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'trade_id': self.id,
|
'trade_id': self.id,
|
||||||
@@ -576,11 +625,12 @@ class LocalTrade:
|
|||||||
'is_short': self.is_short,
|
'is_short': self.is_short,
|
||||||
'trading_mode': self.trading_mode,
|
'trading_mode': self.trading_mode,
|
||||||
'funding_fees': self.funding_fees,
|
'funding_fees': self.funding_fees,
|
||||||
'open_order_id': self.open_order_id,
|
|
||||||
'amount_precision': self.amount_precision,
|
'amount_precision': self.amount_precision,
|
||||||
'price_precision': self.price_precision,
|
'price_precision': self.price_precision,
|
||||||
'precision_mode': self.precision_mode,
|
'precision_mode': self.precision_mode,
|
||||||
'orders': orders,
|
'contract_size': self.contract_size,
|
||||||
|
'has_open_orders': self.has_open_orders,
|
||||||
|
'orders': orders_json,
|
||||||
}
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -621,18 +671,18 @@ class LocalTrade:
|
|||||||
self.stop_loss_pct = -1 * abs(percent)
|
self.stop_loss_pct = -1 * abs(percent)
|
||||||
|
|
||||||
def adjust_stop_loss(self, current_price: float, stoploss: Optional[float],
|
def adjust_stop_loss(self, current_price: float, stoploss: Optional[float],
|
||||||
initial: bool = False, refresh: bool = False) -> None:
|
initial: bool = False, allow_refresh: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
This adjusts the stop loss to it's most recently observed setting
|
This adjusts the stop loss to it's most recently observed setting
|
||||||
:param current_price: Current rate the asset is traded
|
:param current_price: Current rate the asset is traded
|
||||||
:param stoploss: Stoploss as factor (sample -0.05 -> -5% below current price).
|
:param stoploss: Stoploss as factor (sample -0.05 -> -5% below current price).
|
||||||
:param initial: Called to initiate stop_loss.
|
:param initial: Called to initiate stop_loss.
|
||||||
Skips everything if self.stop_loss is already set.
|
Skips everything if self.stop_loss is already set.
|
||||||
|
:param refresh: Called to refresh stop_loss, allows adjustment in both directions
|
||||||
"""
|
"""
|
||||||
if stoploss is None or (initial and not (self.stop_loss is None or self.stop_loss == 0)):
|
if stoploss is None or (initial and not (self.stop_loss is None or self.stop_loss == 0)):
|
||||||
# Don't modify if called with initial and nothing to do
|
# Don't modify if called with initial and nothing to do
|
||||||
return
|
return
|
||||||
refresh = True if refresh and self.nr_of_successful_entries == 1 else False
|
|
||||||
|
|
||||||
leverage = self.leverage or 1.0
|
leverage = self.leverage or 1.0
|
||||||
if self.is_short:
|
if self.is_short:
|
||||||
@@ -643,7 +693,7 @@ class LocalTrade:
|
|||||||
stop_loss_norm = price_to_precision(new_loss, self.price_precision, self.precision_mode,
|
stop_loss_norm = price_to_precision(new_loss, self.price_precision, self.precision_mode,
|
||||||
rounding_mode=ROUND_DOWN if self.is_short else ROUND_UP)
|
rounding_mode=ROUND_DOWN if self.is_short else ROUND_UP)
|
||||||
# no stop loss assigned yet
|
# no stop loss assigned yet
|
||||||
if self.initial_stop_loss_pct is None or refresh:
|
if self.initial_stop_loss_pct is None:
|
||||||
self.__set_stop_loss(stop_loss_norm, stoploss)
|
self.__set_stop_loss(stop_loss_norm, stoploss)
|
||||||
self.initial_stop_loss = price_to_precision(
|
self.initial_stop_loss = price_to_precision(
|
||||||
stop_loss_norm, self.price_precision, self.precision_mode,
|
stop_loss_norm, self.price_precision, self.precision_mode,
|
||||||
@@ -658,8 +708,14 @@ class LocalTrade:
|
|||||||
# stop losses only walk up, never down!,
|
# stop losses only walk up, never down!,
|
||||||
# ? But adding more to a leveraged trade would create a lower liquidation price,
|
# ? But adding more to a leveraged trade would create a lower liquidation price,
|
||||||
# ? decreasing the minimum stoploss
|
# ? decreasing the minimum stoploss
|
||||||
if (higher_stop and not self.is_short) or (lower_stop and self.is_short):
|
if (
|
||||||
|
allow_refresh
|
||||||
|
or (higher_stop and not self.is_short)
|
||||||
|
or (lower_stop and self.is_short)
|
||||||
|
):
|
||||||
logger.debug(f"{self.pair} - Adjusting stoploss...")
|
logger.debug(f"{self.pair} - Adjusting stoploss...")
|
||||||
|
if not allow_refresh:
|
||||||
|
self.is_stop_loss_trailing = True
|
||||||
self.__set_stop_loss(stop_loss_norm, stoploss)
|
self.__set_stop_loss(stop_loss_norm, stoploss)
|
||||||
else:
|
else:
|
||||||
logger.debug(f"{self.pair} - Keeping current stoploss...")
|
logger.debug(f"{self.pair} - Keeping current stoploss...")
|
||||||
@@ -672,7 +728,7 @@ class LocalTrade:
|
|||||||
f"Trailing stoploss saved us: "
|
f"Trailing stoploss saved us: "
|
||||||
f"{float(self.stop_loss) - float(self.initial_stop_loss or 0.0):.8f}.")
|
f"{float(self.stop_loss) - float(self.initial_stop_loss or 0.0):.8f}.")
|
||||||
|
|
||||||
def update_trade(self, order: Order) -> None:
|
def update_trade(self, order: Order, recalculating: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Updates this entity with amount and actual open/close rates.
|
Updates this entity with amount and actual open/close rates.
|
||||||
:param order: order retrieved by exchange.fetch_order()
|
:param order: order retrieved by exchange.fetch_order()
|
||||||
@@ -692,24 +748,13 @@ class LocalTrade:
|
|||||||
if self.is_open:
|
if self.is_open:
|
||||||
payment = "SELL" if self.is_short else "BUY"
|
payment = "SELL" if self.is_short else "BUY"
|
||||||
logger.info(f'{order.order_type.upper()}_{payment} has been fulfilled for {self}.')
|
logger.info(f'{order.order_type.upper()}_{payment} has been fulfilled for {self}.')
|
||||||
# condition to avoid reset value when updating fees
|
|
||||||
if self.open_order_id == order.order_id:
|
|
||||||
self.open_order_id = None
|
|
||||||
else:
|
|
||||||
logger.warning(
|
|
||||||
f'Got different open_order_id {self.open_order_id} != {order.order_id}')
|
|
||||||
self.recalc_trade_from_orders()
|
self.recalc_trade_from_orders()
|
||||||
elif order.ft_order_side == self.exit_side:
|
elif order.ft_order_side == self.exit_side:
|
||||||
if self.is_open:
|
if self.is_open:
|
||||||
payment = "BUY" if self.is_short else "SELL"
|
payment = "BUY" if self.is_short else "SELL"
|
||||||
# * On margin shorts, you buy a little bit more than the amount (amount + interest)
|
# * On margin shorts, you buy a little bit more than the amount (amount + interest)
|
||||||
logger.info(f'{order.order_type.upper()}_{payment} has been fulfilled for {self}.')
|
logger.info(f'{order.order_type.upper()}_{payment} has been fulfilled for {self}.')
|
||||||
# condition to avoid reset value when updating fees
|
|
||||||
if self.open_order_id == order.order_id:
|
|
||||||
self.open_order_id = None
|
|
||||||
else:
|
|
||||||
logger.warning(
|
|
||||||
f'Got different open_order_id {self.open_order_id} != {order.order_id}')
|
|
||||||
|
|
||||||
elif order.ft_order_side == 'stoploss' and order.status not in ('open', ):
|
elif order.ft_order_side == 'stoploss' and order.status not in ('open', ):
|
||||||
self.stoploss_order_id = None
|
self.stoploss_order_id = None
|
||||||
@@ -725,8 +770,9 @@ class LocalTrade:
|
|||||||
self.precision_mode, self.contract_size)
|
self.precision_mode, self.contract_size)
|
||||||
if (
|
if (
|
||||||
isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC)
|
isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC)
|
||||||
or order.safe_amount_after_fee > amount_tr
|
or (not recalculating and order.safe_amount_after_fee > amount_tr)
|
||||||
):
|
):
|
||||||
|
# When recalculating a trade, only comming out to 0 can force a close
|
||||||
self.close(order.safe_price)
|
self.close(order.safe_price)
|
||||||
else:
|
else:
|
||||||
self.recalc_trade_from_orders()
|
self.recalc_trade_from_orders()
|
||||||
@@ -739,10 +785,9 @@ class LocalTrade:
|
|||||||
and marks trade as closed
|
and marks trade as closed
|
||||||
"""
|
"""
|
||||||
self.close_rate = rate
|
self.close_rate = rate
|
||||||
self.close_date = self.close_date or datetime.utcnow()
|
self.close_date = self.close_date or self._date_last_filled_utc or dt_now()
|
||||||
self.is_open = False
|
self.is_open = False
|
||||||
self.exit_order_status = 'closed'
|
self.exit_order_status = 'closed'
|
||||||
self.open_order_id = None
|
|
||||||
self.recalc_trade_from_orders(is_closing=True)
|
self.recalc_trade_from_orders(is_closing=True)
|
||||||
if show_msg:
|
if show_msg:
|
||||||
logger.info(f"Marking {self} as closed as the trade is fulfilled "
|
logger.info(f"Marking {self} as closed as the trade is fulfilled "
|
||||||
@@ -780,12 +825,13 @@ class LocalTrade:
|
|||||||
def update_order(self, order: Dict) -> None:
|
def update_order(self, order: Dict) -> None:
|
||||||
Order.update_orders(self.orders, order)
|
Order.update_orders(self.orders, order)
|
||||||
|
|
||||||
def get_exit_order_count(self) -> int:
|
def get_canceled_exit_order_count(self) -> int:
|
||||||
"""
|
"""
|
||||||
Get amount of failed exiting orders
|
Get amount of failed exiting orders
|
||||||
assumes full exits.
|
assumes full exits.
|
||||||
"""
|
"""
|
||||||
return len([o for o in self.orders if o.ft_order_side == self.exit_side])
|
return len([o for o in self.orders if o.ft_order_side == self.exit_side
|
||||||
|
and o.status in CANCELED_EXCHANGE_STATES])
|
||||||
|
|
||||||
def _calc_open_trade_value(self, amount: float, open_rate: float) -> float:
|
def _calc_open_trade_value(self, amount: float, open_rate: float) -> float:
|
||||||
"""
|
"""
|
||||||
@@ -878,11 +924,26 @@ class LocalTrade:
|
|||||||
open_rate: Optional[float] = None) -> float:
|
open_rate: Optional[float] = None) -> float:
|
||||||
"""
|
"""
|
||||||
Calculate the absolute profit in stake currency between Close and Open trade
|
Calculate the absolute profit in stake currency between Close and Open trade
|
||||||
|
Deprecated - only available for backwards compatibility
|
||||||
:param rate: close rate to compare with.
|
:param rate: close rate to compare with.
|
||||||
:param amount: Amount to use for the calculation. Falls back to trade.amount if not set.
|
:param amount: Amount to use for the calculation. Falls back to trade.amount if not set.
|
||||||
:param open_rate: open_rate to use. Defaults to self.open_rate if not provided.
|
:param open_rate: open_rate to use. Defaults to self.open_rate if not provided.
|
||||||
:return: profit in stake currency as float
|
:return: profit in stake currency as float
|
||||||
"""
|
"""
|
||||||
|
prof = self.calculate_profit(rate, amount, open_rate)
|
||||||
|
return prof.profit_abs
|
||||||
|
|
||||||
|
def calculate_profit(self, rate: float, amount: Optional[float] = None,
|
||||||
|
open_rate: Optional[float] = None) -> ProfitStruct:
|
||||||
|
"""
|
||||||
|
Calculate profit metrics (absolute, ratio, total, total ratio).
|
||||||
|
All calculations include fees.
|
||||||
|
:param rate: close rate to compare with.
|
||||||
|
:param amount: Amount to use for the calculation. Falls back to trade.amount if not set.
|
||||||
|
:param open_rate: open_rate to use. Defaults to self.open_rate if not provided.
|
||||||
|
:return: Profit structure, containing absolute and relative profits.
|
||||||
|
"""
|
||||||
|
|
||||||
close_trade_value = self.calc_close_trade_value(rate, amount)
|
close_trade_value = self.calc_close_trade_value(rate, amount)
|
||||||
if amount is None or open_rate is None:
|
if amount is None or open_rate is None:
|
||||||
open_trade_value = self.open_trade_value
|
open_trade_value = self.open_trade_value
|
||||||
@@ -890,10 +951,33 @@ class LocalTrade:
|
|||||||
open_trade_value = self._calc_open_trade_value(amount, open_rate)
|
open_trade_value = self._calc_open_trade_value(amount, open_rate)
|
||||||
|
|
||||||
if self.is_short:
|
if self.is_short:
|
||||||
profit = open_trade_value - close_trade_value
|
profit_abs = open_trade_value - close_trade_value
|
||||||
else:
|
else:
|
||||||
profit = close_trade_value - open_trade_value
|
profit_abs = close_trade_value - open_trade_value
|
||||||
return float(f"{profit:.8f}")
|
|
||||||
|
try:
|
||||||
|
if self.is_short:
|
||||||
|
profit_ratio = (1 - (close_trade_value / open_trade_value)) * self.leverage
|
||||||
|
else:
|
||||||
|
profit_ratio = ((close_trade_value / open_trade_value) - 1) * self.leverage
|
||||||
|
profit_ratio = float(f"{profit_ratio:.8f}")
|
||||||
|
except ZeroDivisionError:
|
||||||
|
profit_ratio = 0.0
|
||||||
|
|
||||||
|
total_profit_abs = profit_abs + self.realized_profit
|
||||||
|
total_profit_ratio = (
|
||||||
|
(total_profit_abs / self.max_stake_amount) * self.leverage
|
||||||
|
if self.max_stake_amount else 0.0
|
||||||
|
)
|
||||||
|
total_profit_ratio = float(f"{total_profit_ratio:.8f}")
|
||||||
|
profit_abs = float(f"{profit_abs:.8f}")
|
||||||
|
|
||||||
|
return ProfitStruct(
|
||||||
|
profit_abs=profit_abs,
|
||||||
|
profit_ratio=profit_ratio,
|
||||||
|
total_profit=profit_abs + self.realized_profit,
|
||||||
|
total_profit_ratio=total_profit_ratio,
|
||||||
|
)
|
||||||
|
|
||||||
def calc_profit_ratio(
|
def calc_profit_ratio(
|
||||||
self, rate: float, amount: Optional[float] = None,
|
self, rate: float, amount: Optional[float] = None,
|
||||||
@@ -914,15 +998,14 @@ class LocalTrade:
|
|||||||
|
|
||||||
short_close_zero = (self.is_short and close_trade_value == 0.0)
|
short_close_zero = (self.is_short and close_trade_value == 0.0)
|
||||||
long_close_zero = (not self.is_short and open_trade_value == 0.0)
|
long_close_zero = (not self.is_short and open_trade_value == 0.0)
|
||||||
leverage = self.leverage or 1.0
|
|
||||||
|
|
||||||
if (short_close_zero or long_close_zero):
|
if (short_close_zero or long_close_zero):
|
||||||
return 0.0
|
return 0.0
|
||||||
else:
|
else:
|
||||||
if self.is_short:
|
if self.is_short:
|
||||||
profit_ratio = (1 - (close_trade_value / open_trade_value)) * leverage
|
profit_ratio = (1 - (close_trade_value / open_trade_value)) * self.leverage
|
||||||
else:
|
else:
|
||||||
profit_ratio = ((close_trade_value / open_trade_value) - 1) * leverage
|
profit_ratio = ((close_trade_value / open_trade_value) - 1) * self.leverage
|
||||||
|
|
||||||
return float(f"{profit_ratio:.8f}")
|
return float(f"{profit_ratio:.8f}")
|
||||||
|
|
||||||
@@ -935,7 +1018,6 @@ class LocalTrade:
|
|||||||
avg_price = FtPrecise(0.0)
|
avg_price = FtPrecise(0.0)
|
||||||
close_profit = 0.0
|
close_profit = 0.0
|
||||||
close_profit_abs = 0.0
|
close_profit_abs = 0.0
|
||||||
profit = None
|
|
||||||
# Reset funding fees
|
# Reset funding fees
|
||||||
self.funding_fees = 0.0
|
self.funding_fees = 0.0
|
||||||
funding_fees = 0.0
|
funding_fees = 0.0
|
||||||
@@ -965,11 +1047,9 @@ class LocalTrade:
|
|||||||
|
|
||||||
exit_rate = o.safe_price
|
exit_rate = o.safe_price
|
||||||
exit_amount = o.safe_amount_after_fee
|
exit_amount = o.safe_amount_after_fee
|
||||||
profit = self.calc_profit(rate=exit_rate, amount=exit_amount,
|
prof = self.calculate_profit(exit_rate, exit_amount, float(avg_price))
|
||||||
open_rate=float(avg_price))
|
close_profit_abs += prof.profit_abs
|
||||||
close_profit_abs += profit
|
close_profit = prof.profit_ratio
|
||||||
close_profit = self.calc_profit_ratio(
|
|
||||||
exit_rate, amount=exit_amount, open_rate=avg_price)
|
|
||||||
else:
|
else:
|
||||||
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
|
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
|
||||||
max_stake_amount += (tmp_amount * price)
|
max_stake_amount += (tmp_amount * price)
|
||||||
@@ -979,7 +1059,7 @@ class LocalTrade:
|
|||||||
if close_profit:
|
if close_profit:
|
||||||
self.close_profit = close_profit
|
self.close_profit = close_profit
|
||||||
self.realized_profit = close_profit_abs
|
self.realized_profit = close_profit_abs
|
||||||
self.close_profit_abs = profit
|
self.close_profit_abs = prof.profit_abs
|
||||||
|
|
||||||
current_amount_tr = amount_to_contract_precision(
|
current_amount_tr = amount_to_contract_precision(
|
||||||
float(current_amount), self.amount_precision, self.precision_mode, self.contract_size)
|
float(current_amount), self.amount_precision, self.precision_mode, self.contract_size)
|
||||||
@@ -1194,7 +1274,7 @@ class LocalTrade:
|
|||||||
logger.info(f"Found open trade: {trade}")
|
logger.info(f"Found open trade: {trade}")
|
||||||
|
|
||||||
# skip case if trailing-stop changed the stoploss already.
|
# skip case if trailing-stop changed the stoploss already.
|
||||||
if (trade.stop_loss == trade.initial_stop_loss
|
if (not trade.is_stop_loss_trailing
|
||||||
and trade.initial_stop_loss_pct != desired_stoploss):
|
and trade.initial_stop_loss_pct != desired_stoploss):
|
||||||
# Stoploss value got changed
|
# Stoploss value got changed
|
||||||
|
|
||||||
@@ -1256,7 +1336,6 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
open_date: Mapped[datetime] = mapped_column(
|
open_date: Mapped[datetime] = mapped_column(
|
||||||
nullable=False, default=datetime.utcnow) # type: ignore
|
nullable=False, default=datetime.utcnow) # type: ignore
|
||||||
close_date: Mapped[Optional[datetime]] = mapped_column() # type: ignore
|
close_date: Mapped[Optional[datetime]] = mapped_column() # type: ignore
|
||||||
open_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # type: ignore
|
|
||||||
# absolute value of the stop loss
|
# absolute value of the stop loss
|
||||||
stop_loss: Mapped[float] = mapped_column(Float(), nullable=True, default=0.0) # type: ignore
|
stop_loss: Mapped[float] = mapped_column(Float(), nullable=True, default=0.0) # type: ignore
|
||||||
# percentage value of the stop loss
|
# percentage value of the stop loss
|
||||||
@@ -1267,6 +1346,8 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
# percentage value of the initial stop loss
|
# percentage value of the initial stop loss
|
||||||
initial_stop_loss_pct: Mapped[Optional[float]] = mapped_column(
|
initial_stop_loss_pct: Mapped[Optional[float]] = mapped_column(
|
||||||
Float(), nullable=True) # type: ignore
|
Float(), nullable=True) # type: ignore
|
||||||
|
is_stop_loss_trailing: Mapped[bool] = mapped_column(
|
||||||
|
nullable=False, default=False) # type: ignore
|
||||||
# stoploss order id which is on exchange
|
# stoploss order id which is on exchange
|
||||||
stoploss_order_id: Mapped[Optional[str]] = mapped_column(
|
stoploss_order_id: Mapped[Optional[str]] = mapped_column(
|
||||||
String(255), nullable=True, index=True) # type: ignore
|
String(255), nullable=True, index=True) # type: ignore
|
||||||
@@ -1411,14 +1492,6 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
# raise an exception.
|
# raise an exception.
|
||||||
return Trade.session.scalars(query)
|
return Trade.session.scalars(query)
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def get_open_order_trades() -> List['Trade']:
|
|
||||||
"""
|
|
||||||
Returns all open trades
|
|
||||||
NOTE: Not supported in Backtesting.
|
|
||||||
"""
|
|
||||||
return cast(List[Trade], Trade.get_trades(Trade.open_order_id.isnot(None)).all())
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_open_trades_without_assigned_fees():
|
def get_open_trades_without_assigned_fees():
|
||||||
"""
|
"""
|
||||||
@@ -1717,7 +1790,10 @@ class Trade(ModelBase, LocalTrade):
|
|||||||
is_short=data["is_short"],
|
is_short=data["is_short"],
|
||||||
trading_mode=data["trading_mode"],
|
trading_mode=data["trading_mode"],
|
||||||
funding_fees=data["funding_fees"],
|
funding_fees=data["funding_fees"],
|
||||||
open_order_id=data["open_order_id"],
|
amount_precision=data.get('amount_precision', None),
|
||||||
|
price_precision=data.get('price_precision', None),
|
||||||
|
precision_mode=data.get('precision_mode', None),
|
||||||
|
contract_size=data.get('contract_size', None),
|
||||||
)
|
)
|
||||||
for order in data["orders"]:
|
for order in data["orders"]:
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""
|
||||||
|
Full trade slots pair list filter
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from freqtrade.constants import Config
|
||||||
|
from freqtrade.exchange.types import Tickers
|
||||||
|
from freqtrade.persistence import Trade
|
||||||
|
from freqtrade.plugins.pairlist.IPairList import IPairList
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class FullTradesFilter(IPairList):
|
||||||
|
|
||||||
|
def __init__(self, exchange, pairlistmanager,
|
||||||
|
config: Config, pairlistconfig: Dict[str, Any],
|
||||||
|
pairlist_pos: int) -> None:
|
||||||
|
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def needstickers(self) -> bool:
|
||||||
|
"""
|
||||||
|
Boolean property defining if tickers are necessary.
|
||||||
|
If no Pairlist requires tickers, an empty List is passed
|
||||||
|
as tickers argument to filter_pairlist
|
||||||
|
"""
|
||||||
|
return False
|
||||||
|
|
||||||
|
def short_desc(self) -> str:
|
||||||
|
"""
|
||||||
|
Short allowlist method description - used for startup-messages
|
||||||
|
"""
|
||||||
|
return f"{self.name} - Shrink whitelist when trade slots are full."
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def description() -> str:
|
||||||
|
return "Shrink whitelist when trade slots are full."
|
||||||
|
|
||||||
|
def filter_pairlist(self, pairlist: List[str], tickers: Tickers) -> List[str]:
|
||||||
|
"""
|
||||||
|
Filters and sorts pairlist and returns the allowlist again.
|
||||||
|
Called on each bot iteration - please use internal caching if necessary
|
||||||
|
:param pairlist: pairlist to filter or sort
|
||||||
|
:param tickers: Tickers (from exchange.get_tickers). May be cached.
|
||||||
|
:return: new allowlist
|
||||||
|
"""
|
||||||
|
# Get the number of open trades and max open trades config
|
||||||
|
num_open = Trade.get_open_trade_count()
|
||||||
|
max_trades = self._config['max_open_trades']
|
||||||
|
|
||||||
|
if (num_open >= max_trades) and (max_trades > 0):
|
||||||
|
return []
|
||||||
|
|
||||||
|
return pairlist
|
||||||
@@ -260,6 +260,7 @@ class VolumePairList(IPairList):
|
|||||||
quoteVolume = (pair_candles['quoteVolume']
|
quoteVolume = (pair_candles['quoteVolume']
|
||||||
.rolling(self._lookback_period)
|
.rolling(self._lookback_period)
|
||||||
.sum()
|
.sum()
|
||||||
|
.fillna(0)
|
||||||
.iloc[-1])
|
.iloc[-1])
|
||||||
|
|
||||||
# replace quoteVolume with range quoteVolume sum calculated above
|
# replace quoteVolume with range quoteVolume sum calculated above
|
||||||
|
|||||||
@@ -29,9 +29,8 @@ def expand_pairlist(wildcardpl: List[str], available_pairs: List[str],
|
|||||||
except re.error as err:
|
except re.error as err:
|
||||||
raise ValueError(f"Wildcard error in {pair_wc}, {err}")
|
raise ValueError(f"Wildcard error in {pair_wc}, {err}")
|
||||||
|
|
||||||
for element in result:
|
result = [element for element in result if re.fullmatch(r'^[A-Za-z0-9:/-]+$', element)]
|
||||||
if not re.fullmatch(r'^[A-Za-z0-9/-]+$', element):
|
|
||||||
result.remove(element)
|
|
||||||
else:
|
else:
|
||||||
for pair_wc in wildcardpl:
|
for pair_wc in wildcardpl:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ class RangeStabilityFilter(IPairList):
|
|||||||
self._days = pairlistconfig.get('lookback_days', 10)
|
self._days = pairlistconfig.get('lookback_days', 10)
|
||||||
self._min_rate_of_change = pairlistconfig.get('min_rate_of_change', 0.01)
|
self._min_rate_of_change = pairlistconfig.get('min_rate_of_change', 0.01)
|
||||||
self._max_rate_of_change = pairlistconfig.get('max_rate_of_change')
|
self._max_rate_of_change = pairlistconfig.get('max_rate_of_change')
|
||||||
self._refresh_period = pairlistconfig.get('refresh_period', 1440)
|
self._refresh_period = pairlistconfig.get('refresh_period', 86400)
|
||||||
self._def_candletype = self._config['candle_type_def']
|
self._def_candletype = self._config['candle_type_def']
|
||||||
|
|
||||||
self._pair_cache: TTLCache = TTLCache(maxsize=1000, ttl=self._refresh_period)
|
self._pair_cache: TTLCache = TTLCache(maxsize=1000, ttl=self._refresh_period)
|
||||||
|
|||||||
@@ -218,6 +218,12 @@ class StrategyResolver(IResolver):
|
|||||||
"Please update your strategy to implement "
|
"Please update your strategy to implement "
|
||||||
"`populate_indicators`, `populate_entry_trend` and `populate_exit_trend` "
|
"`populate_indicators`, `populate_entry_trend` and `populate_exit_trend` "
|
||||||
"with the metadata argument. ")
|
"with the metadata argument. ")
|
||||||
|
|
||||||
|
has_after_fill = ('after_fill' in getfullargspec(strategy.custom_stoploss).args
|
||||||
|
and check_override(strategy, IStrategy, 'custom_stoploss'))
|
||||||
|
if has_after_fill:
|
||||||
|
strategy._ft_stop_uses_after_fill = True
|
||||||
|
|
||||||
return strategy
|
return strategy
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -141,6 +141,10 @@ class Profit(BaseModel):
|
|||||||
expectancy_ratio: float
|
expectancy_ratio: float
|
||||||
max_drawdown: float
|
max_drawdown: float
|
||||||
max_drawdown_abs: float
|
max_drawdown_abs: float
|
||||||
|
max_drawdown_start: str
|
||||||
|
max_drawdown_start_timestamp: int
|
||||||
|
max_drawdown_end: str
|
||||||
|
max_drawdown_end_timestamp: int
|
||||||
trading_volume: Optional[float] = None
|
trading_volume: Optional[float] = None
|
||||||
bot_start_timestamp: int
|
bot_start_timestamp: int
|
||||||
bot_start_date: str
|
bot_start_date: str
|
||||||
@@ -157,7 +161,7 @@ class Stats(BaseModel):
|
|||||||
durations: Dict[str, Optional[float]]
|
durations: Dict[str, Optional[float]]
|
||||||
|
|
||||||
|
|
||||||
class DailyRecord(BaseModel):
|
class DailyWeeklyMonthlyRecord(BaseModel):
|
||||||
date: date
|
date: date
|
||||||
abs_profit: float
|
abs_profit: float
|
||||||
rel_profit: float
|
rel_profit: float
|
||||||
@@ -166,8 +170,8 @@ class DailyRecord(BaseModel):
|
|||||||
trade_count: int
|
trade_count: int
|
||||||
|
|
||||||
|
|
||||||
class Daily(BaseModel):
|
class DailyWeeklyMonthly(BaseModel):
|
||||||
data: List[DailyRecord]
|
data: List[DailyWeeklyMonthlyRecord]
|
||||||
fiat_display_currency: str
|
fiat_display_currency: str
|
||||||
stake_currency: str
|
stake_currency: str
|
||||||
|
|
||||||
@@ -304,7 +308,7 @@ class TradeSchema(BaseModel):
|
|||||||
|
|
||||||
min_rate: Optional[float] = None
|
min_rate: Optional[float] = None
|
||||||
max_rate: Optional[float] = None
|
max_rate: Optional[float] = None
|
||||||
open_order_id: Optional[str] = None
|
has_open_orders: bool
|
||||||
orders: List[OrderSchema]
|
orders: List[OrderSchema]
|
||||||
|
|
||||||
leverage: Optional[float] = None
|
leverage: Optional[float] = None
|
||||||
@@ -329,8 +333,6 @@ class OpenTradeSchema(TradeSchema):
|
|||||||
total_profit_fiat: Optional[float] = None
|
total_profit_fiat: Optional[float] = None
|
||||||
total_profit_ratio: Optional[float] = None
|
total_profit_ratio: Optional[float] = None
|
||||||
|
|
||||||
open_order: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class TradeResponse(BaseModel):
|
class TradeResponse(BaseModel):
|
||||||
trades: List[TradeSchema]
|
trades: List[TradeSchema]
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from freqtrade.enums import CandleType, TradingMode
|
|||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.rpc import RPC
|
from freqtrade.rpc import RPC
|
||||||
from freqtrade.rpc.api_server.api_schemas import (AvailablePairs, Balances, BlacklistPayload,
|
from freqtrade.rpc.api_server.api_schemas import (AvailablePairs, Balances, BlacklistPayload,
|
||||||
BlacklistResponse, Count, Daily,
|
BlacklistResponse, Count, DailyWeeklyMonthly,
|
||||||
DeleteLockRequest, DeleteTrade,
|
DeleteLockRequest, DeleteTrade,
|
||||||
ExchangeListResponse, ForceEnterPayload,
|
ExchangeListResponse, ForceEnterPayload,
|
||||||
ForceEnterResponse, ForceExitPayload,
|
ForceEnterResponse, ForceExitPayload,
|
||||||
@@ -51,7 +51,8 @@ logger = logging.getLogger(__name__)
|
|||||||
# 2.30: new /pairlists endpoint
|
# 2.30: new /pairlists endpoint
|
||||||
# 2.31: new /backtest/history/ delete endpoint
|
# 2.31: new /backtest/history/ delete endpoint
|
||||||
# 2.32: new /backtest/history/ patch endpoint
|
# 2.32: new /backtest/history/ patch endpoint
|
||||||
API_VERSION = 2.32
|
# 2.33: Additional weekly/monthly metrics
|
||||||
|
API_VERSION = 2.33
|
||||||
|
|
||||||
# Public API, requires no auth.
|
# Public API, requires no auth.
|
||||||
router_public = APIRouter()
|
router_public = APIRouter()
|
||||||
@@ -99,12 +100,24 @@ def stats(rpc: RPC = Depends(get_rpc)):
|
|||||||
return rpc._rpc_stats()
|
return rpc._rpc_stats()
|
||||||
|
|
||||||
|
|
||||||
@router.get('/daily', response_model=Daily, tags=['info'])
|
@router.get('/daily', response_model=DailyWeeklyMonthly, tags=['info'])
|
||||||
def daily(timescale: int = 7, rpc: RPC = Depends(get_rpc), config=Depends(get_config)):
|
def daily(timescale: int = 7, rpc: RPC = Depends(get_rpc), config=Depends(get_config)):
|
||||||
return rpc._rpc_timeunit_profit(timescale, config['stake_currency'],
|
return rpc._rpc_timeunit_profit(timescale, config['stake_currency'],
|
||||||
config.get('fiat_display_currency', ''))
|
config.get('fiat_display_currency', ''))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/weekly', response_model=DailyWeeklyMonthly, tags=['info'])
|
||||||
|
def weekly(timescale: int = 4, rpc: RPC = Depends(get_rpc), config=Depends(get_config)):
|
||||||
|
return rpc._rpc_timeunit_profit(timescale, config['stake_currency'],
|
||||||
|
config.get('fiat_display_currency', ''), 'weeks')
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/monthly', response_model=DailyWeeklyMonthly, tags=['info'])
|
||||||
|
def monthly(timescale: int = 3, rpc: RPC = Depends(get_rpc), config=Depends(get_config)):
|
||||||
|
return rpc._rpc_timeunit_profit(timescale, config['stake_currency'],
|
||||||
|
config.get('fiat_display_currency', ''), 'months')
|
||||||
|
|
||||||
|
|
||||||
@router.get('/status', response_model=List[OpenTradeSchema], tags=['info'])
|
@router.get('/status', response_model=List[OpenTradeSchema], tags=['info'])
|
||||||
def status(rpc: RPC = Depends(get_rpc)):
|
def status(rpc: RPC = Depends(get_rpc)):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from pandas import DataFrame
|
|||||||
from pydantic import BaseModel, ConfigDict
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
from freqtrade.constants import PairWithTimeframe
|
from freqtrade.constants import PairWithTimeframe
|
||||||
from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType
|
from freqtrade.enums import RPCMessageType, RPCRequestType
|
||||||
|
|
||||||
|
|
||||||
class BaseArbitraryModel(BaseModel):
|
class BaseArbitraryModel(BaseModel):
|
||||||
|
|||||||
+98
-67
@@ -16,7 +16,7 @@ from sqlalchemy import func, select
|
|||||||
|
|
||||||
from freqtrade import __version__
|
from freqtrade import __version__
|
||||||
from freqtrade.configuration.timerange import TimeRange
|
from freqtrade.configuration.timerange import TimeRange
|
||||||
from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT, Config
|
from freqtrade.constants import CANCEL_REASON, Config
|
||||||
from freqtrade.data.history import load_data
|
from freqtrade.data.history import load_data
|
||||||
from freqtrade.data.metrics import calculate_expectancy, calculate_max_drawdown
|
from freqtrade.data.metrics import calculate_expectancy, calculate_max_drawdown
|
||||||
from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, MarketDirection, SignalDirection,
|
from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, MarketDirection, SignalDirection,
|
||||||
@@ -26,12 +26,12 @@ from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs
|
|||||||
from freqtrade.exchange.types import Tickers
|
from freqtrade.exchange.types import Tickers
|
||||||
from freqtrade.loggers import bufferHandler
|
from freqtrade.loggers import bufferHandler
|
||||||
from freqtrade.misc import decimals_per_coin
|
from freqtrade.misc import decimals_per_coin
|
||||||
from freqtrade.persistence import KeyStoreKeys, KeyValueStore, Order, PairLocks, Trade
|
from freqtrade.persistence import KeyStoreKeys, KeyValueStore, PairLocks, Trade
|
||||||
from freqtrade.persistence.models import PairLock
|
from freqtrade.persistence.models import PairLock
|
||||||
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
||||||
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
||||||
from freqtrade.rpc.rpc_types import RPCSendMsg
|
from freqtrade.rpc.rpc_types import RPCSendMsg
|
||||||
from freqtrade.util import dt_humanize, dt_now, shorten_date
|
from freqtrade.util import dt_humanize, dt_now, dt_ts_def, format_date, shorten_date
|
||||||
from freqtrade.wallets import PositionWallet, Wallet
|
from freqtrade.wallets import PositionWallet, Wallet
|
||||||
|
|
||||||
|
|
||||||
@@ -171,11 +171,20 @@ class RPC:
|
|||||||
else:
|
else:
|
||||||
results = []
|
results = []
|
||||||
for trade in trades:
|
for trade in trades:
|
||||||
order: Optional[Order] = None
|
|
||||||
current_profit_fiat: Optional[float] = None
|
current_profit_fiat: Optional[float] = None
|
||||||
total_profit_fiat: Optional[float] = None
|
total_profit_fiat: Optional[float] = None
|
||||||
if trade.open_order_id:
|
|
||||||
order = trade.select_order_by_order_id(trade.open_order_id)
|
# prepare open orders details
|
||||||
|
oo_details: Optional[str] = ""
|
||||||
|
oo_details_lst = [
|
||||||
|
f'({oo.order_type} {oo.side} rem={oo.safe_remaining:.8f})'
|
||||||
|
for oo in trade.open_orders
|
||||||
|
if oo.ft_order_side not in ['stoploss']
|
||||||
|
]
|
||||||
|
oo_details = ', '.join(oo_details_lst)
|
||||||
|
|
||||||
|
total_profit_abs = 0.0
|
||||||
|
total_profit_ratio: Optional[float] = None
|
||||||
# calculate profit and send message to user
|
# calculate profit and send message to user
|
||||||
if trade.is_open:
|
if trade.is_open:
|
||||||
try:
|
try:
|
||||||
@@ -184,23 +193,22 @@ class RPC:
|
|||||||
except (ExchangeError, PricingError):
|
except (ExchangeError, PricingError):
|
||||||
current_rate = NAN
|
current_rate = NAN
|
||||||
if len(trade.select_filled_orders(trade.entry_side)) > 0:
|
if len(trade.select_filled_orders(trade.entry_side)) > 0:
|
||||||
current_profit = trade.calc_profit_ratio(
|
|
||||||
current_rate) if not isnan(current_rate) else NAN
|
current_profit = current_profit_abs = current_profit_fiat = NAN
|
||||||
current_profit_abs = trade.calc_profit(
|
if not isnan(current_rate):
|
||||||
current_rate) if not isnan(current_rate) else NAN
|
prof = trade.calculate_profit(current_rate)
|
||||||
|
current_profit = prof.profit_ratio
|
||||||
|
current_profit_abs = prof.profit_abs
|
||||||
|
total_profit_abs = prof.total_profit
|
||||||
|
total_profit_ratio = prof.total_profit_ratio
|
||||||
else:
|
else:
|
||||||
current_profit = current_profit_abs = current_profit_fiat = 0.0
|
current_profit = current_profit_abs = current_profit_fiat = 0.0
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# Closed trade ...
|
# Closed trade ...
|
||||||
current_rate = trade.close_rate
|
current_rate = trade.close_rate
|
||||||
current_profit = trade.close_profit or 0.0
|
current_profit = trade.close_profit or 0.0
|
||||||
current_profit_abs = trade.close_profit_abs or 0.0
|
current_profit_abs = trade.close_profit_abs or 0.0
|
||||||
total_profit_abs = trade.realized_profit + current_profit_abs
|
|
||||||
total_profit_ratio: Optional[float] = None
|
|
||||||
if trade.max_stake_amount:
|
|
||||||
total_profit_ratio = (
|
|
||||||
(total_profit_abs / trade.max_stake_amount) * trade.leverage
|
|
||||||
)
|
|
||||||
|
|
||||||
# Calculate fiat profit
|
# Calculate fiat profit
|
||||||
if not isnan(current_profit_abs) and self._fiat_converter:
|
if not isnan(current_profit_abs) and self._fiat_converter:
|
||||||
@@ -216,8 +224,11 @@ class RPC:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Calculate guaranteed profit (in case of trailing stop)
|
# Calculate guaranteed profit (in case of trailing stop)
|
||||||
stoploss_entry_dist = trade.calc_profit(trade.stop_loss)
|
stop_entry = trade.calculate_profit(trade.stop_loss)
|
||||||
stoploss_entry_dist_ratio = trade.calc_profit_ratio(trade.stop_loss)
|
|
||||||
|
stoploss_entry_dist = stop_entry.profit_abs
|
||||||
|
stoploss_entry_dist_ratio = stop_entry.profit_ratio
|
||||||
|
|
||||||
# calculate distance to stoploss
|
# calculate distance to stoploss
|
||||||
stoploss_current_dist = trade.stop_loss - current_rate
|
stoploss_current_dist = trade.stop_loss - current_rate
|
||||||
stoploss_current_dist_ratio = stoploss_current_dist / current_rate
|
stoploss_current_dist_ratio = stoploss_current_dist / current_rate
|
||||||
@@ -230,7 +241,6 @@ class RPC:
|
|||||||
profit_pct=round(current_profit * 100, 2),
|
profit_pct=round(current_profit * 100, 2),
|
||||||
profit_abs=current_profit_abs,
|
profit_abs=current_profit_abs,
|
||||||
profit_fiat=current_profit_fiat,
|
profit_fiat=current_profit_fiat,
|
||||||
|
|
||||||
total_profit_abs=total_profit_abs,
|
total_profit_abs=total_profit_abs,
|
||||||
total_profit_fiat=total_profit_fiat,
|
total_profit_fiat=total_profit_fiat,
|
||||||
total_profit_ratio=total_profit_ratio,
|
total_profit_ratio=total_profit_ratio,
|
||||||
@@ -239,10 +249,7 @@ class RPC:
|
|||||||
stoploss_current_dist_pct=round(stoploss_current_dist_ratio * 100, 2),
|
stoploss_current_dist_pct=round(stoploss_current_dist_ratio * 100, 2),
|
||||||
stoploss_entry_dist=stoploss_entry_dist,
|
stoploss_entry_dist=stoploss_entry_dist,
|
||||||
stoploss_entry_dist_ratio=round(stoploss_entry_dist_ratio, 8),
|
stoploss_entry_dist_ratio=round(stoploss_entry_dist_ratio, 8),
|
||||||
open_order=(
|
open_orders=oo_details
|
||||||
f'({order.order_type} {order.side} rem={order.safe_remaining:.8f})' if
|
|
||||||
order else None
|
|
||||||
),
|
|
||||||
))
|
))
|
||||||
results.append(trade_dict)
|
results.append(trade_dict)
|
||||||
return results
|
return results
|
||||||
@@ -267,8 +274,9 @@ class RPC:
|
|||||||
profit_str = f'{NAN:.2%}'
|
profit_str = f'{NAN:.2%}'
|
||||||
else:
|
else:
|
||||||
if trade.nr_of_successful_entries > 0:
|
if trade.nr_of_successful_entries > 0:
|
||||||
trade_profit = trade.calc_profit(current_rate)
|
profit = trade.calculate_profit(current_rate)
|
||||||
profit_str = f'{trade.calc_profit_ratio(current_rate):.2%}'
|
trade_profit = profit.profit_abs
|
||||||
|
profit_str = f'{profit.profit_ratio:.2%}'
|
||||||
else:
|
else:
|
||||||
trade_profit = 0.0
|
trade_profit = 0.0
|
||||||
profit_str = f'{0.0:.2f}'
|
profit_str = f'{0.0:.2f}'
|
||||||
@@ -283,18 +291,22 @@ class RPC:
|
|||||||
profit_str += f" ({fiat_profit:.2f})"
|
profit_str += f" ({fiat_profit:.2f})"
|
||||||
fiat_profit_sum = fiat_profit if isnan(fiat_profit_sum) \
|
fiat_profit_sum = fiat_profit if isnan(fiat_profit_sum) \
|
||||||
else fiat_profit_sum + fiat_profit
|
else fiat_profit_sum + fiat_profit
|
||||||
open_order = (trade.select_order_by_order_id(
|
|
||||||
trade.open_order_id) if trade.open_order_id else None)
|
active_attempt_side_symbols = [
|
||||||
|
'*' if (oo and oo.ft_order_side == trade.entry_side) else '**'
|
||||||
|
for oo in trade.open_orders
|
||||||
|
]
|
||||||
|
|
||||||
|
# exemple: '*.**.**' trying to enter, exit and exit with 3 different orders
|
||||||
|
active_attempt_side_symbols_str = '.'.join(active_attempt_side_symbols)
|
||||||
|
|
||||||
detail_trade = [
|
detail_trade = [
|
||||||
f'{trade.id} {direction_str}',
|
f'{trade.id} {direction_str}',
|
||||||
trade.pair + ('*' if (open_order
|
trade.pair + active_attempt_side_symbols_str,
|
||||||
and open_order.ft_order_side == trade.entry_side) else '')
|
|
||||||
+ ('**' if (open_order and
|
|
||||||
open_order.ft_order_side == trade.exit_side is not None) else ''),
|
|
||||||
shorten_date(dt_humanize(trade.open_date, only_distance=True)),
|
shorten_date(dt_humanize(trade.open_date, only_distance=True)),
|
||||||
profit_str
|
profit_str
|
||||||
]
|
]
|
||||||
|
|
||||||
if self._config.get('position_adjustment_enable', False):
|
if self._config.get('position_adjustment_enable', False):
|
||||||
max_entry_str = ''
|
max_entry_str = ''
|
||||||
if self._config.get('max_entry_position_adjustment', -1) > 0:
|
if self._config.get('max_entry_position_adjustment', -1) > 0:
|
||||||
@@ -364,7 +376,7 @@ class RPC:
|
|||||||
|
|
||||||
data = [
|
data = [
|
||||||
{
|
{
|
||||||
'date': f"{key.year}-{key.month:02d}" if timeunit == 'months' else key,
|
'date': key,
|
||||||
'abs_profit': value["amount"],
|
'abs_profit': value["amount"],
|
||||||
'starting_balance': value["daily_stake"],
|
'starting_balance': value["daily_stake"],
|
||||||
'rel_profit': value["rel_profit"],
|
'rel_profit': value["rel_profit"],
|
||||||
@@ -487,9 +499,10 @@ class RPC:
|
|||||||
profit_ratio = NAN
|
profit_ratio = NAN
|
||||||
profit_abs = NAN
|
profit_abs = NAN
|
||||||
else:
|
else:
|
||||||
profit_ratio = trade.calc_profit_ratio(rate=current_rate)
|
profit = trade.calculate_profit(trade.close_rate or current_rate)
|
||||||
profit_abs = trade.calc_profit(
|
|
||||||
rate=trade.close_rate or current_rate) + trade.realized_profit
|
profit_ratio = profit.profit_ratio
|
||||||
|
profit_abs = profit.total_profit
|
||||||
|
|
||||||
profit_all_coin.append(profit_abs)
|
profit_all_coin.append(profit_abs)
|
||||||
profit_all_ratio.append(profit_ratio)
|
profit_all_ratio.append(profit_ratio)
|
||||||
@@ -525,7 +538,8 @@ class RPC:
|
|||||||
|
|
||||||
winrate = (winning_trades / closed_trade_count) if closed_trade_count > 0 else 0
|
winrate = (winning_trades / closed_trade_count) if closed_trade_count > 0 else 0
|
||||||
|
|
||||||
trades_df = DataFrame([{'close_date': trade.close_date.strftime(DATETIME_PRINT_FORMAT),
|
trades_df = DataFrame([{'close_date': format_date(trade.close_date),
|
||||||
|
'close_date_dt': trade.close_date,
|
||||||
'profit_abs': trade.close_profit_abs}
|
'profit_abs': trade.close_profit_abs}
|
||||||
for trade in trades if not trade.is_open and trade.close_date])
|
for trade in trades if not trade.is_open and trade.close_date])
|
||||||
|
|
||||||
@@ -533,10 +547,15 @@ class RPC:
|
|||||||
|
|
||||||
max_drawdown_abs = 0.0
|
max_drawdown_abs = 0.0
|
||||||
max_drawdown = 0.0
|
max_drawdown = 0.0
|
||||||
|
drawdown_start: Optional[datetime] = None
|
||||||
|
drawdown_end: Optional[datetime] = None
|
||||||
|
dd_high_val = dd_low_val = 0.0
|
||||||
if len(trades_df) > 0:
|
if len(trades_df) > 0:
|
||||||
try:
|
try:
|
||||||
(max_drawdown_abs, _, _, _, _, max_drawdown) = calculate_max_drawdown(
|
(max_drawdown_abs, drawdown_start, drawdown_end, dd_high_val, dd_low_val,
|
||||||
trades_df, value_col='profit_abs', starting_balance=starting_balance)
|
max_drawdown) = calculate_max_drawdown(
|
||||||
|
trades_df, value_col='profit_abs', date_col='close_date_dt',
|
||||||
|
starting_balance=starting_balance)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
# ValueError if no losing trade.
|
# ValueError if no losing trade.
|
||||||
pass
|
pass
|
||||||
@@ -570,12 +589,12 @@ class RPC:
|
|||||||
'profit_all_fiat': profit_all_fiat,
|
'profit_all_fiat': profit_all_fiat,
|
||||||
'trade_count': len(trades),
|
'trade_count': len(trades),
|
||||||
'closed_trade_count': closed_trade_count,
|
'closed_trade_count': closed_trade_count,
|
||||||
'first_trade_date': first_date.strftime(DATETIME_PRINT_FORMAT) if first_date else '',
|
'first_trade_date': format_date(first_date),
|
||||||
'first_trade_humanized': dt_humanize(first_date) if first_date else '',
|
'first_trade_humanized': dt_humanize(first_date) if first_date else '',
|
||||||
'first_trade_timestamp': int(first_date.timestamp() * 1000) if first_date else 0,
|
'first_trade_timestamp': dt_ts_def(first_date, 0),
|
||||||
'latest_trade_date': last_date.strftime(DATETIME_PRINT_FORMAT) if last_date else '',
|
'latest_trade_date': format_date(last_date),
|
||||||
'latest_trade_humanized': dt_humanize(last_date) if last_date else '',
|
'latest_trade_humanized': dt_humanize(last_date) if last_date else '',
|
||||||
'latest_trade_timestamp': int(last_date.timestamp() * 1000) if last_date else 0,
|
'latest_trade_timestamp': dt_ts_def(last_date, 0),
|
||||||
'avg_duration': str(timedelta(seconds=sum(durations) / num)).split('.')[0],
|
'avg_duration': str(timedelta(seconds=sum(durations) / num)).split('.')[0],
|
||||||
'best_pair': best_pair[0] if best_pair else '',
|
'best_pair': best_pair[0] if best_pair else '',
|
||||||
'best_rate': round(best_pair[1] * 100, 2) if best_pair else 0, # Deprecated
|
'best_rate': round(best_pair[1] * 100, 2) if best_pair else 0, # Deprecated
|
||||||
@@ -588,9 +607,15 @@ class RPC:
|
|||||||
'expectancy_ratio': expectancy_ratio,
|
'expectancy_ratio': expectancy_ratio,
|
||||||
'max_drawdown': max_drawdown,
|
'max_drawdown': max_drawdown,
|
||||||
'max_drawdown_abs': max_drawdown_abs,
|
'max_drawdown_abs': max_drawdown_abs,
|
||||||
|
'max_drawdown_start': format_date(drawdown_start),
|
||||||
|
'max_drawdown_start_timestamp': dt_ts_def(drawdown_start),
|
||||||
|
'max_drawdown_end': format_date(drawdown_end),
|
||||||
|
'max_drawdown_end_timestamp': dt_ts_def(drawdown_end),
|
||||||
|
'drawdown_high': dd_high_val,
|
||||||
|
'drawdown_low': dd_low_val,
|
||||||
'trading_volume': trading_volume,
|
'trading_volume': trading_volume,
|
||||||
'bot_start_timestamp': int(bot_start.timestamp() * 1000) if bot_start else 0,
|
'bot_start_timestamp': dt_ts_def(bot_start, 0),
|
||||||
'bot_start_date': bot_start.strftime(DATETIME_PRINT_FORMAT) if bot_start else '',
|
'bot_start_date': format_date(bot_start),
|
||||||
}
|
}
|
||||||
|
|
||||||
def __balance_get_est_stake(
|
def __balance_get_est_stake(
|
||||||
@@ -762,21 +787,25 @@ class RPC:
|
|||||||
|
|
||||||
def __exec_force_exit(self, trade: Trade, ordertype: Optional[str],
|
def __exec_force_exit(self, trade: Trade, ordertype: Optional[str],
|
||||||
amount: Optional[float] = None) -> bool:
|
amount: Optional[float] = None) -> bool:
|
||||||
# Check if there is there is an open order
|
# Check if there is there are open orders
|
||||||
fully_canceled = False
|
trade_entry_cancelation_registry = []
|
||||||
if trade.open_order_id:
|
for oo in trade.open_orders:
|
||||||
order = self._freqtrade.exchange.fetch_order(trade.open_order_id, trade.pair)
|
trade_entry_cancelation_res = {'order_id': oo.order_id, 'cancel_state': False}
|
||||||
|
order = self._freqtrade.exchange.fetch_order(oo.order_id, trade.pair)
|
||||||
|
|
||||||
if order['side'] == trade.entry_side:
|
if order['side'] == trade.entry_side:
|
||||||
fully_canceled = self._freqtrade.handle_cancel_enter(
|
fully_canceled = self._freqtrade.handle_cancel_enter(
|
||||||
trade, order, CANCEL_REASON['FORCE_EXIT'])
|
trade, order, oo.order_id, CANCEL_REASON['FORCE_EXIT'])
|
||||||
|
trade_entry_cancelation_res['cancel_state'] = fully_canceled
|
||||||
|
trade_entry_cancelation_registry.append(trade_entry_cancelation_res)
|
||||||
|
|
||||||
if order['side'] == trade.exit_side:
|
if order['side'] == trade.exit_side:
|
||||||
# Cancel order - so it is placed anew with a fresh price.
|
# Cancel order - so it is placed anew with a fresh price.
|
||||||
self._freqtrade.handle_cancel_exit(trade, order, CANCEL_REASON['FORCE_EXIT'])
|
self._freqtrade.handle_cancel_exit(
|
||||||
|
trade, order, oo.order_id, CANCEL_REASON['FORCE_EXIT'])
|
||||||
|
|
||||||
if not fully_canceled:
|
if all(tocr['cancel_state'] is False for tocr in trade_entry_cancelation_registry):
|
||||||
if trade.open_order_id is not None:
|
if trade.has_open_orders:
|
||||||
# Order cancellation failed, so we can't exit.
|
# Order cancellation failed, so we can't exit.
|
||||||
return False
|
return False
|
||||||
# Get current rate and execute sell
|
# Get current rate and execute sell
|
||||||
@@ -875,10 +904,10 @@ class RPC:
|
|||||||
if trade:
|
if trade:
|
||||||
is_short = trade.is_short
|
is_short = trade.is_short
|
||||||
if not self._freqtrade.strategy.position_adjustment_enable:
|
if not self._freqtrade.strategy.position_adjustment_enable:
|
||||||
raise RPCException(f'position for {pair} already open - id: {trade.id}')
|
raise RPCException(f"position for {pair} already open - id: {trade.id}")
|
||||||
if trade.open_order_id is not None:
|
if trade.has_open_orders:
|
||||||
raise RPCException(f'position for {pair} already open - id: {trade.id} '
|
raise RPCException(f"position for {pair} already open - id: {trade.id} "
|
||||||
f'and has open order {trade.open_order_id}')
|
f"and has open order {','.join(trade.open_orders_ids)}")
|
||||||
else:
|
else:
|
||||||
if Trade.get_open_trade_count() >= self._config['max_open_trades']:
|
if Trade.get_open_trade_count() >= self._config['max_open_trades']:
|
||||||
raise RPCException("Maximum number of trades is reached.")
|
raise RPCException("Maximum number of trades is reached.")
|
||||||
@@ -915,16 +944,18 @@ class RPC:
|
|||||||
if not trade:
|
if not trade:
|
||||||
logger.warning('cancel_open_order: Invalid trade_id received.')
|
logger.warning('cancel_open_order: Invalid trade_id received.')
|
||||||
raise RPCException('Invalid trade_id.')
|
raise RPCException('Invalid trade_id.')
|
||||||
if not trade.open_order_id:
|
if not trade.has_open_orders:
|
||||||
logger.warning('cancel_open_order: No open order for trade_id.')
|
logger.warning('cancel_open_order: No open order for trade_id.')
|
||||||
raise RPCException('No open order for trade_id.')
|
raise RPCException('No open order for trade_id.')
|
||||||
|
|
||||||
try:
|
for open_order in trade.open_orders:
|
||||||
order = self._freqtrade.exchange.fetch_order(trade.open_order_id, trade.pair)
|
try:
|
||||||
except ExchangeError as e:
|
order = self._freqtrade.exchange.fetch_order(open_order.order_id, trade.pair)
|
||||||
logger.info(f"Cannot query order for {trade} due to {e}.", exc_info=True)
|
except ExchangeError as e:
|
||||||
raise RPCException("Order not found.")
|
logger.info(f"Cannot query order for {trade} due to {e}.", exc_info=True)
|
||||||
self._freqtrade.handle_cancel_order(order, trade, CANCEL_REASON['USER_CANCEL'])
|
raise RPCException("Order not found.")
|
||||||
|
self._freqtrade.handle_cancel_order(
|
||||||
|
order, open_order.order_id, trade, CANCEL_REASON['USER_CANCEL'])
|
||||||
Trade.commit()
|
Trade.commit()
|
||||||
|
|
||||||
def _rpc_delete(self, trade_id: int) -> Dict[str, Union[str, int]]:
|
def _rpc_delete(self, trade_id: int) -> Dict[str, Union[str, int]]:
|
||||||
@@ -940,9 +971,9 @@ class RPC:
|
|||||||
raise RPCException('invalid argument')
|
raise RPCException('invalid argument')
|
||||||
|
|
||||||
# Try cancelling regular order if that exists
|
# Try cancelling regular order if that exists
|
||||||
if trade.open_order_id:
|
for open_order in trade.open_orders:
|
||||||
try:
|
try:
|
||||||
self._freqtrade.exchange.cancel_order(trade.open_order_id, trade.pair)
|
self._freqtrade.exchange.cancel_order(open_order.order_id, trade.pair)
|
||||||
c_count += 1
|
c_count += 1
|
||||||
except (ExchangeError):
|
except (ExchangeError):
|
||||||
pass
|
pass
|
||||||
@@ -1092,7 +1123,7 @@ class RPC:
|
|||||||
buffer = bufferHandler.buffer[-limit:]
|
buffer = bufferHandler.buffer[-limit:]
|
||||||
else:
|
else:
|
||||||
buffer = bufferHandler.buffer
|
buffer = bufferHandler.buffer
|
||||||
records = [[datetime.fromtimestamp(r.created).strftime(DATETIME_PRINT_FORMAT),
|
records = [[format_date(datetime.fromtimestamp(r.created)),
|
||||||
r.created * 1000, r.name, r.levelname,
|
r.created * 1000, r.name, r.levelname,
|
||||||
r.message + ('\n' + r.exc_text if r.exc_text else '')]
|
r.message + ('\n' + r.exc_text if r.exc_text else '')]
|
||||||
for r in buffer]
|
for r in buffer]
|
||||||
@@ -1309,7 +1340,7 @@ class RPC:
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"last_process": str(last_p),
|
"last_process": str(last_p),
|
||||||
"last_process_loc": last_p.astimezone(tzlocal()).strftime(DATETIME_PRINT_FORMAT),
|
"last_process_loc": format_date(last_p.astimezone(tzlocal())),
|
||||||
"last_process_ts": int(last_p.timestamp()),
|
"last_process_ts": int(last_p.timestamp()),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+16
-27
@@ -51,6 +51,7 @@ class TimeunitMappings:
|
|||||||
message2: str
|
message2: str
|
||||||
callback: str
|
callback: str
|
||||||
default: int
|
default: int
|
||||||
|
dateformat: str
|
||||||
|
|
||||||
|
|
||||||
def authorized_only(command_handler: Callable[..., Coroutine[Any, Any, None]]):
|
def authorized_only(command_handler: Callable[..., Coroutine[Any, Any, None]]):
|
||||||
@@ -531,40 +532,24 @@ class Telegram(RPCHandler):
|
|||||||
cur_entry_amount = order["filled"] or order["amount"]
|
cur_entry_amount = order["filled"] or order["amount"]
|
||||||
cur_entry_average = order["safe_price"]
|
cur_entry_average = order["safe_price"]
|
||||||
lines.append(" ")
|
lines.append(" ")
|
||||||
|
lines.append(f"*{wording} #{order_nr}:*")
|
||||||
if order_nr == 1:
|
if order_nr == 1:
|
||||||
lines.append(f"*{wording} #{order_nr}:*")
|
|
||||||
lines.append(
|
lines.append(
|
||||||
f"*Amount:* {cur_entry_amount:.8g} "
|
f"*Amount:* {cur_entry_amount:.8g} "
|
||||||
f"({round_coin_value(order['cost'], quote_currency)})"
|
f"({round_coin_value(order['cost'], quote_currency)})"
|
||||||
)
|
)
|
||||||
lines.append(f"*Average Price:* {cur_entry_average:.8g}")
|
lines.append(f"*Average Price:* {cur_entry_average:.8g}")
|
||||||
else:
|
else:
|
||||||
sum_stake = 0
|
|
||||||
sum_amount = 0
|
|
||||||
for y in range(order_nr):
|
|
||||||
loc_order = filled_orders[y]
|
|
||||||
if loc_order['is_open'] is True:
|
|
||||||
# Skip open orders (e.g. stop orders)
|
|
||||||
continue
|
|
||||||
amount = loc_order["filled"] or loc_order["amount"]
|
|
||||||
sum_stake += amount * loc_order["safe_price"]
|
|
||||||
sum_amount += amount
|
|
||||||
prev_avg_price = sum_stake / sum_amount
|
|
||||||
# TODO: This calculation ignores fees.
|
# TODO: This calculation ignores fees.
|
||||||
price_to_1st_entry = ((cur_entry_average - first_avg) / first_avg)
|
price_to_1st_entry = ((cur_entry_average - first_avg) / first_avg)
|
||||||
minus_on_entry = 0
|
|
||||||
if prev_avg_price:
|
|
||||||
minus_on_entry = (cur_entry_average - prev_avg_price) / prev_avg_price
|
|
||||||
|
|
||||||
lines.append(f"*{wording} #{order_nr}:* at {minus_on_entry:.2%} avg Profit")
|
|
||||||
if is_open:
|
if is_open:
|
||||||
lines.append("({})".format(dt_humanize(order["order_filled_date"],
|
lines.append("({})".format(dt_humanize(order["order_filled_date"],
|
||||||
granularity=["day", "hour", "minute"])))
|
granularity=["day", "hour", "minute"])))
|
||||||
lines.append(f"*Amount:* {cur_entry_amount:.8g} "
|
lines.append(f"*Amount:* {cur_entry_amount:.8g} "
|
||||||
f"({round_coin_value(order['cost'], quote_currency)})")
|
f"({round_coin_value(order['cost'], quote_currency)})")
|
||||||
lines.append(f"*Average {wording} Price:* {cur_entry_average:.8g} "
|
lines.append(f"*Average {wording} Price:* {cur_entry_average:.8g} "
|
||||||
f"({price_to_1st_entry:.2%} from 1st entry Rate)")
|
f"({price_to_1st_entry:.2%} from 1st entry rate)")
|
||||||
lines.append(f"*Order filled:* {order['order_filled_date']}")
|
lines.append(f"*Order Filled:* {order['order_filled_date']}")
|
||||||
|
|
||||||
lines_detail.append("\n".join(lines))
|
lines_detail.append("\n".join(lines))
|
||||||
|
|
||||||
@@ -662,10 +647,10 @@ class Telegram(RPCHandler):
|
|||||||
("`({stop_loss_ratio:.2%})`" if r['stop_loss_ratio'] else ""))
|
("`({stop_loss_ratio:.2%})`" if r['stop_loss_ratio'] else ""))
|
||||||
lines.append("*Stoploss distance:* `{stoploss_current_dist:.8g}` "
|
lines.append("*Stoploss distance:* `{stoploss_current_dist:.8g}` "
|
||||||
"`({stoploss_current_dist_ratio:.2%})`")
|
"`({stoploss_current_dist_ratio:.2%})`")
|
||||||
if r['open_order']:
|
if r.get('open_orders'):
|
||||||
lines.append(
|
lines.append(
|
||||||
"*Open Order:* `{open_order}`"
|
"*Open Order:* `{open_orders}`"
|
||||||
+ "- `{exit_order_status}`" if r['exit_order_status'] else "")
|
+ ("- `{exit_order_status}`" if r['exit_order_status'] else ""))
|
||||||
|
|
||||||
lines_detail = self._prepare_order_details(
|
lines_detail = self._prepare_order_details(
|
||||||
r['orders'], r['quote_currency'], r['is_open'])
|
r['orders'], r['quote_currency'], r['is_open'])
|
||||||
@@ -736,10 +721,10 @@ class Telegram(RPCHandler):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
vals = {
|
vals = {
|
||||||
'days': TimeunitMappings('Day', 'Daily', 'days', 'update_daily', 7),
|
'days': TimeunitMappings('Day', 'Daily', 'days', 'update_daily', 7, '%Y-%m-%d'),
|
||||||
'weeks': TimeunitMappings('Monday', 'Weekly', 'weeks (starting from Monday)',
|
'weeks': TimeunitMappings('Monday', 'Weekly', 'weeks (starting from Monday)',
|
||||||
'update_weekly', 8),
|
'update_weekly', 8, '%Y-%m-%d'),
|
||||||
'months': TimeunitMappings('Month', 'Monthly', 'months', 'update_monthly', 6),
|
'months': TimeunitMappings('Month', 'Monthly', 'months', 'update_monthly', 6, '%Y-%m'),
|
||||||
}
|
}
|
||||||
val = vals[unit]
|
val = vals[unit]
|
||||||
|
|
||||||
@@ -756,7 +741,7 @@ class Telegram(RPCHandler):
|
|||||||
unit
|
unit
|
||||||
)
|
)
|
||||||
stats_tab = tabulate(
|
stats_tab = tabulate(
|
||||||
[[f"{period['date']} ({period['trade_count']})",
|
[[f"{period['date']:{val.dateformat}} ({period['trade_count']})",
|
||||||
f"{round_coin_value(period['abs_profit'], stats['stake_currency'])}",
|
f"{round_coin_value(period['abs_profit'], stats['stake_currency'])}",
|
||||||
f"{period['fiat_value']:.2f} {stats['fiat_display_currency']}",
|
f"{period['fiat_value']:.2f} {stats['fiat_display_currency']}",
|
||||||
f"{period['rel_profit']:.2%}",
|
f"{period['rel_profit']:.2%}",
|
||||||
@@ -888,7 +873,11 @@ class Telegram(RPCHandler):
|
|||||||
f"*Trading volume:* `{round_coin_value(stats['trading_volume'], stake_cur)}`\n"
|
f"*Trading volume:* `{round_coin_value(stats['trading_volume'], stake_cur)}`\n"
|
||||||
f"*Profit factor:* `{stats['profit_factor']:.2f}`\n"
|
f"*Profit factor:* `{stats['profit_factor']:.2f}`\n"
|
||||||
f"*Max Drawdown:* `{stats['max_drawdown']:.2%} "
|
f"*Max Drawdown:* `{stats['max_drawdown']:.2%} "
|
||||||
f"({round_coin_value(stats['max_drawdown_abs'], stake_cur)})`"
|
f"({round_coin_value(stats['max_drawdown_abs'], stake_cur)})`\n"
|
||||||
|
f" from `{stats['max_drawdown_start']} "
|
||||||
|
f"({round_coin_value(stats['drawdown_high'], stake_cur)})`\n"
|
||||||
|
f" to `{stats['max_drawdown_end']} "
|
||||||
|
f"({round_coin_value(stats['drawdown_low'], stake_cur)})`\n"
|
||||||
)
|
)
|
||||||
await self._send_msg(markdown_msg, reload_able=True, callback_path="update_profit",
|
await self._send_msg(markdown_msg, reload_able=True, callback_path="update_profit",
|
||||||
query=update.callback_query)
|
query=update.callback_query)
|
||||||
|
|||||||
@@ -373,7 +373,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
|
||||||
current_profit: float, **kwargs) -> float:
|
current_profit: float, after_fill: bool, **kwargs) -> Optional[float]:
|
||||||
"""
|
"""
|
||||||
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
||||||
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
||||||
@@ -389,12 +389,14 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
||||||
|
:param after_fill: True if the stoploss is called after the order was filled.
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return float: New stoploss value, relative to the current_rate
|
:return float: New stoploss value, relative to the current_rate
|
||||||
"""
|
"""
|
||||||
return self.stoploss
|
return self.stoploss
|
||||||
|
|
||||||
def custom_entry_price(self, pair: str, current_time: datetime, proposed_rate: float,
|
def custom_entry_price(self, pair: str, trade: Optional[Trade],
|
||||||
|
current_time: datetime, proposed_rate: float,
|
||||||
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
entry_tag: Optional[str], side: str, **kwargs) -> float:
|
||||||
"""
|
"""
|
||||||
Custom entry price logic, returning the new entry price.
|
Custom entry price logic, returning the new entry price.
|
||||||
@@ -404,6 +406,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
When not implemented by a strategy, returns None, orderbook is used to set entry price
|
When not implemented by a strategy, returns None, orderbook is used to set entry price
|
||||||
|
|
||||||
:param pair: Pair that's currently analyzed
|
:param pair: Pair that's currently analyzed
|
||||||
|
:param trade: trade object (None for initial entries).
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param proposed_rate: Rate, calculated based on pricing settings in exit_pricing.
|
:param proposed_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
|
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
|
||||||
@@ -512,7 +515,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
"""
|
"""
|
||||||
Custom trade adjustment logic, returning the stake amount that a trade should be
|
Custom trade adjustment logic, returning the stake amount that a trade should be
|
||||||
increased or decreased.
|
increased or decreased.
|
||||||
This means extra buy or sell orders with additional fees.
|
This means extra entry or exit orders with additional fees.
|
||||||
Only called when `position_adjustment_enable` is set to True.
|
Only called when `position_adjustment_enable` is set to True.
|
||||||
|
|
||||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
@@ -521,8 +524,9 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
|
|
||||||
:param trade: trade object.
|
:param trade: trade object.
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Current buy rate.
|
:param current_rate: Current entry rate (same as current_entry_profit)
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate
|
||||||
|
(same as current_entry_profit).
|
||||||
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
||||||
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
||||||
:param current_entry_rate: Current rate using entry pricing.
|
:param current_entry_rate: Current rate using entry pricing.
|
||||||
@@ -719,6 +723,8 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
# END - Intended to be overridden by strategy
|
# END - Intended to be overridden by strategy
|
||||||
###
|
###
|
||||||
|
|
||||||
|
_ft_stop_uses_after_fill = False
|
||||||
|
|
||||||
def __informative_pairs_freqai(self) -> ListPairsWithTimeframes:
|
def __informative_pairs_freqai(self) -> ListPairsWithTimeframes:
|
||||||
"""
|
"""
|
||||||
Create informative-pairs needed for FreqAI
|
Create informative-pairs needed for FreqAI
|
||||||
@@ -1160,13 +1166,17 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
def ft_stoploss_adjust(self, current_rate: float, trade: Trade,
|
def ft_stoploss_adjust(self, current_rate: float, trade: Trade,
|
||||||
current_time: datetime, current_profit: float,
|
current_time: datetime, current_profit: float,
|
||||||
force_stoploss: float, low: Optional[float] = None,
|
force_stoploss: float, low: Optional[float] = None,
|
||||||
high: Optional[float] = None) -> None:
|
high: Optional[float] = None, after_fill: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Adjust stop-loss dynamically if configured to do so.
|
Adjust stop-loss dynamically if configured to do so.
|
||||||
:param current_profit: current profit as ratio
|
:param current_profit: current profit as ratio
|
||||||
:param low: Low value of this candle, only set in backtesting
|
:param low: Low value of this candle, only set in backtesting
|
||||||
:param high: High value of this candle, only set in backtesting
|
:param high: High value of this candle, only set in backtesting
|
||||||
"""
|
"""
|
||||||
|
if after_fill and not self._ft_stop_uses_after_fill:
|
||||||
|
# Skip if the strategy doesn't support after fill.
|
||||||
|
return
|
||||||
|
|
||||||
stop_loss_value = force_stoploss if force_stoploss else self.stoploss
|
stop_loss_value = force_stoploss if force_stoploss else self.stoploss
|
||||||
|
|
||||||
# Initiate stoploss with open_rate. Does nothing if stoploss is already set.
|
# Initiate stoploss with open_rate. Does nothing if stoploss is already set.
|
||||||
@@ -1181,18 +1191,20 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
bound = (low if trade.is_short else high)
|
bound = (low if trade.is_short else high)
|
||||||
bound_profit = current_profit if not bound else trade.calc_profit_ratio(bound)
|
bound_profit = current_profit if not bound else trade.calc_profit_ratio(bound)
|
||||||
if self.use_custom_stoploss and dir_correct:
|
if self.use_custom_stoploss and dir_correct:
|
||||||
stop_loss_value = strategy_safe_wrapper(self.custom_stoploss, default_retval=None,
|
stop_loss_value_custom = strategy_safe_wrapper(
|
||||||
supress_error=True
|
self.custom_stoploss, default_retval=None, supress_error=True
|
||||||
)(pair=trade.pair, trade=trade,
|
)(pair=trade.pair, trade=trade,
|
||||||
current_time=current_time,
|
current_time=current_time,
|
||||||
current_rate=(bound or current_rate),
|
current_rate=(bound or current_rate),
|
||||||
current_profit=bound_profit)
|
current_profit=bound_profit,
|
||||||
|
after_fill=after_fill)
|
||||||
# Sanity check - error cases will return None
|
# Sanity check - error cases will return None
|
||||||
if stop_loss_value:
|
if stop_loss_value_custom:
|
||||||
# logger.info(f"{trade.pair} {stop_loss_value=} {bound_profit=}")
|
stop_loss_value = stop_loss_value_custom
|
||||||
trade.adjust_stop_loss(bound or current_rate, stop_loss_value)
|
trade.adjust_stop_loss(bound or current_rate, stop_loss_value,
|
||||||
|
allow_refresh=after_fill)
|
||||||
else:
|
else:
|
||||||
logger.warning("CustomStoploss function did not return valid stoploss")
|
logger.debug("CustomStoploss function did not return valid stoploss")
|
||||||
|
|
||||||
if self.trailing_stop and dir_correct:
|
if self.trailing_stop and dir_correct:
|
||||||
# trailing stoploss handling
|
# trailing stoploss handling
|
||||||
@@ -1245,7 +1257,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
|||||||
exit_type = ExitType.STOP_LOSS
|
exit_type = ExitType.STOP_LOSS
|
||||||
|
|
||||||
# If initial stoploss is not the same as current one then it is trailing.
|
# If initial stoploss is not the same as current one then it is trailing.
|
||||||
if trade.initial_stop_loss != trade.stop_loss:
|
if trade.is_stop_loss_trailing:
|
||||||
exit_type = ExitType.TRAILING_STOP_LOSS
|
exit_type = ExitType.TRAILING_STOP_LOSS
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{trade.pair} - HIT STOP: current price at "
|
f"{trade.pair} - HIT STOP: current price at "
|
||||||
|
|||||||
@@ -45,10 +45,13 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame,
|
|||||||
elif minutes < minutes_inf:
|
elif minutes < minutes_inf:
|
||||||
# Subtract "small" timeframe so merging is not delayed by 1 small candle
|
# Subtract "small" timeframe so merging is not delayed by 1 small candle
|
||||||
# Detailed explanation in https://github.com/freqtrade/freqtrade/issues/4073
|
# Detailed explanation in https://github.com/freqtrade/freqtrade/issues/4073
|
||||||
informative['date_merge'] = (
|
if not informative.empty:
|
||||||
informative[date_column] + pd.to_timedelta(minutes_inf, 'm') -
|
informative['date_merge'] = (
|
||||||
pd.to_timedelta(minutes, 'm')
|
informative[date_column] + pd.to_timedelta(minutes_inf, 'm') -
|
||||||
)
|
pd.to_timedelta(minutes, 'm')
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
informative['date_merge'] = informative[date_column]
|
||||||
else:
|
else:
|
||||||
raise ValueError("Tried to merge a faster timeframe to a slower timeframe."
|
raise ValueError("Tried to merge a faster timeframe to a slower timeframe."
|
||||||
"This would create new rows, and can throw off your regular indicators.")
|
"This would create new rows, and can throw off your regular indicators.")
|
||||||
@@ -123,7 +126,8 @@ def stoploss_from_open(
|
|||||||
return max(stoploss * leverage, 0.0)
|
return max(stoploss * leverage, 0.0)
|
||||||
|
|
||||||
|
|
||||||
def stoploss_from_absolute(stop_rate: float, current_rate: float, is_short: bool = False) -> float:
|
def stoploss_from_absolute(stop_rate: float, current_rate: float, is_short: bool = False,
|
||||||
|
leverage: float = 1.0) -> float:
|
||||||
"""
|
"""
|
||||||
Given current price and desired stop price, return a stop loss value that is relative to current
|
Given current price and desired stop price, return a stop loss value that is relative to current
|
||||||
price.
|
price.
|
||||||
@@ -136,6 +140,7 @@ def stoploss_from_absolute(stop_rate: float, current_rate: float, is_short: bool
|
|||||||
:param stop_rate: Stop loss price.
|
:param stop_rate: Stop loss price.
|
||||||
:param current_rate: Current asset price.
|
:param current_rate: Current asset price.
|
||||||
:param is_short: When true, perform the calculation for short instead of long
|
:param is_short: When true, perform the calculation for short instead of long
|
||||||
|
:param leverage: Leverage to use for the calculation
|
||||||
:return: Positive stop loss value relative to current price
|
:return: Positive stop loss value relative to current price
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -150,4 +155,4 @@ def stoploss_from_absolute(stop_rate: float, current_rate: float, is_short: bool
|
|||||||
# negative stoploss values indicate the requested stop price is higher/lower
|
# negative stoploss values indicate the requested stop price is higher/lower
|
||||||
# (long/short) than the current price
|
# (long/short) than the current price
|
||||||
# shorts can yield stoploss values higher than 1, so limit that as well
|
# shorts can yield stoploss values higher than 1, so limit that as well
|
||||||
return max(min(stoploss, 1.0), 0.0)
|
return max(min(stoploss, 1.0), 0.0) * leverage
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ class FreqaiExampleStrategy(IStrategy):
|
|||||||
plot_config = {
|
plot_config = {
|
||||||
"main_plot": {},
|
"main_plot": {},
|
||||||
"subplots": {
|
"subplots": {
|
||||||
"&-s_close": {"prediction": {"color": "blue"}},
|
"&-s_close": {"&-s_close": {"color": "blue"}},
|
||||||
"do_predict": {
|
"do_predict": {
|
||||||
"do_predict": {"color": "brown"},
|
"do_predict": {"color": "brown"},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ class SampleStrategy(IStrategy):
|
|||||||
exit_short_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)
|
exit_short_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)
|
||||||
|
|
||||||
# Number of candles the strategy requires before producing valid signals
|
# Number of candles the strategy requires before producing valid signals
|
||||||
startup_candle_count: int = 30
|
startup_candle_count: int = 200
|
||||||
|
|
||||||
# Optional order type mapping.
|
# Optional order type mapping.
|
||||||
order_types = {
|
order_types = {
|
||||||
|
|||||||
@@ -243,7 +243,7 @@
|
|||||||
"# Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day)\n",
|
"# Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from freqtrade.configuration import Configuration\n",
|
"from freqtrade.configuration import Configuration\n",
|
||||||
"from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats\n",
|
"from freqtrade.data.btanalysis import load_backtest_stats\n",
|
||||||
"import plotly.express as px\n",
|
"import plotly.express as px\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -254,20 +254,8 @@
|
|||||||
"stats = load_backtest_stats(backtest_dir)\n",
|
"stats = load_backtest_stats(backtest_dir)\n",
|
||||||
"strategy_stats = stats['strategy'][strategy]\n",
|
"strategy_stats = stats['strategy'][strategy]\n",
|
||||||
"\n",
|
"\n",
|
||||||
"dates = []\n",
|
"df = pd.DataFrame(columns=['dates','equity'], data=strategy_stats['daily_profit'])\n",
|
||||||
"profits = []\n",
|
"df['equity_daily'] = df['equity'].cumsum()\n",
|
||||||
"for date_profit in strategy_stats['daily_profit']:\n",
|
|
||||||
" dates.append(date_profit[0])\n",
|
|
||||||
" profits.append(date_profit[1])\n",
|
|
||||||
"\n",
|
|
||||||
"equity = 0\n",
|
|
||||||
"equity_daily = []\n",
|
|
||||||
"for daily_profit in profits:\n",
|
|
||||||
" equity_daily.append(equity)\n",
|
|
||||||
" equity += float(daily_profit)\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"df = pd.DataFrame({'dates': dates,'equity_daily': equity_daily})\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"fig = px.line(df, x=\"dates\", y=\"equity_daily\")\n",
|
"fig = px.line(df, x=\"dates\", y=\"equity_daily\")\n",
|
||||||
"fig.show()\n"
|
"fig.show()\n"
|
||||||
@@ -414,7 +402,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.9.7"
|
"version": "3.11.4"
|
||||||
},
|
},
|
||||||
"mimetype": "text/x-python",
|
"mimetype": "text/x-python",
|
||||||
"name": "python",
|
"name": "python",
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ def bot_loop_start(self, current_time: datetime, **kwargs) -> None:
|
|||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def custom_entry_price(self, pair: str, current_time: 'datetime', proposed_rate: float,
|
def custom_entry_price(self, pair: str, trade: Optional['Trade'],
|
||||||
|
current_time: 'datetime', proposed_rate: float,
|
||||||
entry_tag: 'Optional[str]', side: str, **kwargs) -> float:
|
entry_tag: 'Optional[str]', side: str, **kwargs) -> float:
|
||||||
"""
|
"""
|
||||||
Custom entry price logic, returning the new entry price.
|
Custom entry price logic, returning the new entry price.
|
||||||
@@ -23,6 +24,7 @@ def custom_entry_price(self, pair: str, current_time: 'datetime', proposed_rate:
|
|||||||
When not implemented by a strategy, returns None, orderbook is used to set entry price
|
When not implemented by a strategy, returns None, orderbook is used to set entry price
|
||||||
|
|
||||||
:param pair: Pair that's currently analyzed
|
:param pair: Pair that's currently analyzed
|
||||||
|
:param trade: trade object (None for initial entries).
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param proposed_rate: Rate, calculated based on pricing settings in exit_pricing.
|
:param proposed_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
|
:param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
|
||||||
@@ -102,8 +104,8 @@ def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: f
|
|||||||
|
|
||||||
use_custom_stoploss = True
|
use_custom_stoploss = True
|
||||||
|
|
||||||
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: 'datetime',
|
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
||||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
current_profit: float, after_fill: bool, **kwargs) -> float:
|
||||||
"""
|
"""
|
||||||
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
|
||||||
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
e.g. returning -0.05 would create a stoploss 5% below current_rate.
|
||||||
@@ -111,7 +113,7 @@ def custom_stoploss(self, pair: str, trade: 'Trade', current_time: 'datetime',
|
|||||||
|
|
||||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
|
|
||||||
When not implemented by a strategy, returns the initial stoploss value
|
When not implemented by a strategy, returns the initial stoploss value.
|
||||||
Only called when use_custom_stoploss is set to True.
|
Only called when use_custom_stoploss is set to True.
|
||||||
|
|
||||||
:param pair: Pair that's currently analyzed
|
:param pair: Pair that's currently analyzed
|
||||||
@@ -119,10 +121,10 @@ def custom_stoploss(self, pair: str, trade: 'Trade', current_time: 'datetime',
|
|||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
:param current_rate: Rate, calculated based on pricing settings in exit_pricing.
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
||||||
|
:param after_fill: True if the stoploss is called after the order was filled.
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return float: New stoploss value, relative to the current_rate
|
:return float: New stoploss value, relative to the current_rate
|
||||||
"""
|
"""
|
||||||
return self.stoploss
|
|
||||||
|
|
||||||
def custom_exit(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
def custom_exit(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
|
||||||
current_profit: float, **kwargs) -> 'Optional[Union[str, bool]]':
|
current_profit: float, **kwargs) -> 'Optional[Union[str, bool]]':
|
||||||
@@ -257,7 +259,7 @@ def adjust_trade_position(self, trade: 'Trade', current_time: datetime,
|
|||||||
"""
|
"""
|
||||||
Custom trade adjustment logic, returning the stake amount that a trade should be
|
Custom trade adjustment logic, returning the stake amount that a trade should be
|
||||||
increased or decreased.
|
increased or decreased.
|
||||||
This means extra buy or sell orders with additional fees.
|
This means extra entry or exit orders with additional fees.
|
||||||
Only called when `position_adjustment_enable` is set to True.
|
Only called when `position_adjustment_enable` is set to True.
|
||||||
|
|
||||||
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
|
||||||
@@ -266,8 +268,9 @@ def adjust_trade_position(self, trade: 'Trade', current_time: datetime,
|
|||||||
|
|
||||||
:param trade: trade object.
|
:param trade: trade object.
|
||||||
:param current_time: datetime object, containing the current datetime
|
:param current_time: datetime object, containing the current datetime
|
||||||
:param current_rate: Current buy rate.
|
:param current_rate: Current entry rate (same as current_entry_profit)
|
||||||
:param current_profit: Current profit (as ratio), calculated based on current_rate.
|
:param current_profit: Current profit (as ratio), calculated based on current_rate
|
||||||
|
(same as current_entry_profit).
|
||||||
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
|
||||||
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
|
||||||
:param current_entry_rate: Current rate using entry pricing.
|
:param current_entry_rate: Current rate using entry pricing.
|
||||||
@@ -276,8 +279,8 @@ def adjust_trade_position(self, trade: 'Trade', current_time: datetime,
|
|||||||
:param current_exit_profit: Current profit using exit pricing.
|
:param current_exit_profit: Current profit using exit pricing.
|
||||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||||
:return float: Stake amount to adjust your trade,
|
:return float: Stake amount to adjust your trade,
|
||||||
Positive values to increase position, Negative values to decrease position.
|
Positive values to increase position, Negative values to decrease position.
|
||||||
Return None for no action.
|
Return None for no action.
|
||||||
"""
|
"""
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -9,11 +9,8 @@
|
|||||||
"name": "{{ exchange_name | lower }}",
|
"name": "{{ exchange_name | lower }}",
|
||||||
"key": "{{ exchange_key }}",
|
"key": "{{ exchange_key }}",
|
||||||
"secret": "{{ exchange_secret }}",
|
"secret": "{{ exchange_secret }}",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {},
|
||||||
"enableRateLimit": true,
|
|
||||||
"rateLimit": 500
|
|
||||||
},
|
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
|
|||||||
@@ -3,13 +3,8 @@
|
|||||||
"name": "kraken",
|
"name": "kraken",
|
||||||
"key": "{{ exchange_key }}",
|
"key": "{{ exchange_key }}",
|
||||||
"secret": "{{ exchange_secret }}",
|
"secret": "{{ exchange_secret }}",
|
||||||
"ccxt_config": {"enableRateLimit": true},
|
"ccxt_config": {},
|
||||||
"ccxt_async_config": {
|
"ccxt_async_config": {},
|
||||||
"enableRateLimit": true,
|
|
||||||
"rateLimit": 1000
|
|
||||||
// Enable the below for downoading data.
|
|
||||||
//"rateLimit": 3100
|
|
||||||
},
|
|
||||||
"pair_whitelist": [
|
"pair_whitelist": [
|
||||||
],
|
],
|
||||||
"pair_blacklist": [
|
"pair_blacklist": [
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from freqtrade.util.datetime_helpers import (dt_floor_day, dt_from_ts, dt_humanize, dt_now, dt_ts,
|
from freqtrade.util.datetime_helpers import (dt_floor_day, dt_from_ts, dt_humanize, dt_now, dt_ts,
|
||||||
dt_utc, format_ms_time, shorten_date)
|
dt_ts_def, dt_utc, format_date, format_ms_time,
|
||||||
|
shorten_date)
|
||||||
from freqtrade.util.ft_precise import FtPrecise
|
from freqtrade.util.ft_precise import FtPrecise
|
||||||
from freqtrade.util.periodic_cache import PeriodicCache
|
from freqtrade.util.periodic_cache import PeriodicCache
|
||||||
from freqtrade.util.template_renderer import render_template, render_template_with_fallback # noqa
|
from freqtrade.util.template_renderer import render_template, render_template_with_fallback # noqa
|
||||||
@@ -11,7 +12,9 @@ __all__ = [
|
|||||||
'dt_humanize',
|
'dt_humanize',
|
||||||
'dt_now',
|
'dt_now',
|
||||||
'dt_ts',
|
'dt_ts',
|
||||||
|
'dt_ts_def',
|
||||||
'dt_utc',
|
'dt_utc',
|
||||||
|
'format_date',
|
||||||
'format_ms_time',
|
'format_ms_time',
|
||||||
'FtPrecise',
|
'FtPrecise',
|
||||||
'PeriodicCache',
|
'PeriodicCache',
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from packaging import version
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
from freqtrade.constants import DOCS_LINK, Config
|
from freqtrade.constants import DOCS_LINK, Config
|
||||||
from freqtrade.enums.tradingmode import TradingMode
|
from freqtrade.enums import TradingMode
|
||||||
from freqtrade.exceptions import OperationalException
|
from freqtrade.exceptions import OperationalException
|
||||||
from freqtrade.persistence.pairlock import PairLock
|
from freqtrade.persistence.pairlock import PairLock
|
||||||
from freqtrade.persistence.trade_model import Trade
|
from freqtrade.persistence.trade_model import Trade
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ from typing import Optional
|
|||||||
|
|
||||||
import arrow
|
import arrow
|
||||||
|
|
||||||
|
from freqtrade.constants import DATETIME_PRINT_FORMAT
|
||||||
|
|
||||||
|
|
||||||
def dt_now() -> datetime:
|
def dt_now() -> datetime:
|
||||||
"""Return the current datetime in UTC."""
|
"""Return the current datetime in UTC."""
|
||||||
@@ -26,6 +28,16 @@ def dt_ts(dt: Optional[datetime] = None) -> int:
|
|||||||
return int(dt_now().timestamp() * 1000)
|
return int(dt_now().timestamp() * 1000)
|
||||||
|
|
||||||
|
|
||||||
|
def dt_ts_def(dt: Optional[datetime], default: int = 0) -> int:
|
||||||
|
"""
|
||||||
|
Return dt in ms as a timestamp in UTC.
|
||||||
|
If dt is None, return the current datetime in UTC.
|
||||||
|
"""
|
||||||
|
if dt:
|
||||||
|
return int(dt.timestamp() * 1000)
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
def dt_floor_day(dt: datetime) -> datetime:
|
def dt_floor_day(dt: datetime) -> datetime:
|
||||||
"""Return the floor of the day for the given datetime."""
|
"""Return the floor of the day for the given datetime."""
|
||||||
return dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
return dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
@@ -63,6 +75,17 @@ def dt_humanize(dt: datetime, **kwargs) -> str:
|
|||||||
return arrow.get(dt).humanize(**kwargs)
|
return arrow.get(dt).humanize(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def format_date(date: Optional[datetime]) -> str:
|
||||||
|
"""
|
||||||
|
Return a formatted date string.
|
||||||
|
Returns an empty string if date is None.
|
||||||
|
:param date: datetime to format
|
||||||
|
"""
|
||||||
|
if date:
|
||||||
|
return date.strftime(DATETIME_PRINT_FORMAT)
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
def format_ms_time(date: int) -> str:
|
def format_ms_time(date: int) -> str:
|
||||||
"""
|
"""
|
||||||
convert MS date to readable format.
|
convert MS date to readable format.
|
||||||
|
|||||||
+2
-1
@@ -22,7 +22,6 @@ nav:
|
|||||||
- Web Hook: webhook-config.md
|
- Web Hook: webhook-config.md
|
||||||
- Data Downloading: data-download.md
|
- Data Downloading: data-download.md
|
||||||
- Backtesting: backtesting.md
|
- Backtesting: backtesting.md
|
||||||
- Lookahead analysis: lookahead-analysis.md
|
|
||||||
- Hyperopt: hyperopt.md
|
- Hyperopt: hyperopt.md
|
||||||
- FreqAI:
|
- FreqAI:
|
||||||
- Introduction: freqai.md
|
- Introduction: freqai.md
|
||||||
@@ -43,6 +42,8 @@ nav:
|
|||||||
- Advanced Topics:
|
- Advanced Topics:
|
||||||
- Advanced Post-installation Tasks: advanced-setup.md
|
- Advanced Post-installation Tasks: advanced-setup.md
|
||||||
- Trade Object: trade-object.md
|
- Trade Object: trade-object.md
|
||||||
|
- Lookahead analysis: lookahead-analysis.md
|
||||||
|
- Recursive analysis: recursive-analysis.md
|
||||||
- Advanced Strategy: strategy-advanced.md
|
- Advanced Strategy: strategy-advanced.md
|
||||||
- Advanced Hyperopt: advanced-hyperopt.md
|
- Advanced Hyperopt: advanced-hyperopt.md
|
||||||
- Producer/Consumer mode: producer-consumer.md
|
- Producer/Consumer mode: producer-consumer.md
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ ignore = ["freqtrade/vendor/**"]
|
|||||||
line-length = 100
|
line-length = 100
|
||||||
extend-exclude = [".env", ".venv"]
|
extend-exclude = [".env", ".venv"]
|
||||||
target-version = "py38"
|
target-version = "py38"
|
||||||
|
# Exclude UP036 as it's causing the "exit if < 3.9" to fail.
|
||||||
extend-select = [
|
extend-select = [
|
||||||
"C90", # mccabe
|
"C90", # mccabe
|
||||||
# "N", # pep8-naming
|
# "N", # pep8-naming
|
||||||
|
|||||||
@@ -7,24 +7,24 @@
|
|||||||
-r docs/requirements-docs.txt
|
-r docs/requirements-docs.txt
|
||||||
|
|
||||||
coveralls==3.3.1
|
coveralls==3.3.1
|
||||||
ruff==0.0.285
|
ruff==0.0.291
|
||||||
mypy==1.5.1
|
mypy==1.5.1
|
||||||
pre-commit==3.3.3
|
pre-commit==3.4.0
|
||||||
pytest==7.4.0
|
pytest==7.4.2
|
||||||
pytest-asyncio==0.21.1
|
pytest-asyncio==0.21.1
|
||||||
pytest-cov==4.1.0
|
pytest-cov==4.1.0
|
||||||
pytest-mock==3.11.1
|
pytest-mock==3.11.1
|
||||||
pytest-random-order==1.1.0
|
pytest-random-order==1.1.0
|
||||||
isort==5.12.0
|
isort==5.12.0
|
||||||
# For datetime mocking
|
# For datetime mocking
|
||||||
time-machine==2.12.0
|
time-machine==2.13.0
|
||||||
|
|
||||||
# Convert jupyter notebooks to markdown documents
|
# Convert jupyter notebooks to markdown documents
|
||||||
nbconvert==7.7.4
|
nbconvert==7.8.0
|
||||||
|
|
||||||
# mypy types
|
# mypy types
|
||||||
types-cachetools==5.3.0.6
|
types-cachetools==5.3.0.6
|
||||||
types-filelock==3.2.7
|
types-filelock==3.2.7
|
||||||
types-requests==2.31.0.2
|
types-requests==2.31.0.4
|
||||||
types-tabulate==0.9.0.3
|
types-tabulate==0.9.0.3
|
||||||
types-python-dateutil==2.8.19.14
|
types-python-dateutil==2.8.19.14
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
# Required for freqai
|
# Required for freqai
|
||||||
scikit-learn==1.1.3
|
scikit-learn==1.1.3
|
||||||
joblib==1.3.2
|
joblib==1.3.2
|
||||||
catboost==1.2; 'arm' not in platform_machine
|
catboost==1.2.2; 'arm' not in platform_machine
|
||||||
lightgbm==4.0.0
|
lightgbm==4.1.0
|
||||||
xgboost==1.7.6
|
xgboost==2.0.0
|
||||||
tensorboard==2.14.0
|
tensorboard==2.14.0
|
||||||
datasieve==0.1.7
|
datasieve==0.1.7
|
||||||
|
|||||||
@@ -2,8 +2,7 @@
|
|||||||
-r requirements.txt
|
-r requirements.txt
|
||||||
|
|
||||||
# Required for hyperopt
|
# Required for hyperopt
|
||||||
scipy==1.11.2; python_version >= '3.9'
|
scipy==1.11.2
|
||||||
scipy==1.10.1; python_version < '3.9'
|
|
||||||
scikit-learn==1.1.3
|
scikit-learn==1.1.3
|
||||||
scikit-optimize==0.9.0
|
scikit-optimize==0.9.0
|
||||||
filelock==3.12.2
|
filelock==3.12.4
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Include all requirements to run the bot.
|
# Include all requirements to run the bot.
|
||||||
-r requirements.txt
|
-r requirements.txt
|
||||||
|
|
||||||
plotly==5.16.1
|
plotly==5.17.0
|
||||||
|
|||||||
+15
-16
@@ -1,21 +1,20 @@
|
|||||||
numpy==1.25.2; python_version > '3.8'
|
numpy==1.26.0; platform_machine != 'armv7l'
|
||||||
numpy==1.24.3; python_version <= '3.8'
|
numpy==1.25.2; platform_machine == 'armv7l'
|
||||||
pandas==2.0.3
|
pandas==2.0.3
|
||||||
pandas-ta==0.3.14b
|
pandas-ta==0.3.14b
|
||||||
|
|
||||||
ccxt==4.0.71
|
ccxt==4.0.105
|
||||||
cryptography==41.0.3; platform_machine != 'armv7l'
|
cryptography==41.0.3
|
||||||
cryptography==40.0.1; platform_machine == 'armv7l'
|
|
||||||
aiohttp==3.8.5
|
aiohttp==3.8.5
|
||||||
SQLAlchemy==2.0.20
|
SQLAlchemy==2.0.21
|
||||||
python-telegram-bot==20.4
|
python-telegram-bot==20.5
|
||||||
# can't be hard-pinned due to telegram-bot pinning httpx with ~
|
# can't be hard-pinned due to telegram-bot pinning httpx with ~
|
||||||
httpx>=0.24.1
|
httpx>=0.24.1
|
||||||
arrow==1.2.3
|
arrow==1.2.3
|
||||||
cachetools==5.3.1
|
cachetools==5.3.1
|
||||||
requests==2.31.0
|
requests==2.31.0
|
||||||
urllib3==2.0.4
|
urllib3==2.0.5
|
||||||
jsonschema==4.19.0
|
jsonschema==4.19.1
|
||||||
TA-Lib==0.4.28
|
TA-Lib==0.4.28
|
||||||
technical==1.4.0
|
technical==1.4.0
|
||||||
tabulate==0.9.0
|
tabulate==0.9.0
|
||||||
@@ -24,23 +23,23 @@ jinja2==3.1.2
|
|||||||
tables==3.8.0
|
tables==3.8.0
|
||||||
blosc==1.11.1
|
blosc==1.11.1
|
||||||
joblib==1.3.2
|
joblib==1.3.2
|
||||||
rich==13.5.2
|
rich==13.5.3
|
||||||
pyarrow==12.0.1; platform_machine != 'armv7l'
|
pyarrow==13.0.0; platform_machine != 'armv7l'
|
||||||
|
|
||||||
# find first, C search in arrays
|
# find first, C search in arrays
|
||||||
py_find_1st==1.1.5
|
py_find_1st==1.1.5
|
||||||
|
|
||||||
# Load ticker files 30% faster
|
# Load ticker files 30% faster
|
||||||
python-rapidjson==1.10
|
python-rapidjson==1.11
|
||||||
# Properly format api responses
|
# Properly format api responses
|
||||||
orjson==3.9.5
|
orjson==3.9.7
|
||||||
|
|
||||||
# Notify systemd
|
# Notify systemd
|
||||||
sdnotify==0.3.2
|
sdnotify==0.3.2
|
||||||
|
|
||||||
# API Server
|
# API Server
|
||||||
fastapi==0.101.1
|
fastapi==0.103.1
|
||||||
pydantic==2.2.1
|
pydantic==2.3.0
|
||||||
uvicorn==0.23.2
|
uvicorn==0.23.2
|
||||||
pyjwt==2.8.0
|
pyjwt==2.8.0
|
||||||
aiofiles==23.2.1
|
aiofiles==23.2.1
|
||||||
@@ -49,7 +48,7 @@ psutil==5.9.5
|
|||||||
# Support for colorized terminal output
|
# Support for colorized terminal output
|
||||||
colorama==0.4.6
|
colorama==0.4.6
|
||||||
# Building config files interactively
|
# Building config files interactively
|
||||||
questionary==2.0.0
|
questionary==2.0.1
|
||||||
prompt-toolkit==3.0.36
|
prompt-toolkit==3.0.36
|
||||||
# Extensions to datetime library
|
# Extensions to datetime library
|
||||||
python-dateutil==2.8.2
|
python-dateutil==2.8.2
|
||||||
|
|||||||
@@ -134,6 +134,20 @@ class FtRestClient:
|
|||||||
"""
|
"""
|
||||||
return self._get("daily", params={"timescale": days} if days else None)
|
return self._get("daily", params={"timescale": days} if days else None)
|
||||||
|
|
||||||
|
def weekly(self, weeks=None):
|
||||||
|
"""Return the profits for each week, and amount of trades.
|
||||||
|
|
||||||
|
:return: json object
|
||||||
|
"""
|
||||||
|
return self._get("weekly", params={"timescale": weeks} if weeks else None)
|
||||||
|
|
||||||
|
def monthly(self, months=None):
|
||||||
|
"""Return the profits for each month, and amount of trades.
|
||||||
|
|
||||||
|
:return: json object
|
||||||
|
"""
|
||||||
|
return self._get("monthly", params={"timescale": months} if months else None)
|
||||||
|
|
||||||
def edge(self):
|
def edge(self):
|
||||||
"""Return information about edge.
|
"""Return information about edge.
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ classifiers =
|
|||||||
Environment :: Console
|
Environment :: Console
|
||||||
Intended Audience :: Science/Research
|
Intended Audience :: Science/Research
|
||||||
License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
||||||
Programming Language :: Python :: 3.8
|
|
||||||
Programming Language :: Python :: 3.9
|
Programming Language :: Python :: 3.9
|
||||||
Programming Language :: Python :: 3.10
|
Programming Language :: Python :: 3.10
|
||||||
Programming Language :: Python :: 3.11
|
Programming Language :: Python :: 3.11
|
||||||
@@ -33,7 +32,7 @@ tests_require =
|
|||||||
pytest-mock
|
pytest-mock
|
||||||
|
|
||||||
packages = find:
|
packages = find:
|
||||||
python_requires = >=3.8
|
python_requires = >=3.9
|
||||||
|
|
||||||
[options.entry_points]
|
[options.entry_points]
|
||||||
console_scripts =
|
console_scripts =
|
||||||
@@ -50,3 +49,5 @@ exclude =
|
|||||||
__pycache__,
|
__pycache__,
|
||||||
.eggs,
|
.eggs,
|
||||||
user_data,
|
user_data,
|
||||||
|
.venv
|
||||||
|
.env
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ function check_installed_python() {
|
|||||||
exit 2
|
exit 2
|
||||||
fi
|
fi
|
||||||
|
|
||||||
for v in 11 10 9 8
|
for v in 11 10 9
|
||||||
do
|
do
|
||||||
PYTHON="python3.${v}"
|
PYTHON="python3.${v}"
|
||||||
which $PYTHON
|
which $PYTHON
|
||||||
@@ -36,7 +36,7 @@ function check_installed_python() {
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
echo "No usable python found. Please make sure to have python3.8 or newer installed."
|
echo "No usable python found. Please make sure to have python3.9 or newer installed."
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,7 +192,7 @@ function update() {
|
|||||||
fi
|
fi
|
||||||
updateenv
|
updateenv
|
||||||
echo "Update completed."
|
echo "Update completed."
|
||||||
echo_block "Don't forget to activate your virtual enviorment with 'source .venv/bin/activate'!"
|
echo_block "Don't forget to activate your virtual environment with 'source .venv/bin/activate'!"
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,7 +277,7 @@ function install() {
|
|||||||
install_redhat
|
install_redhat
|
||||||
else
|
else
|
||||||
echo "This script does not support your OS."
|
echo "This script does not support your OS."
|
||||||
echo "If you have Python version 3.8 - 3.11, pip, virtualenv, ta-lib you can continue."
|
echo "If you have Python version 3.9 - 3.11, pip, virtualenv, ta-lib you can continue."
|
||||||
echo "Wait 10 seconds to continue the next install steps or use ctrl+c to interrupt this shell."
|
echo "Wait 10 seconds to continue the next install steps or use ctrl+c to interrupt this shell."
|
||||||
sleep 10
|
sleep 10
|
||||||
fi
|
fi
|
||||||
@@ -304,7 +304,7 @@ function help() {
|
|||||||
echo " -p,--plot Install dependencies for Plotting scripts."
|
echo " -p,--plot Install dependencies for Plotting scripts."
|
||||||
}
|
}
|
||||||
|
|
||||||
# Verify if 3.8+ is installed
|
# Verify if 3.9+ is installed
|
||||||
check_installed_python
|
check_installed_python
|
||||||
|
|
||||||
case $* in
|
case $* in
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user