Compare commits
851 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
54c07e5e62 | ||
|
a6b48f7366 | ||
|
c6fd6a0fbf | ||
|
297e63de0a | ||
|
8ae0f99a96 | ||
|
a29653b510 | ||
|
c9b6bb1229 | ||
|
5a900858d8 | ||
|
2f349e0504 | ||
|
23b47b66ec | ||
|
6c8b5ea38c | ||
|
4d040f3123 | ||
|
88121760e4 | ||
|
ae7a12200c | ||
|
d63aaf3bfd | ||
|
ff69b511e3 | ||
|
4054dec7a0 | ||
|
353f722dc5 | ||
|
83959f0e56 | ||
|
c657a1df2b | ||
|
e545ef563c | ||
|
0eeafcd157 | ||
|
f25d6224dd | ||
|
e04c2dda2c | ||
|
d2181bdd94 | ||
|
5ac6244465 | ||
|
2957756275 | ||
|
b49b9b515e | ||
|
259dc75a30 | ||
|
ca8e52dc2c | ||
|
91ee48f3fb | ||
|
e2e6b940a3 | ||
|
c651e0ac82 | ||
|
430f53ca11 | ||
|
3186add87b | ||
|
7ecc56fa44 | ||
|
2fe7b683cb | ||
|
77ef3240cd | ||
|
97e6e5e976 | ||
|
f5b4a6d3d7 | ||
|
d9ecf3e4bf | ||
|
d2e20d86bb | ||
|
269a669af8 | ||
|
881f602f91 | ||
|
e0800b7c29 | ||
|
04aa74e5ad | ||
|
43add0b159 | ||
|
945ff09e27 | ||
|
78ee36a8c6 | ||
|
bee28a1061 | ||
|
10668bb249 | ||
|
56a06cbd33 | ||
|
bca5f804a8 | ||
|
5adbe3c2d3 | ||
|
751e2b2359 | ||
|
a7342bd910 | ||
|
f2f2c281c0 | ||
|
d22384c7fb | ||
|
29b369c65e | ||
|
2d2fd968c8 | ||
|
882d0a5933 | ||
|
09d89fbfb3 | ||
|
d91b9d1253 | ||
|
1634297685 | ||
|
16cbd441ce | ||
|
e6dd463ca3 | ||
|
1172c95817 | ||
|
0b33b798e4 | ||
|
4c41da2ea4 | ||
|
9b58b4c54d | ||
|
a8e0526d87 | ||
|
90fbf70bcc | ||
|
582b59044c | ||
|
df955b8104 | ||
|
e7d687ee11 | ||
|
0fd3d74fc4 | ||
|
9435950fc9 | ||
|
500e1c77de | ||
|
c6a3038f52 | ||
|
212d20ed08 | ||
|
bec86b1325 | ||
|
6335d81ceb | ||
|
7b9bd70d97 | ||
|
3787ac7b98 | ||
|
36670fb5d9 | ||
|
180939a962 | ||
|
6e71f2f166 | ||
|
44ac2409ff | ||
|
6139239b86 | ||
|
9d09a67dea | ||
|
87b506972f | ||
|
c453969235 | ||
|
fdd362299f | ||
|
42a5d78e60 | ||
|
ddea4b9300 | ||
|
e8c0a0bcd3 | ||
|
1cf19133f4 | ||
|
29d9b6a46a | ||
|
93f9ff1b63 | ||
|
06b84b4086 | ||
|
bba7a38144 | ||
|
47a91c9d8e | ||
|
e598c769d4 | ||
|
f024cc40d3 | ||
|
ecca7164d9 | ||
|
d5a298bbb7 | ||
|
5efbdd25a7 | ||
|
ab27d2c720 | ||
|
c92e1d97d6 | ||
|
1bc26fd07a | ||
|
be4a9b5f4b | ||
|
9dafc2f3c8 | ||
|
a2d7f8a70d | ||
|
9cbf8c5f00 | ||
|
3312fd34f3 | ||
|
ee92e8dbf4 | ||
|
ec5d2d78dd | ||
|
20c21b42d5 | ||
|
36ef5c6bdf | ||
|
2dea362eda | ||
|
749463e4b7 | ||
|
a0a14a1078 | ||
|
4cdcf00ddc | ||
|
0631fc937a | ||
|
02148a1df2 | ||
|
a93bc74eff | ||
|
ccc9239751 | ||
|
86592c3ba1 | ||
|
81f849811f | ||
|
3e6209def2 | ||
|
634bf2b15c | ||
|
007cc94474 | ||
|
f09af888b1 | ||
|
2e3b8cdba7 | ||
|
f6db784a85 | ||
|
47874a4527 | ||
|
2efa1c164f | ||
|
483cba453a | ||
|
d6b9397579 | ||
|
9a22ce69bd | ||
|
4f3376e2a1 | ||
|
e73dac8d91 | ||
|
539343b20d | ||
|
7be9f0067e | ||
|
64fb8e28ec | ||
|
c35fe2c386 | ||
|
d1c3eabb87 | ||
|
899de8b27c | ||
|
cde1b2b56c | ||
|
5f4c209fca | ||
|
4fedf1e564 | ||
|
5b4d8d69ef | ||
|
fc29564974 | ||
|
867b736b84 | ||
|
7f4b90c68f | ||
|
f99d1c3829 | ||
|
59a576ef3e | ||
|
81997cba8a | ||
|
57fcca9696 | ||
|
29f7c5071b | ||
|
62bcb3d766 | ||
|
2bcce33f23 | ||
|
f2520c11e7 | ||
|
c924e4d519 | ||
|
d442b31f84 | ||
|
df8a27fba6 | ||
|
05128d21a8 | ||
|
faf19eda86 | ||
|
d07c69809d | ||
|
da03c36875 | ||
|
0ac0ca74b5 | ||
|
d69ddd2ac3 | ||
|
1a544be828 | ||
|
bfccb2e96a | ||
|
7bb02d0cc6 | ||
|
f220e0f6ca | ||
|
83644ce5d8 | ||
|
550f9fc891 | ||
|
c7167c83cd | ||
|
6b4094fd92 | ||
|
88f2ad1eae | ||
|
90ee82ac43 | ||
|
db0475f9c3 | ||
|
4af25ec315 | ||
|
0ba8d13de9 | ||
|
f7c74e551f | ||
|
5bf4c5869b | ||
|
cc3f65d069 | ||
|
c83da7cadb | ||
|
7c91c77fd9 | ||
|
40abdd2608 | ||
|
c89a32224c | ||
|
d65a06947d | ||
|
eb3783dc00 | ||
|
c648ec7c0c | ||
|
c7ba85c2e6 | ||
|
b536d50194 | ||
|
f41de38498 | ||
|
c96acd6ca0 | ||
|
2796d3d8a0 | ||
|
636bd5acb5 | ||
|
1a9787ac76 | ||
|
879b513822 | ||
|
4fad7a462c | ||
|
f3b1161640 | ||
|
c4031761fe | ||
|
34f04668c1 | ||
|
52f4187129 | ||
|
f508324fc8 | ||
|
a1fe3850e2 | ||
|
fff8ced3b0 | ||
|
67e66a6c4a | ||
|
5bae5a6a35 | ||
|
61ced5e926 | ||
|
28184201e4 | ||
|
a893f70e49 | ||
|
6990f6af25 | ||
|
c501fd0a70 | ||
|
abf10aec98 | ||
|
aa2cb937b1 | ||
|
ff819386e1 | ||
|
f57bd6b616 | ||
|
418e7adac1 | ||
|
2034527faa | ||
|
412f5d68de | ||
|
2846f9454f | ||
|
739acaa475 | ||
|
97e48080e8 | ||
|
5b00eaa42d | ||
|
9639ffb140 | ||
|
586cbc750c | ||
|
b5ee4f17cb | ||
|
6866f6389d | ||
|
d2cac1d8fd | ||
|
aa54fd2251 | ||
|
f5fb129483 | ||
|
a707aeb3d0 | ||
|
f8bb6a3e06 | ||
|
91b4c9668c | ||
|
d457d43999 | ||
|
ffb53a6df5 | ||
|
82590657fb | ||
|
54303880d3 | ||
|
cbabc295c7 | ||
|
b8aaf744e8 | ||
|
64f04845b6 | ||
|
684cb54992 | ||
|
f6c09160ab | ||
|
221950cdc4 | ||
|
6e6c0757d6 | ||
|
2ee99bde29 | ||
|
d5f704009f | ||
|
3938418ad5 | ||
|
401748e9a7 | ||
|
bc2ae3e88d | ||
|
7b8e665323 | ||
|
df249c7c03 | ||
|
5c20311768 | ||
|
d0506a6435 | ||
|
c8960ab628 | ||
|
537596001e | ||
|
d8c053573a | ||
|
2b69e7830d | ||
|
e3cb5d26c0 | ||
|
84156879f6 | ||
|
d12e03e50d | ||
|
cd0534efcc | ||
|
505648fb66 | ||
|
857eb5ff69 | ||
|
3fe39a3e1b | ||
|
a5e670b402 | ||
|
e8c1abc509 | ||
|
6594679e52 | ||
|
c1897fbc48 | ||
|
aeabe1800b | ||
|
d64751687b | ||
|
3499f1b85c | ||
|
f3d500085c | ||
|
aa8731d0fc | ||
|
cbd2b265bb | ||
|
321bc336ea | ||
|
4459679c64 | ||
|
628b06927c | ||
|
12317b1c53 | ||
|
d1a3a2d000 | ||
|
cfa6a3e3d3 | ||
|
c224c66978 | ||
|
929bbe3058 | ||
|
8796ecb2a9 | ||
|
54512a66ef | ||
|
c40a4d77f8 | ||
|
d69ef4380b | ||
|
8371003c05 | ||
|
19d4e1435c | ||
|
4a80c47fd1 | ||
|
d038bcedb0 | ||
|
c396ad4daa | ||
|
cff8498b42 | ||
|
fdf6121b6e | ||
|
907a61152c | ||
|
e2b3907df5 | ||
|
4be3f053ca | ||
|
83baa6ee2e | ||
|
cebf99b5d8 | ||
|
acbf13e648 | ||
|
2f0775fa1b | ||
|
940bfbee96 | ||
|
e250c56829 | ||
|
49c9258a08 | ||
|
dd83cb1b95 | ||
|
2396f35586 | ||
|
68771a7861 | ||
|
e1356fb80e | ||
|
c80d8f432a | ||
|
122c916356 | ||
|
9f29128205 | ||
|
b384ca8fd2 | ||
|
a0b92fe0b1 | ||
|
328a9ffafd | ||
|
d40054b9d2 | ||
|
4c0e586354 | ||
|
3541f7bfce | ||
|
3a2443b5fa | ||
|
e488ce0d07 | ||
|
521e497ba3 | ||
|
c9ee678a52 | ||
|
078e25e383 | ||
|
a3b0f75289 | ||
|
66939bdcf6 | ||
|
184a6005a6 | ||
|
161c06fd4e | ||
|
5d7317ef77 | ||
|
aae14dd9fe | ||
|
30e3e434ab | ||
|
33645e45fd | ||
|
1ef148317d | ||
|
1b9af9d2d8 | ||
|
27d46ed06f | ||
|
02563019fc | ||
|
8c9119b471 | ||
|
2d02c3f2a4 | ||
|
a3e9d04383 | ||
|
7f851ad8d9 | ||
|
a1c684f67c | ||
|
f347e5934a | ||
|
e033df6a2f | ||
|
b254bdfea3 | ||
|
70a0346b0a | ||
|
7e23304187 | ||
|
926bf07df1 | ||
|
6e85280467 | ||
|
80ed1c3e14 | ||
|
1ae3fb4d2f | ||
|
3f2542fcbc | ||
|
f6278da23f | ||
|
a3ac05cc16 | ||
|
a97bb10877 | ||
|
bd4dd8403b | ||
|
52f0ed5310 | ||
|
f4c7edf551 | ||
|
f8db7f1709 | ||
|
72c273aaed | ||
|
70b9bd9c0e | ||
|
ea5ac1efb5 | ||
|
a83de241e4 | ||
|
f5a44e4fc4 | ||
|
1d141cd406 | ||
|
82797e768f | ||
|
9176064047 | ||
|
bc4c469797 | ||
|
aad10ceee3 | ||
|
58ceda4b90 | ||
|
f36bc80ad1 | ||
|
2b4d821d30 | ||
|
8a940eb0c1 | ||
|
9c2f21b07e | ||
|
055f3fd1fd | ||
|
40843566d0 | ||
|
e13045b599 | ||
|
7d2d0235a0 | ||
|
bff0a09537 | ||
|
c1c2717bc9 | ||
|
fc2970f41b | ||
|
66415d48d4 | ||
|
d54b1dade3 | ||
|
1bf475fa1a | ||
|
099bbc5c7f | ||
|
6e3336cb30 | ||
|
eb6c7f8595 | ||
|
10a706851a | ||
|
8d4515935a | ||
|
9474cb1792 | ||
|
10d9db72a8 | ||
|
cf9331919f | ||
|
7a22aaa111 | ||
|
f1629c907a | ||
|
e6f1912443 | ||
|
16b34e11ca | ||
|
256fc2e78c | ||
|
da0af489a2 | ||
|
8d2e0bfd62 | ||
|
2f82122fc4 | ||
|
889929f782 | ||
|
fa1e9dd70d | ||
|
29a5e4fba1 | ||
|
a20f502159 | ||
|
8bcfe4a6aa | ||
|
854bb0056b | ||
|
90ed4c665b | ||
|
d1bf388b0e | ||
|
6feb68b18d | ||
|
09621b3ef1 | ||
|
f73f0b1653 | ||
|
f7f56f5eda | ||
|
c8806a16a1 | ||
|
4013701bdb | ||
|
4c823f12e3 | ||
|
1e58cd70ad | ||
|
bea4ad8eff | ||
|
d7957bd791 | ||
|
425ec53b28 | ||
|
797dc8a4da | ||
|
d12a2a5888 | ||
|
845e27542a | ||
|
c67b253099 | ||
|
154fff7d02 | ||
|
82fd6e6fb3 | ||
|
b3938a86c3 | ||
|
2f8ed7ed19 | ||
|
af36635769 | ||
|
495728f502 | ||
|
5dccd01fb7 | ||
|
5fcab1eee8 | ||
|
b60d7ad42f | ||
|
fa1f9bcdbd | ||
|
53abfdbcbf | ||
|
3519cebf66 | ||
|
a7246ba1ec | ||
|
60b47b6eec | ||
|
ca2880537d | ||
|
13274964a9 | ||
|
235a10ab86 | ||
|
5faebad863 | ||
|
90a9052377 | ||
|
d3de398395 | ||
|
83b88e7916 | ||
|
3faa2d0eb9 | ||
|
fab19ae3a7 | ||
|
e94dfdeff2 | ||
|
9713dc8d94 | ||
|
b748ed3435 | ||
|
7c7f7b9ece | ||
|
785cd2a640 | ||
|
c475729c13 | ||
|
989ab646a9 | ||
|
7461b5dc02 | ||
|
135487b2c9 | ||
|
b25f28d1ad | ||
|
cee8f3349e | ||
|
9559cb988e | ||
|
db34cb1b75 | ||
|
c9b0b4c7a4 | ||
|
c3fd894a6c | ||
|
9f2d397e1f | ||
|
7719d8fbea | ||
|
3883d18b8a | ||
|
2b3f2e5fa8 | ||
|
5ae554bdff | ||
|
6ac7dcf5e9 | ||
|
6da97fafa8 | ||
|
6d4fe94285 | ||
|
b27f3b8f2c | ||
|
ed29232478 | ||
|
3c0d184097 | ||
|
d846114d3c | ||
|
aabeece4c0 | ||
|
b614964ba9 | ||
|
888ea58df2 | ||
|
d0ccfa1925 | ||
|
41945138ac | ||
|
ca054799d0 | ||
|
b37f34ff5b | ||
|
a75420f75f | ||
|
7daa5bc338 | ||
|
4eaaec9d1a | ||
|
bc6a10353b | ||
|
f82c4346b6 | ||
|
53499e01de | ||
|
bdda620397 | ||
|
2409261cb7 | ||
|
b5a806dec7 | ||
|
4628024de6 | ||
|
f04873b0b0 | ||
|
5853b9904c | ||
|
5d5074ac9c | ||
|
84ef588163 | ||
|
d1cda3991c | ||
|
24aa596e3c | ||
|
3798f94d4c | ||
|
75dcc369c0 | ||
|
e1f89e3ad3 | ||
|
7e7c82cf4a | ||
|
71dd038664 | ||
|
55041878ae | ||
|
0dd274917f | ||
|
f3beaa3374 | ||
|
6d01653bfe | ||
|
455838648d | ||
|
3c7981160c | ||
|
4ac1ac7ef5 | ||
|
776fc56265 | ||
|
a8d56b2850 | ||
|
11059e532b | ||
|
da1fea6582 | ||
|
3315f994b6 | ||
|
560aea876e | ||
|
b24d359a27 | ||
|
90744ff5ab | ||
|
b48bf035f6 | ||
|
c13c11cfa1 | ||
|
6e615998c0 | ||
|
94afb7cb1d | ||
|
bfef3cf497 | ||
|
cba156dfff | ||
|
64db1f6736 | ||
|
a47a25ca88 | ||
|
88efa4065b | ||
|
f15e5e9d57 | ||
|
2ccdb67e4d | ||
|
1b8943ac54 | ||
|
9382b38c41 | ||
|
22fcf7b4dc | ||
|
20fc3b7978 | ||
|
9325880fe5 | ||
|
cac0e37b06 | ||
|
2c8e8d8ef6 | ||
|
6fbdd6bee9 | ||
|
e89fa44680 | ||
|
a9fbad0741 | ||
|
8cc48cf4b0 | ||
|
10ee23622a | ||
|
904e1647e1 | ||
|
caec345c0b | ||
|
18a53f4467 | ||
|
6dfde99cbe | ||
|
21418e2988 | ||
|
4475110df8 | ||
|
0ea44b0143 | ||
|
3327ebf2b1 | ||
|
26a2395aeb | ||
|
9d518b9d29 | ||
|
6ebb9017c7 | ||
|
a88464de3a | ||
|
fd7af587da | ||
|
84918ad424 | ||
|
699c0d6bc3 | ||
|
2537b8cb0c | ||
|
78883663a0 | ||
|
b00406a7eb | ||
|
4d56e3b36e | ||
|
8e9a3e8fc8 | ||
|
1ffda29fd2 | ||
|
024aa3ab6b | ||
|
20abf67779 | ||
|
fb3a53b8af | ||
|
4c9295fe2d | ||
|
6a7163d3a9 | ||
|
de23f3928d | ||
|
8975e38b1d | ||
|
20a132651f | ||
|
88ba7e467d | ||
|
df7ceb4ccb | ||
|
47bb8ad0d4 | ||
|
304d15e236 | ||
|
d1c45cf3f8 | ||
|
04f28ed9bc | ||
|
ce84f74528 | ||
|
762604300f | ||
|
433fd2a7c3 | ||
|
814cc20c6b | ||
|
f4a532ef6d | ||
|
6b5983339d | ||
|
ae1b28aab7 | ||
|
09b77d9f14 | ||
|
5c39ebd0a0 | ||
|
e2a00c03d6 | ||
|
66d18575a7 | ||
|
9e4fc00a0f | ||
|
70f3ff0461 | ||
|
e7054adc49 | ||
|
28787a001c | ||
|
525550e4c7 | ||
|
6860491189 | ||
|
b37b5c3d90 | ||
|
9c5b94adf5 | ||
|
65f539e9d8 | ||
|
d65c1eea7a | ||
|
8a030e7fc0 | ||
|
a3144cb2f0 | ||
|
baa942ff98 | ||
|
32c2ce146e | ||
|
4b277afc52 | ||
|
5479c67178 | ||
|
80dbba1280 | ||
|
aa39f2160b | ||
|
a2567bea64 | ||
|
d1b52809ac | ||
|
d06777b8ce | ||
|
7a6476c9ba | ||
|
e4f185f357 | ||
|
df085a6f15 | ||
|
c648d973c1 | ||
|
ec8fb5f308 | ||
|
b83487a70d | ||
|
dbe8f727cb | ||
|
91c70a0e9c | ||
|
37c5b68987 | ||
|
e861f05b75 | ||
|
552c93abf0 | ||
|
b7c1d55491 | ||
|
9876d126ca | ||
|
9547d47ae2 | ||
|
5fca17d7e1 | ||
|
416517b0c9 | ||
|
9d8ea2f13b | ||
|
88fa7fc24c | ||
|
53ee636fa0 | ||
|
873f5dbe6b | ||
|
db520a09ee | ||
|
866908d2ca | ||
|
377d59abe7 | ||
|
d9e7d64f33 | ||
|
1b90ec58b9 | ||
|
d923bab828 | ||
|
48728e2d66 | ||
|
e529a4c261 | ||
|
eff5cc0568 | ||
|
c6d6dbfdb1 | ||
|
8f214aec89 | ||
|
abc6b9459a | ||
|
d804372d74 | ||
|
018e270336 | ||
|
2a728ee68f | ||
|
3d4f62081e | ||
|
ef0fcb0e0f | ||
|
f8b8b9ac63 | ||
|
2a6b542b09 | ||
|
c3064dfd2b | ||
|
cd4466a626 | ||
|
e5a61667dd | ||
|
2496aa8e3f | ||
|
004993583b | ||
|
443fd8f7dd | ||
|
b2fb28453f | ||
|
fc98cf0037 | ||
|
6db75bc244 | ||
|
d6ca562b03 | ||
|
3dbd83e35a | ||
|
8eeabd2372 | ||
|
ed9cb4219d | ||
|
ef92fd775c | ||
|
abaeab89aa | ||
|
243bcb2368 | ||
|
86f2693040 | ||
|
b6d1c5b17a | ||
|
039dfc302c | ||
|
56fd714de2 | ||
|
e51ac2c973 | ||
|
cadde3ab6d | ||
|
9987e64e8c | ||
|
98647b490c | ||
|
32118cc1cb | ||
|
63f41cf1c6 | ||
|
e5aed098b5 | ||
|
5e6e625694 | ||
|
a95454d338 | ||
|
ad75048678 | ||
|
402c761a23 | ||
|
66f9ece061 | ||
|
27b8617077 | ||
|
2ab989e274 | ||
|
5a11ca86bb | ||
|
25e6d6a7bf | ||
|
eb1040ddb7 | ||
|
a68445692b | ||
|
48935d2932 | ||
|
83ed0b38c1 | ||
|
90670e7401 | ||
|
a105e5664a | ||
|
b8442d536a | ||
|
6688a2c112 | ||
|
33cfeaf9b0 | ||
|
f487dac047 | ||
|
690eb2a52b | ||
|
20b52fcef9 | ||
|
0ac5e5035c | ||
|
c6b9c8eca0 | ||
|
ecbb77c17f | ||
|
bb8acc61db | ||
|
90cabd7c21 | ||
|
c6d2233978 | ||
|
6d5aca4f32 | ||
|
248ef5a0ea | ||
|
560acb7cea | ||
|
5fefa9e97c | ||
|
1c5f8070e5 | ||
|
506907ddc9 | ||
|
84f0f451a0 | ||
|
fa466a54cd | ||
|
3c668c2f8e | ||
|
779278ed50 | ||
|
96f70118ca | ||
|
4e62b62add | ||
|
9cfbe98a23 | ||
|
31a7e9feed | ||
|
20ad8a379d | ||
|
8f17b81329 | ||
|
76a93fabc7 | ||
|
98eed4f2ed | ||
|
2195ae59d6 | ||
|
4f88857442 | ||
|
01d53c0160 | ||
|
d98cd6f135 | ||
|
dc567f99d6 | ||
|
ffd7034c00 | ||
|
43c25c8a32 | ||
|
a71deeda94 | ||
|
89b4f45fe3 | ||
|
9835312033 | ||
|
1ff0d0f1fa | ||
|
1a73159200 | ||
|
c417877eb8 | ||
|
9ec4368c6f | ||
|
3f44d51355 | ||
|
95bd9e8e0b | ||
|
bc92503c92 | ||
|
5ba106d96b | ||
|
fc5764f9df | ||
|
342f3f450b | ||
|
0c6b5e01fb | ||
|
6507a26cc1 | ||
|
e72c6a0d94 | ||
|
834a0ed620 | ||
|
1af962899d | ||
|
11e787c884 | ||
|
1c19856d26 | ||
|
d73ba71ec6 | ||
|
dc07037edf | ||
|
21622ac313 | ||
|
ce190a7485 | ||
|
cf4c3642ce | ||
|
021fa1ca1a | ||
|
3a542bce62 | ||
|
c5e6a34f25 | ||
|
1537389617 | ||
|
b07d29b1af | ||
|
b2796f99b6 | ||
|
bbb05b5286 | ||
|
60f89c8c01 | ||
|
8513a5e2d6 | ||
|
69f8738d00 | ||
|
c32507252e | ||
|
2e2f084f66 | ||
|
e1c0c6af7d | ||
|
86de88ed48 | ||
|
1042f9847a | ||
|
a2964afd42 | ||
|
539b5627fd | ||
|
cbd10309f5 | ||
|
362a40db6f | ||
|
861a7834fc | ||
|
307ade6251 | ||
|
0b5354f13d | ||
|
707c5668a5 | ||
|
0277cd82ea | ||
|
9cea5cd442 | ||
|
a6fc743d85 | ||
|
fa968996ed | ||
|
4cd45b6535 | ||
|
2af9ffa7f2 | ||
|
39197458f4 | ||
|
35bbe12065 | ||
|
9add86144c | ||
|
03c8d65d07 | ||
|
75e6acd6ed | ||
|
95b4189d69 | ||
|
22dd91fc21 | ||
|
700370ac5c | ||
|
05de60a7fe | ||
|
cc41cdbf22 | ||
|
c05af1b63c | ||
|
33db37a915 | ||
|
e398c37526 | ||
|
655672c957 | ||
|
2282f4bd37 | ||
|
ce845ab092 | ||
|
b5b6458f12 | ||
|
56e13c8919 | ||
|
23d467eb0d | ||
|
c741b67c3c | ||
|
5a5741878c | ||
|
4463d58470 | ||
|
f0bbc75038 | ||
|
fda8f7e305 | ||
|
52b212db64 | ||
|
931d24b5a8 | ||
|
18dfa56752 | ||
|
26ab108890 | ||
|
1cc174c007 | ||
|
e26f563f4b | ||
|
ebd0a1722d | ||
|
f81c49ce6d | ||
|
2f7181e236 | ||
|
2275a1539e | ||
|
f2266ea9f4 | ||
|
82ff878e38 | ||
|
7200bc3fba | ||
|
a48c0ad868 | ||
|
e4cc5c479f | ||
|
014c18ead2 | ||
|
3bd873f3c6 | ||
|
6c4f424887 | ||
|
04257d8ecc | ||
|
b69f5afaaf | ||
|
5db883906a | ||
|
703924d6c4 | ||
|
330b8cf8a1 | ||
|
6e778ad710 | ||
|
f44e3dc319 | ||
|
d8b2d39f2f | ||
|
7c7ca1cb90 | ||
|
1058e5fb72 | ||
|
b2a9b87be3 | ||
|
3f9f29ba4e | ||
|
390db9503f | ||
|
3448f86263 | ||
|
3252654ed3 | ||
|
641e3fdf7a | ||
|
de33ec4250 | ||
|
25447329a0 | ||
|
dc9fed4a5f | ||
|
88a24da272 | ||
|
e4655c9b07 | ||
|
45d12dbc83 | ||
|
189835b963 | ||
|
3163cbdf8a | ||
|
1e6f9f9fe2 | ||
|
3091869115 | ||
|
58d70b2079 | ||
|
0e9e6b3443 | ||
|
9199fd5964 |
49
.github/workflows/ci.yml
vendored
49
.github/workflows/ci.yml
vendored
@@ -7,6 +7,8 @@ on:
|
||||
- develop
|
||||
- github_actions_tests
|
||||
tags:
|
||||
release:
|
||||
types: [published]
|
||||
pull_request:
|
||||
schedule:
|
||||
- cron: '0 5 * * 4'
|
||||
@@ -18,7 +20,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-18.04, macos-latest ]
|
||||
python-version: [3.7]
|
||||
python-version: [3.7, 3.8]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
@@ -64,19 +66,17 @@ jobs:
|
||||
pip install -e .
|
||||
|
||||
- name: Tests
|
||||
env:
|
||||
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
|
||||
COVERALLS_SERVICE_NAME: travis-ci
|
||||
TRAVIS: "true"
|
||||
run: |
|
||||
pytest --random-order --cov=freqtrade --cov-config=.coveragerc
|
||||
|
||||
- name: Coveralls
|
||||
if: (startsWith(matrix.os, 'ubuntu') && matrix.python-version == '3.8')
|
||||
env:
|
||||
# Coveralls token. Not used as secret due to github not providing secrets to forked repositories
|
||||
COVERALLS_REPO_TOKEN: 6D1m0xupS3FgutfuGao8keFf9Hc0FpIXu
|
||||
run: |
|
||||
# Allow failure for coveralls
|
||||
# Fake travis environment to get coveralls working correctly
|
||||
export TRAVIS_PULL_REQUEST="https://github.com/${GITHUB_REPOSITORY}/pull/$(cat $GITHUB_EVENT_PATH | jq -r .number)"
|
||||
export TRAVIS_BRANCH=${GITHUB_REF#"ref/heads"}
|
||||
export CI_BRANCH=${GITHUB_REF#"ref/heads"}
|
||||
echo "${TRAVIS_BRANCH}"
|
||||
coveralls || true
|
||||
coveralls -v || true
|
||||
|
||||
- name: Backtesting
|
||||
run: |
|
||||
@@ -193,15 +193,40 @@ jobs:
|
||||
deploy:
|
||||
needs: [ build, build_windows, docs_check ]
|
||||
runs-on: ubuntu-18.04
|
||||
if: (github.event_name == 'push' || github.event_name == 'schedule') && github.repository == 'freqtrade/freqtrade'
|
||||
if: (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'release') && github.repository == 'freqtrade/freqtrade'
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.8
|
||||
|
||||
- name: Extract branch name
|
||||
shell: bash
|
||||
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
|
||||
id: extract_branch
|
||||
|
||||
- name: Build distribution
|
||||
run: |
|
||||
pip install -U setuptools wheel
|
||||
python setup.py sdist bdist_wheel
|
||||
|
||||
- name: Publish to PyPI (Test)
|
||||
uses: pypa/gh-action-pypi-publish@master
|
||||
if: (steps.extract_branch.outputs.branch == 'master' || github.event_name == 'release')
|
||||
with:
|
||||
user: __token__
|
||||
password: ${{ secrets.pypi_test_password }}
|
||||
repository_url: https://test.pypi.org/legacy/
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@master
|
||||
if: (steps.extract_branch.outputs.branch == 'master' || github.event_name == 'release')
|
||||
with:
|
||||
user: __token__
|
||||
password: ${{ secrets.pypi_password }}
|
||||
|
||||
- name: Build and test and push docker image
|
||||
env:
|
||||
IMAGE_NAME: freqtradeorg/freqtrade
|
||||
|
@@ -48,7 +48,7 @@ pytest tests/test_<file_name>.py::test_<method_name>
|
||||
#### Run Flake8
|
||||
|
||||
```bash
|
||||
flake8 freqtrade
|
||||
flake8 freqtrade tests scripts
|
||||
```
|
||||
|
||||
We receive a lot of code that fails the `flake8` checks.
|
||||
@@ -109,11 +109,11 @@ Exceptions:
|
||||
|
||||
Contributors may be given commit privileges. Preference will be given to those with:
|
||||
|
||||
1. Past contributions to FreqTrade and other related open-source projects. Contributions to FreqTrade include both code (both accepted and pending) and friendly participation in the issue tracker and Pull request reviews. Quantity and quality are considered.
|
||||
1. Past contributions to Freqtrade and other related open-source projects. Contributions to Freqtrade include both code (both accepted and pending) and friendly participation in the issue tracker and Pull request reviews. Quantity and quality are considered.
|
||||
1. A coding style that the other core committers find simple, minimal, and clean.
|
||||
1. Access to resources for cross-platform development and testing.
|
||||
1. Time to devote to the project regularly.
|
||||
|
||||
Being a Committer does not grant write permission on `develop` or `master` for security reasons (Users trust FreqTrade with their Exchange API keys).
|
||||
Being a Committer does not grant write permission on `develop` or `master` for security reasons (Users trust Freqtrade with their Exchange API keys).
|
||||
|
||||
After being Committer for some time, a Committer may be named Core Committer and given full repository access.
|
||||
|
@@ -1,4 +1,4 @@
|
||||
FROM python:3.7.5-slim-stretch
|
||||
FROM python:3.8.1-slim-buster
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get -y install curl build-essential libssl-dev \
|
||||
|
@@ -1,6 +1,6 @@
|
||||
# Freqtrade
|
||||
|
||||
[](https://travis-ci.org/freqtrade/freqtrade)
|
||||
[](https://github.com/freqtrade/freqtrade/actions/)
|
||||
[](https://coveralls.io/github/freqtrade/freqtrade?branch=develop)
|
||||
[](https://www.freqtrade.io)
|
||||
[](https://codeclimate.com/github/freqtrade/freqtrade/maintainability)
|
||||
|
@@ -1,11 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
import warnings
|
||||
import logging
|
||||
|
||||
from freqtrade.main import main
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
warnings.warn(
|
||||
"Deprecated - To continue to run the bot like this, please run `pip install -e .` again.",
|
||||
DeprecationWarning)
|
||||
main(sys.argv[1:])
|
||||
|
||||
logger.error("DEPRECATED installation detected, please run `pip install -e .` again.")
|
||||
|
||||
sys.exit(2)
|
||||
|
@@ -2,6 +2,7 @@
|
||||
# Downloaded from https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib
|
||||
# Invoke-WebRequest -Uri "https://download.lfd.uci.edu/pythonlibs/xxxxxxx/TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl" -OutFile "TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl"
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
pip install build_helpers\TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
|
||||
|
||||
pip install -r requirements-dev.txt
|
||||
|
@@ -23,7 +23,7 @@ if [ $? -ne 0 ]; then
|
||||
fi
|
||||
|
||||
# Run backtest
|
||||
docker run --rm -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy DefaultStrategy
|
||||
docker run --rm -v $(pwd)/config.json.example:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy DefaultStrategy
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "failed running backtest"
|
||||
|
@@ -2,6 +2,7 @@
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"ticker_interval": "5m",
|
||||
"dry_run": false,
|
||||
@@ -43,7 +44,7 @@
|
||||
"DASH/BTC",
|
||||
"ZEC/BTC",
|
||||
"XLM/BTC",
|
||||
"NXT/BTC",
|
||||
"XRP/BTC",
|
||||
"TRX/BTC",
|
||||
"ADA/BTC",
|
||||
"XMR/BTC"
|
||||
@@ -59,7 +60,6 @@
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
|
@@ -2,6 +2,7 @@
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"ticker_interval": "5m",
|
||||
"dry_run": true,
|
||||
@@ -64,7 +65,6 @@
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
|
@@ -2,8 +2,11 @@
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "BTC",
|
||||
"stake_amount": 0.05,
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"amount_reserve_percent": 0.05,
|
||||
"amend_last_stake_amount": false,
|
||||
"last_stake_amount_min_ratio": 0.5,
|
||||
"dry_run": false,
|
||||
"ticker_interval": "5m",
|
||||
"trailing_stop": false,
|
||||
@@ -59,8 +62,8 @@
|
||||
"refresh_period": 1800
|
||||
},
|
||||
{"method": "PrecisionFilter"},
|
||||
{"method": "PriceFilter", "low_price_ratio": 0.01
|
||||
}
|
||||
{"method": "PriceFilter", "low_price_ratio": 0.01},
|
||||
{"method": "SpreadFilter", "max_spread_ratio": 0.005}
|
||||
],
|
||||
"exchange": {
|
||||
"name": "bittrex",
|
||||
@@ -96,7 +99,6 @@
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
@@ -127,5 +129,7 @@
|
||||
"heartbeat_interval": 60
|
||||
},
|
||||
"strategy": "DefaultStrategy",
|
||||
"strategy_path": "user_data/strategies/"
|
||||
"strategy_path": "user_data/strategies/",
|
||||
"dataformat_ohlcv": "json",
|
||||
"dataformat_trades": "jsongz"
|
||||
}
|
||||
|
@@ -2,6 +2,7 @@
|
||||
"max_open_trades": 5,
|
||||
"stake_currency": "EUR",
|
||||
"stake_amount": 10,
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "EUR",
|
||||
"ticker_interval": "5m",
|
||||
"dry_run": true,
|
||||
@@ -70,7 +71,6 @@
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"capital_available_percentage": 0.5,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.1,
|
||||
|
@@ -3,6 +3,18 @@ version: '3'
|
||||
services:
|
||||
freqtrade:
|
||||
image: freqtradeorg/freqtrade:master
|
||||
# Build step - only needed when additional dependencies are needed
|
||||
# build:
|
||||
# context: .
|
||||
# dockerfile: "./Dockerfile.technical"
|
||||
restart: unless-stopped
|
||||
container_name: freqtrade
|
||||
volumes:
|
||||
- "./user_data:/freqtrade/user_data"
|
||||
- "./config.json:/freqtrade/config.json"
|
||||
# Default command used when running `docker compose up`
|
||||
command: >
|
||||
trade
|
||||
--logfile /freqtrade/user_data/freqtrade.log
|
||||
--db-url sqlite:////freqtrade/user_data/tradesv3.sqlite
|
||||
--config /freqtrade/user_data/config.json
|
||||
--strategy SampleStrategy
|
||||
|
@@ -4,6 +4,34 @@ This page explains some advanced Hyperopt topics that may require higher
|
||||
coding skills and Python knowledge than creation of an ordinal hyperoptimization
|
||||
class.
|
||||
|
||||
## Derived hyperopt classes
|
||||
|
||||
Custom hyperop classes can be derived in the same way [it can be done for strategies](strategy-customization.md#derived-strategies).
|
||||
|
||||
Applying to hyperoptimization, as an example, you may override how dimensions are defined in your optimization hyperspace:
|
||||
|
||||
```python
|
||||
class MyAwesomeHyperOpt(IHyperOpt):
|
||||
...
|
||||
# Uses default stoploss dimension
|
||||
|
||||
class MyAwesomeHyperOpt2(MyAwesomeHyperOpt):
|
||||
@staticmethod
|
||||
def stoploss_space() -> List[Dimension]:
|
||||
# Override boundaries for stoploss
|
||||
return [
|
||||
Real(-0.33, -0.01, name='stoploss'),
|
||||
]
|
||||
```
|
||||
|
||||
and then quickly switch between hyperopt classes, running optimization process with hyperopt class you need in each particular case:
|
||||
|
||||
```
|
||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt ...
|
||||
or
|
||||
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 ...
|
||||
```
|
||||
|
||||
## Creating and using a custom loss function
|
||||
|
||||
To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 173 KiB After Width: | Height: | Size: 211 KiB |
BIN
docs/assets/plot-dataframe2.png
Normal file
BIN
docs/assets/plot-dataframe2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 190 KiB |
@@ -78,13 +78,17 @@ Please also read about the [strategy startup period](strategy-customization.md#s
|
||||
#### Supplying custom fee value
|
||||
|
||||
Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt.
|
||||
To account for this in backtesting, you can use `--fee 0.001` to supply this value to backtesting.
|
||||
This fee must be a percentage, and will be applied twice (once for trade entry, and once for trade exit).
|
||||
To account for this in backtesting, you can use the `--fee` command line option to supply this value to backtesting.
|
||||
This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit).
|
||||
|
||||
For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:
|
||||
|
||||
```bash
|
||||
freqtrade backtesting --fee 0.001
|
||||
```
|
||||
|
||||
!!! Note
|
||||
Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info.
|
||||
|
||||
#### Running backtest with smaller testset by using timerange
|
||||
|
||||
@@ -115,45 +119,46 @@ A backtesting result will look like that:
|
||||
|
||||
```
|
||||
========================================================= BACKTESTING REPORT ========================================================
|
||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 | 21 |
|
||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 | 8 |
|
||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 | 14 |
|
||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 | 7 |
|
||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 | 10 |
|
||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 | 20 |
|
||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 | 15 |
|
||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 | 17 |
|
||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 | 18 |
|
||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 | 9 |
|
||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 | 21 |
|
||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 | 7 |
|
||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 | 13 |
|
||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 | 5 |
|
||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 | 9 |
|
||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 | 11 |
|
||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 | 23 |
|
||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 | 15 |
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses |
|
||||
|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|--------:|
|
||||
| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 | 0 | 21 |
|
||||
| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 | 0 | 8 |
|
||||
| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 | 0 | 14 |
|
||||
| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 | 0 | 7 |
|
||||
| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 | 0 | 10 |
|
||||
| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 | 0 | 20 |
|
||||
| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 | 0 | 15 |
|
||||
| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 | 0 | 17 |
|
||||
| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 | 0 | 18 |
|
||||
| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 | 0 | 9 |
|
||||
| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 | 0 | 21 |
|
||||
| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 | 0 | 7 |
|
||||
| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 | 0 | 13 |
|
||||
| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 | 0 | 5 |
|
||||
| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 | 0 | 9 |
|
||||
| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 | 0 | 11 |
|
||||
| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 | 0 | 23 |
|
||||
| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 | 0 | 15 |
|
||||
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 |
|
||||
========================================================= SELL REASON STATS =========================================================
|
||||
| Sell Reason | Count |
|
||||
|:-------------------|--------:|
|
||||
| trailing_stop_loss | 205 |
|
||||
| stop_loss | 166 |
|
||||
| sell_signal | 56 |
|
||||
| force_sell | 2 |
|
||||
| Sell Reason | Sells | Wins | Draws | Losses |
|
||||
|:-------------------|--------:|------:|-------:|--------:|
|
||||
| trailing_stop_loss | 205 | 150 | 0 | 55 |
|
||||
| stop_loss | 166 | 0 | 0 | 166 |
|
||||
| sell_signal | 56 | 36 | 0 | 20 |
|
||||
| force_sell | 2 | 0 | 0 | 2 |
|
||||
====================================================== LEFT OPEN TRADES REPORT ======================================================
|
||||
| pair | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:---------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 |
|
||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 |
|
||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 |
|
||||
| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses |
|
||||
|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|--------:|
|
||||
| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 | 0 |
|
||||
| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 | 0 |
|
||||
| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 | 0 |
|
||||
```
|
||||
|
||||
The 1st table contains all trades the bot made, including "left open trades".
|
||||
|
||||
The 2nd table contains a recap of sell reasons.
|
||||
This table can tell you which area needs some additional work (i.e. all `sell_signal` trades are losses, so we should disable the sell-signal or work on improving that).
|
||||
|
||||
The 3rd table contains all trades the bot had to `forcesell` at the end of the backtest period to present a full picture.
|
||||
This is necessary to simulate realistic behaviour, since the backtest period has to end at some point, while realistically, you could leave the bot running forever.
|
||||
@@ -194,7 +199,10 @@ Since backtesting lacks some detailed information about what happens within a ca
|
||||
- Buys happen at open-price
|
||||
- Sell signal sells happen at open-price of the following candle
|
||||
- Low happens before high for stoploss, protecting capital first.
|
||||
- ROI sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%)
|
||||
- ROI
|
||||
- sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%)
|
||||
- sells are never "below the candle", so a ROI of 2% may result in a sell at 2.4% if low was at 2.4% profit
|
||||
- Forcesells caused by `<N>=-1` ROI entries use low as sell value, unless N falls on the candle open (e.g. `120: -1` for 1h candles)
|
||||
- Stoploss sells happen exactly at stoploss price, even if low was lower
|
||||
- Trailing stoploss
|
||||
- High happens first - adjusting stoploss
|
||||
@@ -229,11 +237,11 @@ There will be an additional table comparing win/losses of the different strategi
|
||||
Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
|
||||
|
||||
```
|
||||
=========================================================== Strategy Summary ===========================================================
|
||||
| Strategy | buy count | avg profit % | cum profit % | tot profit BTC | tot profit % | avg duration | profit | loss |
|
||||
|:------------|------------:|---------------:|---------------:|-----------------:|---------------:|:---------------|---------:|-------:|
|
||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |
|
||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 825 |
|
||||
=========================================================== STRATEGY SUMMARY ===========================================================
|
||||
| Strategy | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses |
|
||||
|:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|
|
||||
| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 |
|
||||
| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 |
|
||||
```
|
||||
|
||||
## Next step
|
||||
|
@@ -45,19 +45,23 @@ optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--db-url PATH Override trades database URL, this is useful in custom
|
||||
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||
Live Run mode, `sqlite://` for Dry Run).
|
||||
Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for
|
||||
Dry Run).
|
||||
--sd-notify Notify systemd service manager.
|
||||
--dry-run Enforce dry-run for trading (removes Exchange secrets
|
||||
and simulates trades).
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified.
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
Specify configuration file (default:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
@@ -68,6 +72,8 @@ Strategy arguments:
|
||||
Specify strategy class name which will be used by the
|
||||
bot.
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
.
|
||||
|
||||
```
|
||||
|
||||
### How to specify which configuration file be used?
|
||||
@@ -192,8 +198,8 @@ Backtesting also uses the config specified via `-c/--config`.
|
||||
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [-s NAME]
|
||||
[--strategy-path PATH] [-i TICKER_INTERVAL]
|
||||
[--timerange TIMERANGE] [--max_open_trades INT]
|
||||
[--stake_amount STAKE_AMOUNT] [--fee FLOAT]
|
||||
[--timerange TIMERANGE] [--max-open-trades INT]
|
||||
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||
[--eps] [--dmmp]
|
||||
[--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]
|
||||
[--export EXPORT] [--export-filename PATH]
|
||||
@@ -205,10 +211,12 @@ optional arguments:
|
||||
`1d`).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--max_open_trades INT
|
||||
Specify max_open_trades to use.
|
||||
--stake_amount STAKE_AMOUNT
|
||||
Specify stake_amount.
|
||||
--max-open-trades INT
|
||||
Override the value of the `max_open_trades`
|
||||
configuration setting.
|
||||
--stake-amount STAKE_AMOUNT
|
||||
Override the value of the `stake_amount` configuration
|
||||
setting.
|
||||
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||
entry and exit).
|
||||
--eps, --enable-position-stacking
|
||||
@@ -236,12 +244,15 @@ optional arguments:
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified.
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
Specify configuration file (default:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
@@ -270,11 +281,11 @@ to find optimal parameter values for your stategy.
|
||||
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||
[--max_open_trades INT]
|
||||
[--stake_amount STAKE_AMOUNT] [--fee FLOAT]
|
||||
[--max-open-trades INT]
|
||||
[--stake-amount STAKE_AMOUNT] [--fee FLOAT]
|
||||
[--hyperopt NAME] [--hyperopt-path PATH] [--eps]
|
||||
[-e INT]
|
||||
[--spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]]
|
||||
[--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
|
||||
[--dmmp] [--print-all] [--no-color] [--print-json]
|
||||
[-j JOBS] [--random-state INT] [--min-trades INT]
|
||||
[--continue] [--hyperopt-loss NAME]
|
||||
@@ -286,10 +297,12 @@ optional arguments:
|
||||
`1d`).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--max_open_trades INT
|
||||
Specify max_open_trades to use.
|
||||
--stake_amount STAKE_AMOUNT
|
||||
Specify stake_amount.
|
||||
--max-open-trades INT
|
||||
Override the value of the `max_open_trades`
|
||||
configuration setting.
|
||||
--stake-amount STAKE_AMOUNT
|
||||
Override the value of the `stake_amount` configuration
|
||||
setting.
|
||||
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||
entry and exit).
|
||||
--hyperopt NAME Specify hyperopt class name which will be used by the
|
||||
@@ -300,9 +313,9 @@ optional arguments:
|
||||
Allow buying the same pair multiple times (position
|
||||
stacking).
|
||||
-e INT, --epochs INT Specify number of epochs (default: 100).
|
||||
--spaces {all,buy,sell,roi,stoploss} [{all,buy,sell,roi,stoploss} ...]
|
||||
--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
|
||||
Specify which parameters to hyperopt. Space-separated
|
||||
list. Default: `all`.
|
||||
list.
|
||||
--dmmp, --disable-max-market-positions
|
||||
Disable applying `max_open_trades` during backtest
|
||||
(same as setting `max_open_trades` to a very high
|
||||
@@ -329,17 +342,21 @@ optional arguments:
|
||||
generate completely different results, since the
|
||||
target for optimization is different. Built-in
|
||||
Hyperopt-loss-functions are: DefaultHyperOptLoss,
|
||||
OnlyProfitHyperOptLoss, SharpeHyperOptLoss (default:
|
||||
OnlyProfitHyperOptLoss, SharpeHyperOptLoss,
|
||||
SharpeHyperOptLossDaily.(default:
|
||||
`DefaultHyperOptLoss`).
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified.
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
Specify configuration file (default:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
@@ -350,6 +367,7 @@ Strategy arguments:
|
||||
Specify strategy class name which will be used by the
|
||||
bot.
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
|
||||
```
|
||||
|
||||
## Edge commands
|
||||
@@ -360,7 +378,7 @@ To know your trade expectancy and winrate against historical data, you can use E
|
||||
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
|
||||
[--userdir PATH] [-s NAME] [--strategy-path PATH]
|
||||
[-i TICKER_INTERVAL] [--timerange TIMERANGE]
|
||||
[--max_open_trades INT] [--stake_amount STAKE_AMOUNT]
|
||||
[--max-open-trades INT] [--stake-amount STAKE_AMOUNT]
|
||||
[--fee FLOAT] [--stoplosses STOPLOSS_RANGE]
|
||||
|
||||
optional arguments:
|
||||
@@ -370,10 +388,12 @@ optional arguments:
|
||||
`1d`).
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
--max_open_trades INT
|
||||
Specify max_open_trades to use.
|
||||
--stake_amount STAKE_AMOUNT
|
||||
Specify stake_amount.
|
||||
--max-open-trades INT
|
||||
Override the value of the `max_open_trades`
|
||||
configuration setting.
|
||||
--stake-amount STAKE_AMOUNT
|
||||
Override the value of the `stake_amount` configuration
|
||||
setting.
|
||||
--fee FLOAT Specify fee ratio. Will be applied twice (on trade
|
||||
entry and exit).
|
||||
--stoplosses STOPLOSS_RANGE
|
||||
@@ -384,12 +404,15 @@ optional arguments:
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified.
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
Specify configuration file (default:
|
||||
`userdir/config.json` or `config.json` whichever
|
||||
exists). Multiple --config options may be used. Can be
|
||||
set to `-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
@@ -400,6 +423,7 @@ Strategy arguments:
|
||||
Specify strategy class name which will be used by the
|
||||
bot.
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
|
||||
```
|
||||
|
||||
To understand edge and how to read the results, please read the [edge documentation](edge.md).
|
||||
|
@@ -38,74 +38,81 @@ The prevelance for all Options is as follows:
|
||||
|
||||
Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways.
|
||||
|
||||
| Command | Description |
|
||||
|----------|-------------|
|
||||
| `max_open_trades` | **Required.** Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades).<br> ***Datatype:*** *Positive integer or -1.*
|
||||
| `stake_currency` | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *String*
|
||||
| `stake_amount` | **Required.** Amount of crypto-currency your bot will use for each trade. Set it to `"unlimited"` to allow the bot to use all available balance. [More information below](#understand-stake_amount). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Positive float or `"unlimited"`.*
|
||||
| `amount_reserve_percent` | Reserve some amount in min pair stake amount. The bot will reserve `amount_reserve_percent` + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. <br>*Defaults to `0.05` (5%).* <br> ***Datatype:*** *Positive Float as ratio.*
|
||||
| `ticker_interval` | The ticker interval to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *String*
|
||||
| `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> ***Datatype:*** *String*
|
||||
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||
| `dry_run_wallet` | Overrides the default amount of 999.9 stake currency units in the wallet used by the bot running in the Dry Run mode if you need it for any reason. <br> ***Datatype:*** *Float*
|
||||
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||
| `minimal_roi` | **Required.** Set the threshold in percent the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Dict*
|
||||
| `stoploss` | **Required.** Value of the stoploss in percent used by the bot. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Float (as ratio)*
|
||||
| `trailing_stop` | Enables trailing stoploss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Boolean*
|
||||
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Float*
|
||||
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> ***Datatype:*** *Float*
|
||||
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled. <br> ***Datatype:*** *Integer*
|
||||
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled. <br> ***Datatype:*** *Integer*
|
||||
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#understand-ask_last_balance).
|
||||
| `bid_strategy.use_order_book` | Enable buying using the rates in Order Book Bids. <br> ***Datatype:*** *Boolean*
|
||||
| `bid_strategy.order_book_top` | Bot will use the top N rate in Order Book Bids. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids. *Defaults to `1`.* <br> ***Datatype:*** *Positive Integer*
|
||||
| `bid_strategy. check_depth_of_market.enabled` | Do not buy if the difference of buy orders and sell orders is met in Order Book. <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | The % difference of buy orders and sell orders found in Order Book. A value lesser than 1 means sell orders is greater, while value greater than 1 means buy orders is higher. *Defaults to `0`.* <br> ***Datatype:*** *Float (as ratio)*
|
||||
| `ask_strategy.use_order_book` | Enable selling of open trades using Order Book Asks. <br> ***Datatype:*** *Boolean*
|
||||
| `ask_strategy.order_book_min` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> ***Datatype:*** *Positive Integer*
|
||||
| `ask_strategy.order_book_max` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> ***Datatype:*** *Positive Integer*
|
||||
| `ask_strategy.use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||
| `ask_strategy.sell_profit_only` | Wait until the bot makes a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||
| `ask_strategy.ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> ***Datatype:*** *Boolean*
|
||||
| `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> ***Datatype:*** *Dict*
|
||||
| `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> ***Datatype:*** *Dict*
|
||||
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> ***Datatype:*** *String*
|
||||
| `exchange.sandbox` | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.<br> ***Datatype:*** *Boolean*
|
||||
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||
| `exchange.secret` | API secret to use for the exchange. Only required when you are in production mode. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||
| `exchange.password` | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||
| `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Not used by VolumePairList (see [below](#dynamic-pairlists)). <br> ***Datatype:*** *List*
|
||||
| `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting (see [below](#dynamic-pairlists)). <br> ***Datatype:*** *List*
|
||||
| `exchange.ccxt_config` | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> ***Datatype:*** *Dict*
|
||||
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> ***Datatype:*** *Dict*
|
||||
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> ***Datatype:*** *Positive Integer*
|
||||
| Parameter | Description |
|
||||
|------------|-------------|
|
||||
| `max_open_trades` | **Required.** Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades). [More information below](#configuring-amount-per-trade).<br> **Datatype:** Positive integer or -1.
|
||||
| `stake_currency` | **Required.** Crypto-currency used for trading. [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String
|
||||
| `stake_amount` | **Required.** Amount of crypto-currency your bot will use for each trade. Set it to `"unlimited"` to allow the bot to use all available balance. [More information below](#configuring-amount-per-trade). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Positive float or `"unlimited"`.
|
||||
| `tradable_balance_ratio` | Ratio of the total account balance the bot is allowed to trade. [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.99` 99%).*<br> **Datatype:** Positive float between `0.1` and `1.0`.
|
||||
| `amend_last_stake_amount` | Use reduced last stake amount if necessary. [More information below](#configuring-amount-per-trade). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `last_stake_amount_min_ratio` | Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if `amend_last_stake_amount` is set to `true`). [More information below](#configuring-amount-per-trade). <br>*Defaults to `0.5`.* <br> **Datatype:** Float (as ratio)
|
||||
| `amount_reserve_percent` | Reserve some amount in min pair stake amount. The bot will reserve `amount_reserve_percent` + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. <br>*Defaults to `0.05` (5%).* <br> **Datatype:** Positive Float as ratio.
|
||||
| `ticker_interval` | The ticker interval to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** String
|
||||
| `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency). <br> **Datatype:** String
|
||||
| `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
|
||||
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `minimal_roi` | **Required.** Set the threshold in percent the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
||||
| `stoploss` | **Required.** Value of the stoploss in percent used by the bot. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float (as ratio)
|
||||
| `trailing_stop` | Enables trailing stoploss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Boolean
|
||||
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float
|
||||
| `trailing_stop_positive_offset` | Offset on when to apply `trailing_stop_positive`. Percentage value which should be positive. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0` (no offset).* <br> **Datatype:** Float
|
||||
| `trailing_only_offset_is_reached` | Only apply trailing stoploss when the offset is reached. [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `unfilledtimeout.buy` | **Required.** How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||
| `unfilledtimeout.sell` | **Required.** How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
|
||||
| `bid_strategy.ask_last_balance` | **Required.** Set the bidding price. More information [below](#buy-price-without-orderbook).
|
||||
| `bid_strategy.use_order_book` | Enable buying using the rates in [Order Book Bids](#buy-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
||||
| `bid_strategy.order_book_top` | Bot will use the top N rate in Order Book Bids to buy. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in [Order Book Bids](#buy-price-with-orderbook-enabled). <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||
| `bid_strategy. check_depth_of_market.enabled` | Do not buy if the difference of buy orders and sell orders is met in Order Book. [Check market depth](#check-depth-of-market). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `bid_strategy. check_depth_of_market.bids_to_ask_delta` | The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. [Check market depth](#check-depth-of-market) <br> *Defaults to `0`.* <br> **Datatype:** Float (as ratio)
|
||||
| `ask_strategy.use_order_book` | Enable selling of open trades using [Order Book Asks](#sell-price-with-orderbook-enabled). <br> **Datatype:** Boolean
|
||||
| `ask_strategy.order_book_min` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||
| `ask_strategy.order_book_max` | Bot will scan from the top min to max Order Book Asks searching for a profitable rate. <br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
|
||||
| `ask_strategy.use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||
| `ask_strategy.sell_profit_only` | Wait until the bot makes a positive profit before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `ask_strategy.ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `order_types` | Configure order-types depending on the action (`"buy"`, `"sell"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict
|
||||
| `order_time_in_force` | Configure time in force for buy and sell orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
|
||||
| `exchange.name` | **Required.** Name of the exchange class to use. [List below](#user-content-what-values-for-exchangename). <br> **Datatype:** String
|
||||
| `exchange.sandbox` | Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See [here](sandbox-testing.md) in more details.<br> **Datatype:** Boolean
|
||||
| `exchange.key` | API key to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `exchange.secret` | API secret to use for the exchange. Only required when you are in production mode.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `exchange.password` | API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests.<br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `exchange.pair_whitelist` | List of pairs to use by the bot for trading and to check for potential trades during backtesting. Not used by VolumePairList (see [below](#dynamic-pairlists)). <br> **Datatype:** List
|
||||
| `exchange.pair_blacklist` | List of pairs the bot must absolutely avoid for trading and backtesting (see [below](#dynamic-pairlists)). <br> **Datatype:** List
|
||||
| `exchange.ccxt_config` | Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||
| `exchange.ccxt_async_config` | Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the [ccxt documentation](https://ccxt.readthedocs.io/en/latest/manual.html#instantiation) <br> **Datatype:** Dict
|
||||
| `exchange.markets_refresh_interval` | The interval in minutes in which markets are reloaded. <br>*Defaults to `60` minutes.* <br> **Datatype:** Positive Integer
|
||||
| `edge.*` | Please refer to [edge configuration document](edge.md) for detailed explanation.
|
||||
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> ***Datatype:*** *Boolean*
|
||||
| `pairlists` | Define one or more pairlists to be used. [More information below](#dynamic-pairlists). <br>*Defaults to `StaticPairList`.* <br> ***Datatype:*** *List of Dicts*
|
||||
| `telegram.enabled` | Enable the usage of Telegram. <br> ***Datatype:*** *Boolean*
|
||||
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. **Keep it in secret, do not disclose publicly.** <br> ***Datatype:*** *String*
|
||||
| `webhook.enabled` | Enable usage of Webhook notifications <br> ***Datatype:*** *Boolean*
|
||||
| `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||
| `webhook.webhookbuy` | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||
| `webhook.webhooksell` | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||
| `webhook.webhookstatus` | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentationV](webhook-config.md) for more details. <br> ***Datatype:*** *String*
|
||||
| `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *Boolean*
|
||||
| `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *IPv4*
|
||||
| `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details. <br> ***Datatype:*** *Integer between 1024 and 65535*
|
||||
| `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. **Keep it in secret, do not disclose publicly.**<br> ***Datatype:*** *String*
|
||||
| `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. **Keep it in secret, do not disclose publicly.**<br> ***Datatype:*** *String*
|
||||
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite://` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> ***Datatype:*** *String, SQLAlchemy connect string*
|
||||
| `initial_state` | Defines the initial application state. More information below. <br>*Defaults to `stopped`.* <br> ***Datatype:*** *Enum, either `stopped` or `running`*
|
||||
| `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> ***Datatype:*** *Boolean*
|
||||
| `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> ***Datatype:*** *ClassName*
|
||||
| `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> ***Datatype:*** *String*
|
||||
| `internals.process_throttle_secs` | Set the process throttle. Value in second. <br>*Defaults to `5` seconds.* <br> ***Datatype:*** *Positive Integer*
|
||||
| `internals.heartbeat_interval` | Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. <br>*Defaults to `60` seconds.* <br> ***Datatype:*** *Positive Integer or 0*
|
||||
| `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> ***Datatype:*** *Boolean*
|
||||
| `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> ***Datatype:*** *String*
|
||||
| `user_data_dir` | Directory containing user data. <br> *Defaults to `./user_data/`*. <br> ***Datatype:*** *String*
|
||||
| `experimental.block_bad_exchanges` | Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. <br>*Defaults to `true`.* <br> **Datatype:** Boolean
|
||||
| `pairlists` | Define one or more pairlists to be used. [More information below](#dynamic-pairlists). <br>*Defaults to `StaticPairList`.* <br> **Datatype:** List of Dicts
|
||||
| `telegram.enabled` | Enable the usage of Telegram. <br> **Datatype:** Boolean
|
||||
| `telegram.token` | Your Telegram bot token. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `telegram.chat_id` | Your personal Telegram account id. Only required if `telegram.enabled` is `true`. <br>**Keep it in secret, do not disclose publicly.** <br> **Datatype:** String
|
||||
| `webhook.enabled` | Enable usage of Webhook notifications <br> **Datatype:** Boolean
|
||||
| `webhook.url` | URL for the webhook. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `webhook.webhookbuy` | Payload to send on buy. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `webhook.webhookbuycancel` | Payload to send on buy order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `webhook.webhooksell` | Payload to send on sell. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `webhook.webhooksellcancel` | Payload to send on sell order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `webhook.webhookstatus` | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details. <br> **Datatype:** String
|
||||
| `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details. <br> **Datatype:** Boolean
|
||||
| `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details. <br> **Datatype:** IPv4
|
||||
| `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details. <br>**Datatype:** Integer between 1024 and 65535
|
||||
| `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
|
||||
| `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details. <br>**Keep it in secret, do not disclose publicly.**<br> **Datatype:** String
|
||||
| `db_url` | Declares database URL to use. NOTE: This defaults to `sqlite:///tradesv3.dryrun.sqlite` if `dry_run` is `true`, and to `sqlite:///tradesv3.sqlite` for production instances. <br> **Datatype:** String, SQLAlchemy connect string
|
||||
| `initial_state` | Defines the initial application state. More information below. <br>*Defaults to `stopped`.* <br> **Datatype:** Enum, either `stopped` or `running`
|
||||
| `forcebuy_enable` | Enables the RPC Commands to force a buy. More information below. <br> **Datatype:** Boolean
|
||||
| `strategy` | **Required** Defines Strategy class to use. Recommended to be set via `--strategy NAME`. <br> **Datatype:** ClassName
|
||||
| `strategy_path` | Adds an additional strategy lookup path (must be a directory). <br> **Datatype:** String
|
||||
| `internals.process_throttle_secs` | Set the process throttle. Value in second. <br>*Defaults to `5` seconds.* <br> **Datatype:** Positive Intege
|
||||
| `internals.heartbeat_interval` | Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. <br>*Defaults to `60` seconds.* <br> **Datatype:** Positive Integer or 0
|
||||
| `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details. <br> **Datatype:** Boolean
|
||||
| `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. <br> **Datatype:** String
|
||||
| `user_data_dir` | Directory containing user data. <br> *Defaults to `./user_data/`*. <br> **Datatype:** String
|
||||
| `dataformat_ohlcv` | Data format to use to store OHLCV historic data. <br> *Defaults to `json`*. <br> **Datatype:** String
|
||||
| `dataformat_trades` | Data format to use to store trades historic data. <br> *Defaults to `jsongz`*. <br> **Datatype:** String
|
||||
|
||||
### Parameters in the strategy
|
||||
|
||||
@@ -124,24 +131,63 @@ Values set in the configuration file always overwrite values set in the strategy
|
||||
* `order_time_in_force`
|
||||
* `stake_currency`
|
||||
* `stake_amount`
|
||||
* `unfilledtimeout`
|
||||
* `use_sell_signal` (ask_strategy)
|
||||
* `sell_profit_only` (ask_strategy)
|
||||
* `ignore_roi_if_buy_signal` (ask_strategy)
|
||||
|
||||
### Understand stake_amount
|
||||
### Configuring amount per trade
|
||||
|
||||
The `stake_amount` configuration parameter is an amount of crypto-currency your bot will use for each trade.
|
||||
There are several methods to configure how much of the stake currency the bot will use to enter a trade. All methods respect the [available balance configuration](#available-balance) as explained below.
|
||||
|
||||
The minimal configuration value is 0.0001. Please check your exchange's trading minimums to avoid problems.
|
||||
#### Available balance
|
||||
|
||||
By default, the bot assumes that the `complete amount - 1%` is at it's disposal, and when using [dynamic stake amount](#dynamic-stake-amount), it will split the complete balance into `max_open_trades` buckets per trade.
|
||||
Freqtrade will reserve 1% for eventual fees when entering a trade and will therefore not touch that by default.
|
||||
|
||||
You can configure the "untouched" amount by using the `tradable_balance_ratio` setting.
|
||||
|
||||
For example, if you have 10 ETH available in your wallet on the exchange and `tradable_balance_ratio=0.5` (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers this as available balance. The rest of the wallet is untouched by the trades.
|
||||
|
||||
!!! Warning
|
||||
The `tradable_balance_ratio` setting applies to the current balance (free balance + tied up in trades). Therefore, assuming the starting balance of 1000, a configuration with `tradable_balance_ratio=0.99` will not guarantee that 10 currency units will always remain available on the exchange. For example, the free amount may reduce to 5 units if the total balance is reduced to 500 (either by a losing streak, or by withdrawing balance).
|
||||
|
||||
#### Amend last stake amount
|
||||
|
||||
Assuming we have the tradable balance of 1000 USDT, `stake_amount=400`, and `max_open_trades=3`.
|
||||
The bot would open 2 trades, and will be unable to fill the last trading slot, since the requested 400 USDT are no longer available, since 800 USDT are already tied in other trades.
|
||||
|
||||
To overcome this, the option `amend_last_stake_amount` can be set to `True`, which will enable the bot to reduce stake_amount to the available balance in order to fill the last trade slot.
|
||||
|
||||
In the example above this would mean:
|
||||
|
||||
- Trade1: 400 USDT
|
||||
- Trade2: 400 USDT
|
||||
- Trade3: 200 USDT
|
||||
|
||||
!!! Note
|
||||
This option only applies with [Static stake amount](#static-stake-amount) - since [Dynamic stake amount](#dynamic-stake-amount) divides the balances evenly.
|
||||
|
||||
!!! Note
|
||||
The minimum last stake amount can be configured using `amend_last_stake_amount` - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is `stake_amount * 0.5`. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.
|
||||
|
||||
#### Static stake amount
|
||||
|
||||
The `stake_amount` configuration statically configures the amount of stake-currency your bot will use for each trade.
|
||||
|
||||
The minimal configuration value is 0.0001, however, please check your exchange's trading minimums for the stake currency you're using to avoid problems.
|
||||
|
||||
This setting works in combination with `max_open_trades`. The maximum capital engaged in trades is `stake_amount * max_open_trades`.
|
||||
For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of `max_open_trades=3` and `stake_amount=0.05`.
|
||||
|
||||
To allow the bot to trade all the available `stake_currency` in your account set
|
||||
!!! Note
|
||||
This setting respects the [available balance configuration](#available-balance).
|
||||
|
||||
```json
|
||||
"stake_amount" : "unlimited",
|
||||
```
|
||||
#### Dynamic stake amount
|
||||
|
||||
Alternatively, you can use a dynamic stake amount, which will use the available balance on the exchange, and divide that equally by the amount of allowed trades (`max_open_trades`).
|
||||
|
||||
To configure this, set `stake_amount="unlimited"`. We also recommend to set `tradable_balance_ratio=0.99` (99%) - to keep a minimum balance for eventual fees.
|
||||
|
||||
In this case a trade amount is calculated as:
|
||||
|
||||
@@ -149,6 +195,19 @@ In this case a trade amount is calculated as:
|
||||
currency_balance / (max_open_trades - current_open_trades)
|
||||
```
|
||||
|
||||
To allow the bot to trade all the available `stake_currency` in your account (minus `tradable_balance_ratio`) set
|
||||
|
||||
```json
|
||||
"stake_amount" : "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
```
|
||||
|
||||
!!! Note
|
||||
This configuration will allow increasing / decreasing stakes depending on the performance of the bot (lower stake if bot is loosing, higher stakes if the bot has a winning record, since higher balances are available).
|
||||
|
||||
!!! Note "When using Dry-Run Mode"
|
||||
When using `"stake_amount" : "unlimited",` in combination with Dry-Run, the balance will be simulated starting with a stake of `dry_run_wallet` which will evolve over time. It is therefore important to set `dry_run_wallet` to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency.
|
||||
|
||||
### Understand minimal_roi
|
||||
|
||||
The `minimal_roi` configuration parameter is a JSON object where the key is a duration
|
||||
@@ -169,6 +228,9 @@ This parameter can be set in either Strategy or Configuration file. If you use i
|
||||
`minimal_roi` value from the strategy file.
|
||||
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal roi is disabled unless your trade generates 1000% profit.
|
||||
|
||||
!!! Note "Special case to forcesell after a specific time"
|
||||
A special case presents using `"<N>": -1` as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.
|
||||
|
||||
### Understand stoploss
|
||||
|
||||
Go to the [stoploss documentation](stoploss.md) for more details.
|
||||
@@ -201,13 +263,6 @@ before asking the strategy if we should buy or a sell an asset. After each wait
|
||||
every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or
|
||||
the static list of pairs) if we should buy.
|
||||
|
||||
### Understand ask_last_balance
|
||||
|
||||
The `ask_last_balance` configuration parameter sets the bidding price. Value `0.0` will use `ask` price, `1.0` will
|
||||
use the `last` price and values between those interpolate between ask and last
|
||||
price. Using `ask` price will guarantee quick success in bid, but bot will also
|
||||
end up paying more then would probably have been necessary.
|
||||
|
||||
### Understand order_types
|
||||
|
||||
The `order_types` configuration parameter maps actions (`buy`, `sell`, `stoploss`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
|
||||
@@ -227,7 +282,7 @@ If this is configured, the following 4 values (`buy`, `sell`, `stoploss` and
|
||||
The below is the default which is used if this is not configured in either strategy or configuration file.
|
||||
|
||||
Since `stoploss_on_exchange` uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price.
|
||||
`stoploss` defines the stop-price - and limit should be slightly below this. This defaults to 0.99 / 1%.
|
||||
`stoploss` defines the stop-price - and limit should be slightly below this. This defaults to 0.99 / 1% (configurable via `stoploss_on_exchange_limit_ratio`).
|
||||
Calculation example: we bought the asset at 100$.
|
||||
Stop-price is 95$, then limit would be `95 * 0.99 = 94.05$` - so the stoploss will happen between 95$ and 94.05$.
|
||||
|
||||
@@ -387,6 +442,54 @@ The valid values are:
|
||||
"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"
|
||||
```
|
||||
|
||||
## Prices used for orders
|
||||
|
||||
Prices for regular orders can be controlled via the parameter structures `bid_strategy` for buying and `ask_strategy` for selling.
|
||||
Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.
|
||||
|
||||
!!! Note
|
||||
Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function `fetch_order_book()`, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's `fetch_ticker()`/`fetch_tickers()` functions. Refer to the ccxt library [documentation](https://github.com/ccxt/ccxt/wiki/Manual#market-data) for more details.
|
||||
|
||||
### Buy price
|
||||
|
||||
#### Check depth of market
|
||||
|
||||
When check depth of market is enabled (`bid_strategy.check_depth_of_market.enabled=True`), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.
|
||||
|
||||
Orderbook `bid` (buy) side depth is then divided by the orderbook `ask` (sell) side depth and the resulting delta is compared to the value of the `bid_strategy.check_depth_of_market.bids_to_ask_delta` parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.
|
||||
|
||||
!!! Note
|
||||
A delta value below 1 means that `ask` (sell) orderbook side depth is greater than the depth of the `bid` (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).
|
||||
|
||||
#### Buy price with Orderbook enabled
|
||||
|
||||
When buying with the orderbook enabled (`bid_strategy.use_order_book=True`), Freqtrade fetches the `bid_strategy.order_book_top` entries from the orderbook and then uses the entry specified as `bid_strategy.order_book_top` on the `bid` (buy) side of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
|
||||
|
||||
#### Buy price without Orderbook enabled
|
||||
|
||||
When not using orderbook (`bid_strategy.use_order_book=False`), Freqtrade uses the best `ask` (sell) price from the ticker if it's below the `last` traded price from the ticker. Otherwise (when the `ask` price is not below the `last` price), it calculates a rate between `ask` and `last` price.
|
||||
|
||||
The `bid_strategy.ask_last_balance` configuration parameter controls this. A value of `0.0` will use `ask` price, while `1.0` will use the `last` price and values between those interpolate between ask and last price.
|
||||
|
||||
Using `ask` price often guarantees quicker success in the bid, but the bot can also end up paying more than what would have been necessary.
|
||||
|
||||
### Sell price
|
||||
|
||||
#### Sell price with Orderbook enabled
|
||||
|
||||
When selling with the orderbook enabled (`ask_strategy.use_order_book=True`), Freqtrade fetches the `ask_strategy.order_book_max` entries in the orderbook. Then each of the orderbook steps between `ask_strategy.order_book_min` and `ask_strategy.order_book_max` on the `ask` orderbook side are validated for a profitable sell-possibility based on the strategy configuration and the sell order is placed at the first profitable spot.
|
||||
|
||||
The idea here is to place the sell order early, to be ahead in the queue.
|
||||
|
||||
A fixed slot (mirroring `bid_strategy.order_book_top`) can be defined by setting `ask_strategy.order_book_min` and `ask_strategy.order_book_max` to the same number.
|
||||
|
||||
!!! Warning "Orderbook and stoploss_on_exchange"
|
||||
Using `ask_strategy.order_book_max` higher than 1 may increase the risk, since an eventual [stoploss on exchange](#understand-order_types) will be needed to be cancelled as soon as the order is placed.
|
||||
|
||||
#### Sell price without Orderbook enabled
|
||||
|
||||
When not using orderbook (`ask_strategy.use_order_book=False`), the `bid` price from the ticker will be used as the sell price.
|
||||
|
||||
## Pairlists
|
||||
|
||||
Pairlists define the list of pairs that the bot should trade.
|
||||
@@ -404,6 +507,7 @@ Inactive markets and blacklisted pairs are always removed from the resulting `pa
|
||||
* [`VolumePairList`](#volume-pair-list)
|
||||
* [`PrecisionFilter`](#precision-filter)
|
||||
* [`PriceFilter`](#price-pair-filter)
|
||||
* [`SpreadFilter`](#spread-filter)
|
||||
|
||||
!!! Tip "Testing pairlists"
|
||||
Pairlist configurations can be quite tricky to get right. Best use the [`test-pairlist`](utils.md#test-pairlist) subcommand to test your configuration quickly.
|
||||
@@ -452,6 +556,11 @@ Min price precision is 8 decimals. If price is 0.00000011 - one step would be 0.
|
||||
|
||||
These pairs are dangerous since it may be impossible to place the desired stoploss - and often result in high losses.
|
||||
|
||||
#### Spread Filter
|
||||
Removes pairs that have a difference between asks and bids above the specified ratio (default `0.005`).
|
||||
Example:
|
||||
If `DOGE/BTC` maximum bid is 0.00000026 and minimum ask is 0.00000027 the ratio is calculated as: `1 - bid/ask ~= 0.037` which is `> 0.005`
|
||||
|
||||
### Full Pairlist example
|
||||
|
||||
The below example blacklists `BNB/BTC`, uses `VolumePairList` with `20` assets, sorting by `quoteVolume` and applies both [`PrecisionFilter`](#precision-filter) and [`PriceFilter`](#price-pair-filter), filtering all assets where 1 priceunit is > 1%.
|
||||
@@ -498,8 +607,18 @@ creating trades on the exchange.
|
||||
}
|
||||
```
|
||||
|
||||
Once you will be happy with your bot performance running in the Dry-run mode,
|
||||
you can switch it to production mode.
|
||||
Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode.
|
||||
|
||||
!!! Note
|
||||
A simulated wallet is available during dry-run mode, and will assume a starting capital of `dry_run_wallet` (defaults to 1000).
|
||||
|
||||
### Considerations for dry-run
|
||||
|
||||
* API-keys may or may not be provided. Only Read-Only operations (i.e. operations that do not alter account state) on the exchange are performed in the dry-run mode.
|
||||
* Wallets (`/balance`) are simulated.
|
||||
* Orders are simulated, and will not be posted to the exchange.
|
||||
* In combination with `stoploss_on_exchange`, the stop_loss price is assumed to be filled.
|
||||
* Open orders (not trades, which are stored in the database) are reset on bot restart.
|
||||
|
||||
## Switch to production mode
|
||||
|
||||
@@ -507,6 +626,11 @@ In production mode, the bot will engage your money. Be careful, since a wrong
|
||||
strategy can lose all your money. Be aware of what you are doing when
|
||||
you run it in production mode.
|
||||
|
||||
### Setup your exchange account
|
||||
|
||||
You will need to create API Keys (usually you get `key` and `secret`, some exchanges require an additional `password`) from the Exchange website and you'll need to insert this into the appropriate fields in the configuration or when asked by the `freqtrade new-config` command.
|
||||
API Keys are usually only required for live trading (trading for real money, bot running in "production mode", executing real orders on the exchange) and are not required for the bot running in dry-run (trade simulation) mode. When you setup the bot in dry-run mode, you may fill these fields with empty values.
|
||||
|
||||
### To switch your bot in production mode
|
||||
|
||||
**Edit your `config.json` file.**
|
||||
@@ -528,9 +652,6 @@ you run it in production mode.
|
||||
}
|
||||
```
|
||||
|
||||
!!! Note
|
||||
If you have an exchange API key yet, [see our tutorial](/pre-requisite).
|
||||
|
||||
You should also make sure to read the [Exchanges](exchanges.md) section of the documentation to be aware of potential configuration details specific to your exchange.
|
||||
|
||||
### Using proxy with Freqtrade
|
||||
@@ -555,7 +676,7 @@ freqtrade
|
||||
|
||||
## Embedding Strategies
|
||||
|
||||
FreqTrade provides you with with an easy way to embed the strategy into your configuration file.
|
||||
Freqtrade provides you with with an easy way to embed the strategy into your configuration file.
|
||||
This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field,
|
||||
in your chosen config file.
|
||||
|
||||
|
@@ -8,6 +8,27 @@ You can analyze the results of backtests and trading history easily using Jupyte
|
||||
* Don't forget to start a Jupyter notebook server from within your conda or venv environment or use [nb_conda_kernels](https://github.com/Anaconda-Platform/nb_conda_kernels)*
|
||||
* Copy the example notebook before use so your changes don't get clobbered with the next freqtrade update.
|
||||
|
||||
### Using virtual environment with system-wide Jupyter installation
|
||||
|
||||
Sometimes it can be desired to use a system-wide installation of Jupyter notebook, and use a jupyter kernel from the virtual environment.
|
||||
This prevents you from installing the full jupyter suite multiple times per system, and provides an easy way to switch between tasks (freqtrade / other analytics tasks).
|
||||
|
||||
For this to work, first activate your virtual environment and run the following commands:
|
||||
|
||||
``` bash
|
||||
# Activate virtual environment
|
||||
source .env/bin/activate
|
||||
|
||||
pip install ipykernel
|
||||
ipython kernel install --user --name=freqtrade
|
||||
# Restart jupyter (lab / notebook)
|
||||
# select kernel "freqtrade" in the notebook
|
||||
```
|
||||
|
||||
!!! Note
|
||||
This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the [Project Jupyter](https://jupyter.org/) [documentation](https://jupyter.org/documentation) or [help channels](https://jupyter.org/community).
|
||||
|
||||
|
||||
## Fine print
|
||||
|
||||
Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.
|
||||
|
@@ -12,6 +12,152 @@ Otherwise `--exchange` becomes mandatory.
|
||||
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use `--days xx` with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data.
|
||||
Be carefull though: If the number is too small (which would result in a few missing days), the whole dataset will be removed and only xx days will be downloaded.
|
||||
|
||||
### Usage
|
||||
|
||||
```
|
||||
usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]
|
||||
[--pairs-file FILE] [--days INT] [--dl-trades] [--exchange EXCHANGE]
|
||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]]
|
||||
[--erase] [--data-format-ohlcv {json,jsongz}] [--data-format-trades {json,jsongz}]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Show profits for only these pairs. Pairs are space-separated.
|
||||
--pairs-file FILE File containing a list of pairs to download.
|
||||
--days INT Download data for given number of days.
|
||||
--dl-trades Download trades instead of OHLCV data. The bot will resample trades to the desired timeframe as specified as
|
||||
--timeframes/-t.
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no config is provided.
|
||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]
|
||||
Specify which tickers to download. Space-separated list. Default: `1m 5m`.
|
||||
--erase Clean all existing data for the selected exchange/pairs/timeframes.
|
||||
--data-format-ohlcv {json,jsongz}
|
||||
Storage format for downloaded ohlcv data. (default: `json`).
|
||||
--data-format-trades {json,jsongz}
|
||||
Storage format for downloaded trades data. (default: `jsongz`).
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`
|
||||
to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
|
||||
### Data format
|
||||
|
||||
Freqtrade currently supports 2 dataformats, `json` (plain "text" json files) and `jsongz` (a gzipped version of json files).
|
||||
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
|
||||
|
||||
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` parameters respectivly.
|
||||
|
||||
If the default dataformat has been changed during download, then the keys `dataformat_ohlcv` and `dataformat_trades` in the configuration file need to be adjusted to the selected dataformat as well.
|
||||
|
||||
!!! Note
|
||||
You can convert between data-formats using the [convert-data](#subcommand-convert-data) and [convert-trade-data](#subcommand-convert-trade-data) methods.
|
||||
|
||||
#### Subcommand convert data
|
||||
|
||||
```
|
||||
usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[-p PAIRS [PAIRS ...]] --format-from
|
||||
{json,jsongz} --format-to {json,jsongz}
|
||||
[--erase]
|
||||
[-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Show profits for only these pairs. Pairs are space-
|
||||
separated.
|
||||
--format-from {json,jsongz}
|
||||
Source format for data conversion.
|
||||
--format-to {json,jsongz}
|
||||
Destination format for data conversion.
|
||||
--erase Clean all existing data for the selected
|
||||
exchange/pairs/timeframes.
|
||||
-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]
|
||||
Specify which tickers to download. Space-separated
|
||||
list. Default: `1m 5m`.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
|
||||
##### Example converting data
|
||||
|
||||
The following command will convert all ohlcv (candle) data available in `~/.freqtrade/data/binance` from json to jsongz, saving diskspace in the process.
|
||||
It'll also remove original json data files (`--erase` parameter).
|
||||
|
||||
``` bash
|
||||
freqtrade convert-data --format-from json --format-to jsongz --data-dir ~/.freqtrade/data/binance -t 5m 15m --erase
|
||||
```
|
||||
|
||||
#### Subcommand convert-trade data
|
||||
|
||||
```
|
||||
usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[-p PAIRS [PAIRS ...]] --format-from
|
||||
{json,jsongz} --format-to {json,jsongz}
|
||||
[--erase]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Show profits for only these pairs. Pairs are space-
|
||||
separated.
|
||||
--format-from {json,jsongz}
|
||||
Source format for data conversion.
|
||||
--format-to {json,jsongz}
|
||||
Destination format for data conversion.
|
||||
--erase Clean all existing data for the selected
|
||||
exchange/pairs/timeframes.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
|
||||
##### Example converting trades
|
||||
|
||||
The following command will convert all available trade-data in `~/.freqtrade/data/kraken` from jsongz to json.
|
||||
It'll also remove original jsongz data files (`--erase` parameter).
|
||||
|
||||
``` bash
|
||||
freqtrade convert-trade-data --format-from jsongz --format-to json --data-dir ~/.freqtrade/data/kraken --erase
|
||||
```
|
||||
|
||||
### Pairs file
|
||||
|
||||
In alternative to the whitelist from `config.json`, a `pairs.json` file can be used.
|
||||
|
@@ -1,6 +1,6 @@
|
||||
# Development Help
|
||||
|
||||
This page is intended for developers of FreqTrade, people who want to contribute to the FreqTrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
||||
This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
|
||||
|
||||
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/freqtrade/issues) on [GitHub](https://github.com) and also have a dev channel in [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) where you can ask questions.
|
||||
|
||||
@@ -153,7 +153,7 @@ In VolumePairList, this implements different methods of sorting, does early vali
|
||||
## Implement a new Exchange (WIP)
|
||||
|
||||
!!! Note
|
||||
This section is a Work in Progress and is not a complete guide on how to test a new exchange with FreqTrade.
|
||||
This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade.
|
||||
|
||||
Most exchanges supported by CCXT should work out of the box.
|
||||
|
||||
@@ -183,17 +183,19 @@ raw = ct.fetch_ohlcv(pair, timeframe=timeframe)
|
||||
# convert to dataframe
|
||||
df1 = parse_ticker_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)
|
||||
|
||||
print(df1["date"].tail(1))
|
||||
print(df1.tail(1))
|
||||
print(datetime.utcnow())
|
||||
```
|
||||
|
||||
``` output
|
||||
19 2019-06-08 00:00:00+00:00
|
||||
date open high low close volume
|
||||
499 2019-06-08 00:00:00+00:00 0.000007 0.000007 0.000007 0.000007 26264344.0
|
||||
2019-06-09 12:30:27.873327
|
||||
```
|
||||
|
||||
The output will show the last entry from the Exchange as well as the current UTC date.
|
||||
If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting `"ohlcv_partial_candle"` from the exchange-class untouched / True). Otherwise, set `"ohlcv_partial_candle"` to `False` to not drop Candles (shown in the example above).
|
||||
Another way is to run this command multiple times in a row and observe if the volume is changing (while the date remains the same).
|
||||
|
||||
## Updating example notebooks
|
||||
|
||||
@@ -246,6 +248,17 @@ Determine if crucial bugfixes have been made between this commit and the current
|
||||
git log --oneline --no-decorate --no-merges master..new_release
|
||||
```
|
||||
|
||||
To keep the release-log short, best wrap the full git changelog into a collapsible details secction.
|
||||
|
||||
```markdown
|
||||
<details>
|
||||
<summary>Expand full changelog</summary>
|
||||
|
||||
... Full git changelog
|
||||
|
||||
</details>
|
||||
```
|
||||
|
||||
### Create github release / tag
|
||||
|
||||
Once the PR against master is merged (best right after merging):
|
||||
@@ -253,4 +266,29 @@ Once the PR against master is merged (best right after merging):
|
||||
* Use the button "Draft a new release" in the Github UI (subsection releases).
|
||||
* Use the version-number specified as tag.
|
||||
* Use "master" as reference (this step comes after the above PR is merged).
|
||||
* Use the above changelog as release comment (as codeblock).
|
||||
* Use the above changelog as release comment (as codeblock)
|
||||
|
||||
### After-release
|
||||
|
||||
* Update version in develop by postfixing that with `-dev` (`2019.6 -> 2019.6-dev`).
|
||||
* Create a PR against develop to update that branch.
|
||||
|
||||
## Releases
|
||||
|
||||
### pypi
|
||||
|
||||
To create a pypi release, please run the following commands:
|
||||
|
||||
Additional requirement: `wheel`, `twine` (for uploading), account on pypi with proper permissions.
|
||||
|
||||
``` bash
|
||||
python setup.py sdist bdist_wheel
|
||||
|
||||
# For pypi test (to check if some change to the installation did work)
|
||||
twine upload --repository-url https://test.pypi.org/legacy/ dist/*
|
||||
|
||||
# For production:
|
||||
twine upload dist/*
|
||||
```
|
||||
|
||||
Please don't push non-releases to the productive / real pypi instance.
|
||||
|
137
docs/docker.md
137
docs/docker.md
@@ -1,4 +1,4 @@
|
||||
# Using FreqTrade with Docker
|
||||
# Using Freqtrade with Docker
|
||||
|
||||
## Install Docker
|
||||
|
||||
@@ -8,13 +8,141 @@ Start by downloading and installing Docker CE for your platform:
|
||||
* [Windows](https://docs.docker.com/docker-for-windows/install/)
|
||||
* [Linux](https://docs.docker.com/install/)
|
||||
|
||||
Optionally, [docker-compose](https://docs.docker.com/compose/install/) should be installed and available to follow the [docker quick start guide](#docker-quick-start).
|
||||
|
||||
Once you have Docker installed, simply prepare the config file (e.g. `config.json`) and run the image for `freqtrade` as explained below.
|
||||
|
||||
## Download the official FreqTrade docker image
|
||||
## Freqtrade with docker-compose
|
||||
|
||||
Freqtrade provides an official Docker image on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/), as well as a [docker-compose file](https://github.com/freqtrade/freqtrade/blob/develop/docker-compose.yml) ready for usage.
|
||||
|
||||
!!! Note
|
||||
The following section assumes that docker and docker-compose is installed and available to the logged in user.
|
||||
|
||||
!!! Note
|
||||
All below comands use relative directories and will have to be executed from the directory containing the `docker-compose.yml` file.
|
||||
|
||||
### Docker quick start
|
||||
|
||||
Create a new directory and place the [docker-compose file](https://github.com/freqtrade/freqtrade/blob/develop/docker-compose.yml) in this directory.
|
||||
|
||||
``` bash
|
||||
mkdir ft_userdata
|
||||
cd ft_userdata/
|
||||
# Download the docker-compose file from the repository
|
||||
curl https://raw.githubusercontent.com/freqtrade/freqtrade/develop/docker-compose.yml -o docker-compose.yml
|
||||
|
||||
# Pull the freqtrade image
|
||||
docker-compose pull
|
||||
|
||||
# Create user directory structure
|
||||
docker-compose run --rm freqtrade create-userdir --userdir user_data
|
||||
|
||||
# Create configuration - Requires answering interactive questions
|
||||
docker-compose run --rm freqtrade new-config --config user_data/config.json
|
||||
```
|
||||
|
||||
The above snippet creates a new directory called "ft_userdata", downloads the latest compose file and pulls the freqtrade image.
|
||||
The last 2 steps in the snippet create the directory with user-data, as well as (interactively) the default configuration based on your selections.
|
||||
|
||||
!!! Note
|
||||
You can edit the configuration at any time, which is available as `user_data/config.json` (within the directory `ft_userdata`) when using the above configuration.
|
||||
|
||||
#### Adding your strategy
|
||||
|
||||
The configuration is now available as `user_data/config.json`.
|
||||
You should now copy your strategy to `user_data/strategies/` - and add the Strategy class name to the `docker-compose.yml` file, replacing `SampleStrategy`. If you wish to run the bot with the SampleStrategy, just leave it as it is.
|
||||
|
||||
!!! Warning
|
||||
The `SampleStrategy` is there for your reference and give you ideas for your own strategy.
|
||||
Please always backtest the strategy and use dry-run for some time before risking real money!
|
||||
|
||||
Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above).
|
||||
|
||||
``` bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
#### Docker-compose logs
|
||||
|
||||
Logs will be written to `user_data/freqtrade.log`.
|
||||
Alternatively, you can check the latest logs using `docker-compose logs -f`.
|
||||
|
||||
#### Database
|
||||
|
||||
The database will be in the user_data directory as well, and will be called `user_data/tradesv3.sqlite`.
|
||||
|
||||
#### Updating freqtrade with docker-compose
|
||||
|
||||
To update freqtrade when using docker-compose is as simple as running the following 2 commands:
|
||||
|
||||
``` bash
|
||||
# Download the latest image
|
||||
docker-compose pull
|
||||
# Restart the image
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
This will first pull the latest image, and will then restart the container with the just pulled version.
|
||||
|
||||
!!! Note
|
||||
You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.
|
||||
|
||||
#### Going from here
|
||||
|
||||
Advanced users may edit the docker-compose file further to include all possible options or arguments.
|
||||
|
||||
All possible freqtrade arguments will be available by running `docker-compose run --rm freqtrade <command> <optional arguments>`.
|
||||
|
||||
!!! Note "`docker-compose run --rm`"
|
||||
Including `--rm` will clean up the container after completion, and is highly recommended for all modes except trading mode (running with `freqtrade trade` command).
|
||||
|
||||
##### Example: Download data with docker-compose
|
||||
|
||||
Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory `user_data/data/` on the host.
|
||||
|
||||
``` bash
|
||||
docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h
|
||||
```
|
||||
|
||||
Head over to the [Data Downloading Documentation](data-download.md) for more details on downloading data.
|
||||
|
||||
##### Example: Backtest with docker-compose
|
||||
|
||||
Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe:
|
||||
|
||||
``` bash
|
||||
docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m
|
||||
```
|
||||
|
||||
Head over to the [Backtesting Documentation](backtesting.md) to learn more.
|
||||
|
||||
#### Additional dependencies with docker-compose
|
||||
|
||||
If your strategy requires dependencies not included in the default image (like [technical](https://github.com/freqtrade/technical)) - it will be necessary to build the image on your host.
|
||||
For this, please create a Dockerfile containing installation steps for the additional dependencies (have a look at [Dockerfile.technical](https://github.com/freqtrade/freqtrade/blob/develop/Dockerfile.technical) for an example).
|
||||
|
||||
You'll then also need to modify the `docker-compose.yml` file and uncomment the build step, as well as rename the image to avoid naming collisions.
|
||||
|
||||
``` yaml
|
||||
image: freqtrade_custom
|
||||
build:
|
||||
context: .
|
||||
dockerfile: "./Dockerfile.<yourextension>"
|
||||
```
|
||||
|
||||
You can then run `docker-compose build` to build the docker image, and run it using the commands described above.
|
||||
|
||||
## Freqtrade with docker without docker-compose
|
||||
|
||||
!!! Warning
|
||||
The below documentation is provided for completeness and assumes that you are somewhat familiar with running docker containers. If you're just starting out with docker, we recommend to follow the [Freqtrade with docker-compose](#freqtrade-with-docker-compose) instructions.
|
||||
|
||||
### Download the official Freqtrade docker image
|
||||
|
||||
Pull the image from docker hub.
|
||||
|
||||
Branches / tags available can be checked out on [Dockerhub](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||
Branches / tags available can be checked out on [Dockerhub tags page](https://hub.docker.com/r/freqtradeorg/freqtrade/tags/).
|
||||
|
||||
```bash
|
||||
docker pull freqtradeorg/freqtrade:develop
|
||||
@@ -164,8 +292,7 @@ docker run -d \
|
||||
```
|
||||
|
||||
!!! Note
|
||||
db-url defaults to `sqlite:///tradesv3.sqlite` but it defaults to `sqlite://` if `dry_run=True` is being used.
|
||||
To override this behaviour use a custom db-url value: i.e.: `--db-url sqlite:///tradesv3.dryrun.sqlite`
|
||||
When using docker, it's best to specify `--db-url` explicitly to ensure that the database URL and the mounted database file match.
|
||||
|
||||
!!! Note
|
||||
All available bot command line parameters can be added to the end of the `docker run` command.
|
||||
|
127
docs/edge.md
127
docs/edge.md
@@ -9,6 +9,7 @@ This page explains how to use Edge Positioning module in your bot in order to en
|
||||
Edge does not consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else are ignored in its calculation.
|
||||
|
||||
## Introduction
|
||||
|
||||
Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.
|
||||
|
||||
But it doesn't mean there is no rule, it only means rules should work "most of the time". Let's play a game: we toss a coin, heads: I give you 10$, tails: you give me 10$. Is it an interesting game? No, it's quite boring, isn't it?
|
||||
@@ -22,43 +23,61 @@ Let's complicate it more: you win 80% of the time but only 2$, I win 20% of the
|
||||
The question is: How do you calculate that? How do you know if you wanna play?
|
||||
|
||||
The answer comes to two factors:
|
||||
|
||||
- Win Rate
|
||||
- Risk Reward Ratio
|
||||
|
||||
### Win Rate
|
||||
|
||||
Win Rate (*W*) is is the mean over some amount of trades (*N*) what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only if you won or not).
|
||||
|
||||
```
|
||||
W = (Number of winning trades) / (Total number of trades) = (Number of winning trades) / N
|
||||
```
|
||||
|
||||
Complementary Loss Rate (*L*) is defined as
|
||||
|
||||
```
|
||||
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N
|
||||
```
|
||||
|
||||
or, which is the same, as
|
||||
|
||||
```
|
||||
L = 1 – W
|
||||
```
|
||||
|
||||
### Risk Reward Ratio
|
||||
|
||||
Risk Reward Ratio (*R*) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
|
||||
|
||||
```
|
||||
R = Profit / Loss
|
||||
```
|
||||
|
||||
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
|
||||
|
||||
```
|
||||
Average profit = (Sum of profits) / (Number of winning trades)
|
||||
|
||||
Average loss = (Sum of losses) / (Number of losing trades)
|
||||
|
||||
R = (Average profit) / (Average loss)
|
||||
```
|
||||
|
||||
### Expectancy
|
||||
|
||||
At this point we can combine *W* and *R* to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades and subtracting the percentage of losing trades, which is calculated as follows:
|
||||
|
||||
```
|
||||
Expectancy Ratio = (Risk Reward Ratio X Win Rate) – Loss Rate = (R X W) – L
|
||||
```
|
||||
|
||||
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
|
||||
|
||||
```
|
||||
Expectancy = (5 X 0.28) – 0.72 = 0.68
|
||||
```
|
||||
|
||||
Superficially, this means that on average you expect this strategy’s trades to return .68 times the size of your loses. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
|
||||
|
||||
@@ -69,6 +88,7 @@ You can also use this value to evaluate the effectiveness of modifications to th
|
||||
**NOTICE:** It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology, but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.
|
||||
|
||||
## How does it work?
|
||||
|
||||
If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over *N* trades for each stoploss. Here is an example:
|
||||
|
||||
| Pair | Stoploss | Win Rate | Risk Reward Ratio | Expectancy |
|
||||
@@ -83,6 +103,7 @@ The goal here is to find the best stoploss for the strategy in order to have the
|
||||
Edge module then forces stoploss value it evaluated to your strategy dynamically.
|
||||
|
||||
### Position size
|
||||
|
||||
Edge also dictates the stake amount for each trade to the bot according to the following factors:
|
||||
|
||||
- Allowed capital at risk
|
||||
@@ -90,13 +111,17 @@ Edge also dictates the stake amount for each trade to the bot according to the f
|
||||
|
||||
Allowed capital at risk is calculated as follows:
|
||||
|
||||
```
|
||||
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)
|
||||
```
|
||||
|
||||
Stoploss is calculated as described above against historical data.
|
||||
|
||||
Your position size then will be:
|
||||
|
||||
```
|
||||
Position size = (Allowed capital at risk) / Stoploss
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
@@ -115,94 +140,24 @@ Available capital doesn’t change before a position is sold. Let’s assume tha
|
||||
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be **0.055 / 0.02 = 2.75 ETH**.
|
||||
|
||||
## Configurations
|
||||
|
||||
Edge module has following configuration options:
|
||||
|
||||
#### enabled
|
||||
If true, then Edge will run periodically.
|
||||
|
||||
(defaults to false)
|
||||
|
||||
#### process_throttle_secs
|
||||
How often should Edge run in seconds?
|
||||
|
||||
(defaults to 3600 so one hour)
|
||||
|
||||
#### calculate_since_number_of_days
|
||||
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy
|
||||
Note that it downloads historical data so increasing this number would lead to slowing down the bot.
|
||||
|
||||
(defaults to 7)
|
||||
|
||||
#### capital_available_percentage
|
||||
This is the percentage of the total capital on exchange in stake currency.
|
||||
|
||||
As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital.
|
||||
|
||||
(defaults to 0.5)
|
||||
|
||||
#### allowed_risk
|
||||
Percentage of allowed risk per trade.
|
||||
|
||||
(defaults to 0.01 so 1%)
|
||||
|
||||
#### stoploss_range_min
|
||||
|
||||
Minimum stoploss.
|
||||
|
||||
(defaults to -0.01)
|
||||
|
||||
#### stoploss_range_max
|
||||
|
||||
Maximum stoploss.
|
||||
|
||||
(defaults to -0.10)
|
||||
|
||||
#### stoploss_range_step
|
||||
|
||||
As an example if this is set to -0.01 then Edge will test the strategy for \[-0.01, -0,02, -0,03 ..., -0.09, -0.10\] ranges.
|
||||
Note than having a smaller step means having a bigger range which could lead to slow calculation.
|
||||
|
||||
If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10.
|
||||
|
||||
(defaults to -0.01)
|
||||
|
||||
#### minimum_winrate
|
||||
|
||||
It filters out pairs which don't have at least minimum_winrate.
|
||||
|
||||
This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio.
|
||||
|
||||
(defaults to 0.60)
|
||||
|
||||
#### minimum_expectancy
|
||||
|
||||
It filters out pairs which have the expectancy lower than this number.
|
||||
|
||||
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.
|
||||
|
||||
(defaults to 0.20)
|
||||
|
||||
#### min_trade_number
|
||||
|
||||
When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable.
|
||||
|
||||
Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something.
|
||||
|
||||
(defaults to 10, it is highly recommended not to decrease this number)
|
||||
|
||||
#### max_trade_duration_minute
|
||||
|
||||
Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.
|
||||
|
||||
**NOTICE:** While configuring this value, you should take into consideration your ticker interval. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).
|
||||
|
||||
(defaults to 1 day, i.e. to 60 * 24 = 1440 minutes)
|
||||
|
||||
#### remove_pumps
|
||||
|
||||
Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.
|
||||
|
||||
(defaults to false)
|
||||
| Parameter | Description |
|
||||
|------------|-------------|
|
||||
| `enabled` | If true, then Edge will run periodically. <br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
| `process_throttle_secs` | How often should Edge run in seconds. <br>*Defaults to `3600` (once per hour).* <br> **Datatype:** Integer
|
||||
| `calculate_since_number_of_days` | Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy. <br> **Note** that it downloads historical data so increasing this number would lead to slowing down the bot. <br>*Defaults to `7`.* <br> **Datatype:** Integer
|
||||
| `capital_available_percentage` | **DEPRECATED - [replaced with `tradable_balance_ratio`](configuration.md#Available balance)** This is the percentage of the total capital on exchange in stake currency. <br>As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital. <br>*Defaults to `0.5`.* <br> **Datatype:** Float
|
||||
| `allowed_risk` | Ratio of allowed risk per trade. <br>*Defaults to `0.01` (1%)).* <br> **Datatype:** Float
|
||||
| `stoploss_range_min` | Minimum stoploss. <br>*Defaults to `-0.01`.* <br> **Datatype:** Float
|
||||
| `stoploss_range_max` | Maximum stoploss. <br>*Defaults to `-0.10`.* <br> **Datatype:** Float
|
||||
| `stoploss_range_step` | As an example if this is set to -0.01 then Edge will test the strategy for `[-0.01, -0,02, -0,03 ..., -0.09, -0.10]` ranges. <br> **Note** than having a smaller step means having a bigger range which could lead to slow calculation. <br> If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. <br>*Defaults to `-0.001`.* <br> **Datatype:** Float
|
||||
| `minimum_winrate` | It filters out pairs which don't have at least minimum_winrate. <br>This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. <br>*Defaults to `0.60`.* <br> **Datatype:** Float
|
||||
| `minimum_expectancy` | It filters out pairs which have the expectancy lower than this number. <br>Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return. <br>*Defaults to `0.20`.* <br> **Datatype:** Float
|
||||
| `min_trade_number` | When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. <br>Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. <br>*Defaults to `10` (it is highly recommended not to decrease this number).* <br> **Datatype:** Integer
|
||||
| `max_trade_duration_minute` | Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.<br>**NOTICE:** While configuring this value, you should take into consideration your ticker interval. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).<br>*Defaults to `1440` (one day).* <br> **Datatype:** Integer
|
||||
| `remove_pumps` | Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.<br>*Defaults to `false`.* <br> **Datatype:** Boolean
|
||||
|
||||
## Running Edge independently
|
||||
|
||||
|
@@ -5,7 +5,7 @@ This page combines common gotchas and informations which are exchange-specific a
|
||||
## Binance
|
||||
|
||||
!!! Tip "Stoploss on Exchange"
|
||||
Binance is currently the only exchange supporting `stoploss_on_exchange`. It provides great advantages, so we recommend to benefit from it.
|
||||
Binance supports `stoploss_on_exchange` and uses stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
|
||||
|
||||
### Blacklists
|
||||
|
||||
@@ -22,6 +22,9 @@ Binance has been split into 3, and users must use the correct ccxt exchange ID f
|
||||
|
||||
## Kraken
|
||||
|
||||
!!! Tip "Stoploss on Exchange"
|
||||
Kraken supports `stoploss_on_exchange` and uses stop-loss-market orders. It provides great advantages, so we recommend to benefit from it, however since the resulting order is a stoploss-market order, sell-rates are not guaranteed, which makes this feature less secure than on other exchanges. This limitation is based on kraken's policy [source](https://blog.kraken.com/post/1234/announcement-delisting-pairs-and-temporary-suspension-of-advanced-order-types/) and [source2](https://blog.kraken.com/post/1494/kraken-enables-advanced-orders-and-adds-10-currency-pairs/) - which has stoploss-limit orders disabled.
|
||||
|
||||
### Historic Kraken data
|
||||
|
||||
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.
|
||||
@@ -29,6 +32,10 @@ To download data for the Kraken exchange, using `--dl-trades` is mandatory, othe
|
||||
|
||||
## Bittrex
|
||||
|
||||
### Order types
|
||||
|
||||
Bittrex does not support market orders. If you have a message at the bot startup about this, you should change order type values set in your configuration and/or in the strategy from `"market"` to `"limit"`. See some more details on this [here in the FAQ](faq.md#im-getting-the-exchange-bittrex-does-not-support-market-orders-message-and-cannot-run-my-strategy).
|
||||
|
||||
### Restricted markets
|
||||
|
||||
Bittrex split its exchange into US and International versions.
|
||||
@@ -61,3 +68,24 @@ print(res)
|
||||
```shell
|
||||
$ pip3 install web3
|
||||
```
|
||||
|
||||
### Send incomplete candles to the strategy
|
||||
|
||||
Most exchanges return incomplete candles via their ohlcv / klines interface.
|
||||
By default, Freqtrade assumes that incomplete candles are returned and removes the last candle assuming it's an incomplete candle.
|
||||
|
||||
Whether your exchange returns incomplete candles or not can be checked using [the helper script](developer.md#Incomplete-candles) from the Contributor documentation.
|
||||
|
||||
If the exchange does return incomplete candles and you would like to have incomplete candles in your strategy, you can set the following parameter in the configuration file.
|
||||
|
||||
``` json
|
||||
{
|
||||
|
||||
"exchange": {
|
||||
"_ft_has_params": {"ohlcv_partial_candle": false}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
!!! Warning "Danger of repainting"
|
||||
Changing this parameter makes the strategy responsible to avoid repainting and handle this accordingly. Doing this is therefore not recommended, and should only be performed by experienced users who are fully aware of the impact this setting has.
|
||||
|
18
docs/faq.md
18
docs/faq.md
@@ -45,12 +45,28 @@ the tutorial [here|Testing-new-strategies-with-Hyperopt](bot-usage.md#hyperopt-c
|
||||
|
||||
You can use the `/forcesell all` command from Telegram.
|
||||
|
||||
### I get the message "RESTRICTED_MARKET"
|
||||
### I'm getting the "RESTRICTED_MARKET" message in the log
|
||||
|
||||
Currently known to happen for US Bittrex users.
|
||||
|
||||
Read [the Bittrex section about restricted markets](exchanges.md#restricted-markets) for more information.
|
||||
|
||||
### I'm getting the "Exchange Bittrex does not support market orders." message and cannot run my strategy
|
||||
|
||||
As the message says, Bittrex does not support market orders and you have one of the [order types](configuration.md/#understand-order_types) set to "market". Probably your strategy was written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).
|
||||
|
||||
To fix it for Bittrex, redefine order types in the strategy to use "limit" instead of "market":
|
||||
|
||||
```
|
||||
order_types = {
|
||||
...
|
||||
'stoploss': 'limit',
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Same fix should be done in the configuration file, if order types are defined in your custom config rather than in the strategy.
|
||||
|
||||
### How do I search the bot logs for something?
|
||||
|
||||
By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility subcommands, as well as from the output of your custom `print()`'s you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout.
|
||||
|
@@ -6,8 +6,12 @@ algorithms included in the `scikit-optimize` package to accomplish this. The
|
||||
search will burn all your CPU cores, make your laptop sound like a fighter jet
|
||||
and still take a long time.
|
||||
|
||||
In general, the search for best parameters starts with a few random combinations and then uses Bayesian search with a
|
||||
ML regressor algorithm (currently ExtraTreesRegressor) to quickly find a combination of parameters in the search hyperspace
|
||||
that minimizes the value of the [loss function](#loss-functions).
|
||||
|
||||
Hyperopt requires historic data to be available, just as backtesting does.
|
||||
To learn how to get data for the pairs and exchange you're interrested in, head over to the [Data Downloading](data-download.md) section of the documentation.
|
||||
To learn how to get data for the pairs and exchange you're interested in, head over to the [Data Downloading](data-download.md) section of the documentation.
|
||||
|
||||
!!! Bug
|
||||
Hyperopt can crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
|
||||
@@ -71,8 +75,8 @@ Copy the file `user_data/hyperopts/sample_hyperopt.py` into `user_data/hyperopts
|
||||
|
||||
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
|
||||
|
||||
- Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
- Inside `populate_buy_trend()` - applying the parameters.
|
||||
* Inside `indicator_space()` - the parameters hyperopt shall be optimizing.
|
||||
* Inside `populate_buy_trend()` - applying the parameters.
|
||||
|
||||
There you have two different types of indicators: 1. `guards` and 2. `triggers`.
|
||||
|
||||
@@ -170,10 +174,6 @@ with different value combinations. It will then use the given historical data an
|
||||
buys based on the buy signals generated with the above function and based on the results
|
||||
it will end with telling you which paramter combination produced the best profits.
|
||||
|
||||
The search for best parameters starts with a few random combinations and then uses a
|
||||
regressor algorithm (currently ExtraTreesRegressor) to quickly find a parameter combination
|
||||
that minimizes the value of the [loss function](#loss-functions).
|
||||
|
||||
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
|
||||
When you want to test an indicator that isn't used by the bot currently, remember to
|
||||
add it to the `populate_indicators()` method in your custom hyperopt file.
|
||||
@@ -182,7 +182,7 @@ add it to the `populate_indicators()` method in your custom hyperopt file.
|
||||
|
||||
Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results.
|
||||
|
||||
By default, FreqTrade uses a loss function, which has been with freqtrade since the beginning and optimizes mostly for short trade duration and avoiding losses.
|
||||
By default, Freqtrade uses a loss function, which has been with freqtrade since the beginning and optimizes mostly for short trade duration and avoiding losses.
|
||||
|
||||
A different loss function can be specified by using the `--hyperopt-loss <Class-name>` argument.
|
||||
This class should be in its own file within the `user_data/hyperopts/` directory.
|
||||
@@ -192,6 +192,7 @@ Currently, the following loss functions are builtin:
|
||||
* `DefaultHyperOptLoss` (default legacy Freqtrade hyperoptimization loss function)
|
||||
* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
|
||||
* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on the trade returns)
|
||||
* `SharpeHyperOptLossDaily` (optimizes Sharpe Ratio calculated on daily trade returns)
|
||||
|
||||
Creation of a custom loss function is covered in the [Advanced Hyperopt](advanced-hyperopt.md) part of the documentation.
|
||||
|
||||
@@ -284,6 +285,16 @@ number).
|
||||
You can also enable position stacking in the configuration file by explicitly setting
|
||||
`"position_stacking"=true`.
|
||||
|
||||
### Reproducible results
|
||||
|
||||
The search for optimal parameters starts with a few (currently 30) random combinations in the hyperspace of parameters, random Hyperopt epochs. These random epochs are marked with a leading asterisk sign at the Hyperopt output.
|
||||
|
||||
The initial state for generation of these random values (random state) is controlled by the value of the `--random-state` command line option. You can set it to some arbitrary value of your choice to obtain reproducible results.
|
||||
|
||||
If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the `--random-state` command line option to repeat the set of the initial random epochs used.
|
||||
|
||||
If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyperoptimization results with same random state value used.
|
||||
|
||||
## Understand the Hyperopt Result
|
||||
|
||||
Once Hyperopt is completed you can use the result to create a new strategy.
|
||||
@@ -362,6 +373,7 @@ In order to use this best ROI table found by Hyperopt in backtesting and for liv
|
||||
118: 0
|
||||
}
|
||||
```
|
||||
|
||||
As stated in the comment, you can also use it as the value of the `minimal_roi` setting in the configuration file.
|
||||
|
||||
#### Default ROI Search Space
|
||||
@@ -369,7 +381,7 @@ As stated in the comment, you can also use it as the value of the `minimal_roi`
|
||||
If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the ticker_interval used. By default the values vary in the following ranges (for some of the most used ticker intervals, values are rounded to 5 digits after the decimal point):
|
||||
|
||||
| # step | 1m | | 5m | | 1h | | 1d | |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| ------ | ------ | ----------------- | -------- | ----------- | ---------- | ----------------- | ------------ | ----------------- |
|
||||
| 1 | 0 | 0.01161...0.11992 | 0 | 0.03...0.31 | 0 | 0.06883...0.71124 | 0 | 0.12178...1.25835 |
|
||||
| 2 | 2...8 | 0.00774...0.04255 | 10...40 | 0.02...0.11 | 120...480 | 0.04589...0.25238 | 2880...11520 | 0.08118...0.44651 |
|
||||
| 3 | 4...20 | 0.00387...0.01547 | 20...100 | 0.01...0.04 | 240...1200 | 0.02294...0.09177 | 5760...28800 | 0.04059...0.16237 |
|
||||
@@ -406,6 +418,7 @@ In order to use this best stoploss value found by Hyperopt in backtesting and fo
|
||||
# This attribute will be overridden if the config file contains "stoploss"
|
||||
stoploss = -0.27996
|
||||
```
|
||||
|
||||
As stated in the comment, you can also use it as the value of the `stoploss` setting in the configuration file.
|
||||
|
||||
#### Default Stoploss Search Space
|
||||
@@ -442,6 +455,7 @@ In order to use these best trailing stop parameters found by Hyperopt in backtes
|
||||
trailing_stop_positive_offset = 0.06038
|
||||
trailing_only_offset_is_reached = True
|
||||
```
|
||||
|
||||
As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.
|
||||
|
||||
#### Default Trailing Stop Search Space
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# Freqtrade
|
||||
[](https://travis-ci.org/freqtrade/freqtrade)
|
||||
[](https://github.com/freqtrade/freqtrade/actions/)
|
||||
[](https://coveralls.io/github/freqtrade/freqtrade?branch=develop)
|
||||
[](https://codeclimate.com/github/freqtrade/freqtrade/maintainability)
|
||||
|
||||
@@ -11,8 +11,10 @@
|
||||
<a class="github-button" href="https://github.com/freqtrade/freqtrade/archive/master.zip" data-icon="octicon-cloud-download" data-size="large" aria-label="Download freqtrade/freqtrade on GitHub">Download</a>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a class="github-button" href="https://github.com/freqtrade" data-size="large" aria-label="Follow @freqtrade on GitHub">Follow @freqtrade</a>
|
||||
|
||||
## Introduction
|
||||
Freqtrade is a cryptocurrency trading bot written in Python.
|
||||
|
||||
Freqtrade is a crypto-currency algorithmic trading software developed in python (3.6+) and supported on Windows, macOS and Linux.
|
||||
|
||||
!!! Danger "DISCLAIMER"
|
||||
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
|
||||
@@ -23,18 +25,15 @@ Freqtrade is a cryptocurrency trading bot written in Python.
|
||||
|
||||
## Features
|
||||
|
||||
- Based on Python 3.6+: For botting on any operating system — Windows, macOS and Linux.
|
||||
- Persistence: Persistence is achieved through sqlite database.
|
||||
- Dry-run mode: Run the bot without playing money.
|
||||
- Backtesting: Run a simulation of your buy/sell strategy with historical data.
|
||||
- Strategy Optimization by machine learning: Use machine learning to optimize your buy/sell strategy parameters with real exchange data.
|
||||
- Edge position sizing: Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market.
|
||||
- Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists based on market (pair) trade volume.
|
||||
- Blacklist crypto-currencies: Select which crypto-currency you want to avoid.
|
||||
- Manageable via Telegram or REST APi: Manage the bot with Telegram or via the builtin REST API.
|
||||
- Display profit/loss in fiat: Display your profit/loss in any of 33 fiat currencies supported.
|
||||
- Daily summary of profit/loss: Receive the daily summary of your profit/loss.
|
||||
- Performance status report: Receive the performance status of your current trades.
|
||||
- Develop your Strategy: Write your strategy in python, using [pandas](https://pandas.pydata.org/). Example strategies to inspire you are available in the [strategy repository](https://github.com/freqtrade/freqtrade-strategies).
|
||||
- Download market data: Download historical data of the exchange and the markets your may want to trade with.
|
||||
- Backtest: Test your strategy on downloaded historical data.
|
||||
- Optimize: Find the best parameters for your strategy using hyperoptimization which employs machining learning methods. You can optimize buy, sell, take profit (ROI), stop-loss and trailing stop-loss parameters for your strategy.
|
||||
- Select markets: Create your static list or use an automatic one based on top traded volumes and/or prices (not available during backtesting). You can also explicitly blacklist markets you don't want to trade.
|
||||
- Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode).
|
||||
- Run using Edge (optional module): The concept is to find the best historical [trade expectancy](edge.md#expectancy) by markets based on variation of the stop-loss and then allow/reject markets to trade. The sizing of the trade is based on a risk of a percentage of your capital.
|
||||
- Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).
|
||||
- Analyse: Further analysis can be performed on either Backtesting data or Freqtrade trading history (SQL database), including automated standard plots, and methods to load the data into [interactive environments](data-analysis.md).
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -52,20 +51,23 @@ To run this bot we recommend you a cloud instance with a minimum of:
|
||||
|
||||
### Software requirements
|
||||
|
||||
- Docker (Recommended)
|
||||
|
||||
Alternatively
|
||||
|
||||
- Python 3.6.x
|
||||
- pip (pip3)
|
||||
- git
|
||||
- TA-Lib
|
||||
- virtualenv (Recommended)
|
||||
- Docker (Recommended)
|
||||
|
||||
## Support
|
||||
|
||||
Help / Slack
|
||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our Slack channel.
|
||||
### Help / Slack
|
||||
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our passionate Slack community.
|
||||
|
||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) to join Slack channel.
|
||||
Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtNjU5ODcwNjI1MDU3LTU1MTgxMjkzNmYxNWE1MDEzYzQ3YmU4N2MwZjUyNjJjODRkMDVkNjg4YTAyZGYzYzlhOTZiMTE4ZjQ4YzM0OGE) to join the Freqtrade Slack channel.
|
||||
|
||||
## Ready to try?
|
||||
|
||||
Begin by reading our installation guide [here](installation).
|
||||
Begin by reading our installation guide [for docker](docker.md), or for [installation without docker](installation.md).
|
||||
|
@@ -2,6 +2,8 @@
|
||||
|
||||
This page explains how to prepare your environment for running the bot.
|
||||
|
||||
Please consider using the prebuilt [docker images](docker.md) to get started quickly while trying out freqtrade evaluating how it operates.
|
||||
|
||||
## Prerequisite
|
||||
|
||||
### Requirements
|
||||
@@ -14,15 +16,7 @@ Click each one for install guide:
|
||||
* [virtualenv](https://virtualenv.pypa.io/en/stable/installation/) (Recommended)
|
||||
* [TA-Lib](https://mrjbq7.github.io/ta-lib/install.html) (install instructions below)
|
||||
|
||||
### API keys
|
||||
|
||||
Before running your bot in production you will need to setup few
|
||||
external API. In production mode, the bot will require valid Exchange API
|
||||
credentials. We also recommend a [Telegram bot](telegram-usage.md#setup-your-telegram-bot) (optional but recommended).
|
||||
|
||||
### Setup your exchange account
|
||||
|
||||
You will need to create API Keys (Usually you get `key` and `secret`) from the Exchange website and insert this into the appropriate fields in the configuration or when asked by the installation script.
|
||||
We also recommend a [Telegram bot](telegram-usage.md#setup-your-telegram-bot), which is optional but recommended.
|
||||
|
||||
## Quick start
|
||||
|
||||
@@ -31,7 +25,7 @@ Freqtrade provides the Linux/MacOS Easy Installation script to install all depen
|
||||
!!! Note
|
||||
Windows installation is explained [here](#windows).
|
||||
|
||||
The easiest way to install and run Freqtrade is to clone the bot GitHub repository and then run the Easy Installation script, if it's available for your platform.
|
||||
The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the Easy Installation script, if it's available for your platform.
|
||||
|
||||
!!! Note "Version considerations"
|
||||
When cloning the repository the default working branch has the name `develop`. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The `master` branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the `develop` branch to prevent packaging bugs, so potentially it's more stable).
|
||||
@@ -42,11 +36,12 @@ The easiest way to install and run Freqtrade is to clone the bot GitHub reposito
|
||||
This can be achieved with the following commands:
|
||||
|
||||
```bash
|
||||
git clone git@github.com:freqtrade/freqtrade.git
|
||||
git clone https://github.com/freqtrade/freqtrade.git
|
||||
cd freqtrade
|
||||
git checkout master # Optional, see (1)
|
||||
./setup.sh --install
|
||||
```
|
||||
|
||||
(1) This command switches the cloned repository to the use of the `master` branch. It's not needed if you wish to stay on the `develop` branch. You may later switch between branches at any time with the `git checkout master`/`git checkout develop` commands.
|
||||
|
||||
## Easy Installation Script (Linux/MacOS)
|
||||
@@ -64,11 +59,11 @@ usage:
|
||||
|
||||
** --install **
|
||||
|
||||
With this option, the script will install everything you need to run the bot:
|
||||
With this option, the script will install the bot and most dependencies:
|
||||
You will need to have git and python3.6+ installed beforehand for this to work.
|
||||
|
||||
* Mandatory software as: `ta-lib`
|
||||
* Setup your virtualenv
|
||||
* Configure your `config.json` file
|
||||
* Setup your virtualenv under `.env/`
|
||||
|
||||
This option is a combination of installation tasks, `--reset` and `--config`.
|
||||
|
||||
@@ -82,7 +77,7 @@ This option will hard reset your branch (only if you are on either `master` or `
|
||||
|
||||
** --config **
|
||||
|
||||
Use this option to configure the `config.json` configuration file. The script will interactively ask you questions to setup your bot and create your `config.json`.
|
||||
DEPRECATED - use `freqtrade new-config -c config.json` instead.
|
||||
|
||||
------
|
||||
|
||||
@@ -129,6 +124,17 @@ bash setup.sh -i
|
||||
|
||||
#### 1. Install TA-Lib
|
||||
|
||||
Use the provided ta-lib installation script
|
||||
|
||||
```bash
|
||||
sudo ./build_helpers/install_ta-lib.sh
|
||||
```
|
||||
|
||||
!!! Note
|
||||
This will use the ta-lib tar.gz included in this repository.
|
||||
|
||||
##### TA-Lib manual installation
|
||||
|
||||
Official webpage: https://mrjbq7.github.io/ta-lib/install.html
|
||||
|
||||
```bash
|
||||
@@ -184,7 +190,8 @@ python3 -m pip install -e .
|
||||
# Initialize the user_directory
|
||||
freqtrade create-userdir --userdir user_data/
|
||||
|
||||
cp config.json.example config.json
|
||||
# Create a new configuration file
|
||||
freqtrade new-config --config config.json
|
||||
```
|
||||
|
||||
> *To edit the config please refer to [Bot Configuration](configuration.md).*
|
||||
@@ -270,3 +277,18 @@ The easiest way is to download install Microsoft Visual Studio Community [here](
|
||||
|
||||
Now you have an environment ready, the next step is
|
||||
[Bot Configuration](configuration.md).
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### MacOS installation error
|
||||
|
||||
Newer versions of MacOS may have installation failed with errors like `error: command 'g++' failed with exit status 1`.
|
||||
|
||||
This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS.
|
||||
For MacOS 10.14, this can be accomplished with the below command.
|
||||
|
||||
``` bash
|
||||
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
|
||||
```
|
||||
|
||||
If this file is inexistant, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.
|
||||
|
141
docs/plotting.md
141
docs/plotting.md
@@ -23,58 +23,43 @@ The `freqtrade plot-dataframe` subcommand shows an interactive graph with three
|
||||
Possible arguments:
|
||||
|
||||
```
|
||||
usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [-s NAME]
|
||||
[--strategy-path PATH] [-p PAIRS [PAIRS ...]]
|
||||
[--indicators1 INDICATORS1 [INDICATORS1 ...]]
|
||||
[--indicators2 INDICATORS2 [INDICATORS2 ...]]
|
||||
[--plot-limit INT] [--db-url PATH]
|
||||
[--trade-source {DB,file}] [--export EXPORT]
|
||||
[--export-filename PATH]
|
||||
[--timerange TIMERANGE] [-i TICKER_INTERVAL]
|
||||
usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME]
|
||||
[--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--indicators1 INDICATORS1 [INDICATORS1 ...]]
|
||||
[--indicators2 INDICATORS2 [INDICATORS2 ...]] [--plot-limit INT] [--db-url PATH]
|
||||
[--trade-source {DB,file}] [--export EXPORT] [--export-filename PATH] [--timerange TIMERANGE]
|
||||
[-i TICKER_INTERVAL]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
|
||||
Show profits for only these pairs. Pairs are space-
|
||||
separated.
|
||||
Show profits for only these pairs. Pairs are space-separated.
|
||||
--indicators1 INDICATORS1 [INDICATORS1 ...]
|
||||
Set indicators from your strategy you want in the
|
||||
first row of the graph. Space-separated list. Example:
|
||||
Set indicators from your strategy you want in the first row of the graph. Space-separated list. Example:
|
||||
`ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.
|
||||
--indicators2 INDICATORS2 [INDICATORS2 ...]
|
||||
Set indicators from your strategy you want in the
|
||||
third row of the graph. Space-separated list. Example:
|
||||
Set indicators from your strategy you want in the third row of the graph. Space-separated list. Example:
|
||||
`fastd fastk`. Default: `['macd', 'macdsignal']`.
|
||||
--plot-limit INT Specify tick limit for plotting. Notice: too high
|
||||
values cause huge files. Default: 750.
|
||||
--db-url PATH Override trades database URL, this is useful in custom
|
||||
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||
Live Run mode, `sqlite://` for Dry Run).
|
||||
--plot-limit INT Specify tick limit for plotting. Notice: too high values cause huge files. Default: 750.
|
||||
--db-url PATH Override trades database URL, this is useful in custom deployments (default: `sqlite:///tradesv3.sqlite`
|
||||
for Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for Dry Run).
|
||||
--trade-source {DB,file}
|
||||
Specify the source for trades (Can be DB or file
|
||||
(backtest file)) Default: file
|
||||
--export EXPORT Export backtest results, argument are: trades.
|
||||
Example: `--export=trades`
|
||||
Specify the source for trades (Can be DB or file (backtest file)) Default: file
|
||||
--export EXPORT Export backtest results, argument are: trades. Example: `--export=trades`
|
||||
--export-filename PATH
|
||||
Save backtest results to the file with this filename
|
||||
(default: `user_data/backtest_results/backtest-
|
||||
result.json`). Requires `--export` to be set as well.
|
||||
Example: `--export-filename=user_data/backtest_results
|
||||
/backtest_today.json`
|
||||
Save backtest results to the file with this filename. Requires `--export` to be set as well. Example:
|
||||
`--export-filename=user_data/backtest_results/backtest_today.json`
|
||||
--timerange TIMERANGE
|
||||
Specify what timerange of data to use.
|
||||
-i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL
|
||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`,
|
||||
`1d`).
|
||||
Specify ticker interval (`1m`, `5m`, `30m`, `1h`, `1d`).
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified.
|
||||
--logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
@@ -83,8 +68,7 @@ Common arguments:
|
||||
|
||||
Strategy arguments:
|
||||
-s NAME, --strategy NAME
|
||||
Specify strategy class name (default:
|
||||
`DefaultStrategy`).
|
||||
Specify strategy class name which will be used by the bot.
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
|
||||
```
|
||||
@@ -136,16 +120,77 @@ To plot trades from a backtesting result, use `--export-filename <filename>`
|
||||
freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH
|
||||
```
|
||||
|
||||
### Plot dataframe basics
|
||||
|
||||

|
||||
|
||||
The `plot-dataframe` subcommand requires backtesting data, a strategy and either a backtesting-results file or a database, containing trades corresponding to the strategy.
|
||||
|
||||
The resulting plot will have the following elements:
|
||||
|
||||
* Green triangles: Buy signals from the strategy. (Note: not every buy signal generates a trade, compare to cyan circles.)
|
||||
* Red triangles: Sell signals from the strategy. (Also, not every sell signal terminates a trade, compare to red and green squares.)
|
||||
* Cyan circles: Trade entry points.
|
||||
* Red squares: Trade exit points for trades with loss or 0% profit.
|
||||
* Green squares: Trade exit points for profitable trades.
|
||||
* Indicators with values corresponding to the candle scale (e.g. SMA/EMA), as specified with `--indicators1`.
|
||||
* Volume (bar chart at the bottom of the main chart).
|
||||
* Indicators with values in different scales (e.g. MACD, RSI) below the volume bars, as specified with `--indicators2`.
|
||||
|
||||
!!! Note "Bollinger Bands"
|
||||
Bollinger bands are automatically added to the plot if the columns `bb_lowerband` and `bb_upperband` exist, and are painted as a light blue area spanning from the lower band to the upper band.
|
||||
|
||||
#### Advanced plot configuration
|
||||
|
||||
An advanced plot configuration can be specified in the strategy in the `plot_config` parameter.
|
||||
|
||||
Additional features when using plot_config include:
|
||||
|
||||
* Specify colors per indicator
|
||||
* Specify additional subplots
|
||||
|
||||
The sample plot configuration below specifies fixed colors for the indicators. Otherwise consecutive plots may produce different colorschemes each time, making comparisons difficult.
|
||||
It also allows multiple subplots to display both MACD and RSI at the same time.
|
||||
|
||||
Sample configuration with inline comments explaining the process:
|
||||
|
||||
``` python
|
||||
plot_config = {
|
||||
'main_plot': {
|
||||
# Configuration for main plot indicators.
|
||||
# Specifies `ema10` to be red, and `ema50` to be a shade of gray
|
||||
'ema10': {'color': 'red'},
|
||||
'ema50': {'color': '#CCCCCC'},
|
||||
# By omitting color, a random color is selected.
|
||||
'sar': {},
|
||||
},
|
||||
'subplots': {
|
||||
# Create subplot MACD
|
||||
"MACD": {
|
||||
'macd': {'color': 'blue'},
|
||||
'macdsignal': {'color': 'orange'},
|
||||
},
|
||||
# Additional subplot RSI
|
||||
"RSI": {
|
||||
'rsi': {'color': 'red'},
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
!!! Note
|
||||
The above configuration assumes that `ema10`, `ema50`, `macd`, `macdsignal` and `rsi` are columns in the DataFrame created by the strategy.
|
||||
|
||||
## Plot profit
|
||||
|
||||

|
||||
|
||||
The `freqtrade plot-profit` subcommand shows an interactive graph with three plots:
|
||||
The `plot-profit` subcommand shows an interactive graph with three plots:
|
||||
|
||||
1) Average closing price for all pairs
|
||||
2) The summarized profit made by backtesting.
|
||||
* Average closing price for all pairs.
|
||||
* The summarized profit made by backtesting.
|
||||
Note that this is not the real-world profit, but more of an estimate.
|
||||
3) Profit for each individual pair
|
||||
* Profit for each individual pair.
|
||||
|
||||
The first graph is good to get a grip of how the overall market progresses.
|
||||
|
||||
@@ -173,14 +218,14 @@ optional arguments:
|
||||
--export EXPORT Export backtest results, argument are: trades.
|
||||
Example: `--export=trades`
|
||||
--export-filename PATH
|
||||
Save backtest results to the file with this filename
|
||||
(default: `user_data/backtest_results/backtest-
|
||||
result.json`). Requires `--export` to be set as well.
|
||||
Example: `--export-filename=user_data/backtest_results
|
||||
/backtest_today.json`
|
||||
Save backtest results to the file with this filename.
|
||||
Requires `--export` to be set as well. Example:
|
||||
`--export-filename=user_data/backtest_results/backtest
|
||||
_today.json`
|
||||
--db-url PATH Override trades database URL, this is useful in custom
|
||||
deployments (default: `sqlite:///tradesv3.sqlite` for
|
||||
Live Run mode, `sqlite://` for Dry Run).
|
||||
Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for
|
||||
Dry Run).
|
||||
--trade-source {DB,file}
|
||||
Specify the source for trades (Can be DB or file
|
||||
(backtest file)) Default: file
|
||||
@@ -190,7 +235,9 @@ optional arguments:
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified.
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
|
@@ -1,2 +1,2 @@
|
||||
mkdocs-material==4.5.1
|
||||
mkdocs-material==4.6.3
|
||||
mdx_truly_sane_lists==1.2
|
||||
|
@@ -74,7 +74,7 @@ docker run -d \
|
||||
## Consuming the API
|
||||
|
||||
You can consume the API by using the script `scripts/rest_client.py`.
|
||||
The client script only requires the `requests` module, so FreqTrade does not need to be installed on the system.
|
||||
The client script only requires the `requests` module, so Freqtrade does not need to be installed on the system.
|
||||
|
||||
``` bash
|
||||
python3 scripts/rest_client.py <command> [optional parameters]
|
||||
|
@@ -27,7 +27,7 @@ So this parameter will tell the bot how often it should update the stoploss orde
|
||||
This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.
|
||||
|
||||
!!! Note
|
||||
Stoploss on exchange is only supported for Binance as of now.
|
||||
Stoploss on exchange is only supported for Binance (stop-loss-limit) and Kraken (stop-loss-market) as of now.
|
||||
|
||||
## Static Stop Loss
|
||||
|
||||
|
@@ -346,7 +346,7 @@ if self.dp:
|
||||
|
||||
``` python
|
||||
if self.dp:
|
||||
if self.dp.runmode in ('live', 'dry_run'):
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
ob = self.dp.orderbook(metadata['pair'], 1)
|
||||
dataframe['best_bid'] = ob['bids'][0][0]
|
||||
dataframe['best_ask'] = ob['asks'][0][0]
|
||||
@@ -422,7 +422,7 @@ from freqtrade.persistence import Trade
|
||||
The following example queries for the current pair and trades from today, however other filters can easily be added.
|
||||
|
||||
``` python
|
||||
if self.config['runmode'] in ('live', 'dry_run'):
|
||||
if self.config['runmode'].value in ('live', 'dry_run'):
|
||||
trades = Trade.get_trades([Trade.pair == metadata['pair'],
|
||||
Trade.open_date > datetime.utcnow() - timedelta(days=1),
|
||||
Trade.is_open == False,
|
||||
@@ -434,7 +434,7 @@ if self.config['runmode'] in ('live', 'dry_run'):
|
||||
Get amount of stake_currency currently invested in Trades:
|
||||
|
||||
``` python
|
||||
if self.config['runmode'] in ('live', 'dry_run'):
|
||||
if self.config['runmode'].value in ('live', 'dry_run'):
|
||||
total_stakes = Trade.total_open_trades_stakes()
|
||||
```
|
||||
|
||||
@@ -442,7 +442,7 @@ Retrieve performance per pair.
|
||||
Returns a List of dicts per pair.
|
||||
|
||||
``` python
|
||||
if self.config['runmode'] in ('live', 'dry_run'):
|
||||
if self.config['runmode'].value in ('live', 'dry_run'):
|
||||
performance = Trade.get_overall_performance()
|
||||
```
|
||||
|
||||
@@ -455,6 +455,51 @@ Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of
|
||||
!!! Warning
|
||||
Trade history is not available during backtesting or hyperopt.
|
||||
|
||||
### Prevent trades from happening for a specific pair
|
||||
|
||||
Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair.
|
||||
|
||||
Locked pairs will show the message `Pair <pair> is currently locked.`.
|
||||
|
||||
#### Locking pairs from within the strategy
|
||||
|
||||
Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).
|
||||
|
||||
Freqtrade has an easy method to do this from within the strategy, by calling `self.lock_pair(pair, until)`.
|
||||
`until` must be a datetime object in the future, after which trading will be reenabled for that pair.
|
||||
|
||||
Locks can also be lifted manually, by calling `self.unlock_pair(pair)`.
|
||||
|
||||
To verify if a pair is currently locked, use `self.is_pair_locked(pair)`.
|
||||
|
||||
!!! Note
|
||||
Locked pairs are not persisted, so a restart of the bot, or calling `/reload_conf` will reset locked pairs.
|
||||
|
||||
!!! Warning
|
||||
Locking pairs is not functioning during backtesting.
|
||||
|
||||
##### Pair locking example
|
||||
|
||||
``` python
|
||||
from freqtrade.persistence import Trade
|
||||
from datetime import timedelta, datetime, timezone
|
||||
# Put the above lines a the top of the strategy file, next to all the other imports
|
||||
# --------
|
||||
|
||||
# Within populate indicators (or populate_buy):
|
||||
if self.config['runmode'].value in ('live', 'dry_run'):
|
||||
# fetch closed trades for the last 2 days
|
||||
trades = Trade.get_trades([Trade.pair == metadata['pair'],
|
||||
Trade.open_date > datetime.utcnow() - timedelta(days=2),
|
||||
Trade.is_open == False,
|
||||
]).all()
|
||||
# Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy
|
||||
sumprofit = sum(trade.close_profit for trade in trades)
|
||||
if sumprofit < 0:
|
||||
# Lock pair for 12 hours
|
||||
self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12))
|
||||
```
|
||||
|
||||
### Print created dataframe
|
||||
|
||||
To inspect the created dataframe, you can issue a print-statement in either `populate_buy_trend()` or `populate_sell_trend()`.
|
||||
@@ -479,11 +524,6 @@ def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
|
||||
Printing more than a few rows is also possible (simply use `print(dataframe)` instead of `print(dataframe.tail())`), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
|
||||
|
||||
### Where can i find a strategy template?
|
||||
|
||||
The strategy template is located in the file
|
||||
[user_data/strategies/sample_strategy.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_strategy.py).
|
||||
|
||||
### Specify custom strategy location
|
||||
|
||||
If you want to use a strategy from a different directory you can pass `--strategy-path`
|
||||
@@ -492,6 +532,27 @@ If you want to use a strategy from a different directory you can pass `--strateg
|
||||
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory
|
||||
```
|
||||
|
||||
### Derived strategies
|
||||
|
||||
The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
|
||||
|
||||
``` python
|
||||
class MyAwesomeStrategy(IStrategy):
|
||||
...
|
||||
stoploss = 0.13
|
||||
trailing_stop = False
|
||||
# All other attributes and methods are here as they
|
||||
# should be in any custom strategy...
|
||||
...
|
||||
|
||||
class MyAwesomeStrategy2(MyAwesomeStrategy):
|
||||
# Override something
|
||||
stoploss = 0.08
|
||||
trailing_stop = True
|
||||
```
|
||||
|
||||
Both attributes and methods may be overriden, altering behavior of the original strategy in a way you need.
|
||||
|
||||
### Common mistakes when developing strategies
|
||||
|
||||
Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future.
|
||||
|
@@ -1,24 +1,28 @@
|
||||
# Strategy analysis example
|
||||
|
||||
Debugging a strategy can be time-consuming. FreqTrade offers helper functions to visualize raw data.
|
||||
Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data.
|
||||
The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location.
|
||||
|
||||
## Setup
|
||||
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
from freqtrade.configuration import Configuration
|
||||
|
||||
# Customize these according to your needs.
|
||||
|
||||
# Initialize empty configuration object
|
||||
config = Configuration.from_files([])
|
||||
# Optionally, use existing configuration file
|
||||
# config = Configuration.from_files(["config.json"])
|
||||
|
||||
# Define some constants
|
||||
timeframe = "5m"
|
||||
config["ticker_interval"] = "5m"
|
||||
# Name of the strategy class
|
||||
strategy_name = 'SampleStrategy'
|
||||
# Path to user data
|
||||
user_data_dir = Path('user_data')
|
||||
# Location of the strategy
|
||||
strategy_location = user_data_dir / 'strategies'
|
||||
config["strategy"] = "SampleStrategy"
|
||||
# Location of the data
|
||||
data_location = Path(user_data_dir, 'data', 'binance')
|
||||
data_location = Path(config['user_data_dir'], 'data', 'binance')
|
||||
# Pair to analyze - Only use one pair here
|
||||
pair = "BTC_USDT"
|
||||
```
|
||||
@@ -29,7 +33,7 @@ pair = "BTC_USDT"
|
||||
from freqtrade.data.history import load_pair_history
|
||||
|
||||
candles = load_pair_history(datadir=data_location,
|
||||
timeframe=timeframe,
|
||||
timeframe=config["ticker_interval"],
|
||||
pair=pair)
|
||||
|
||||
# Confirm success
|
||||
@@ -44,9 +48,7 @@ candles.head()
|
||||
```python
|
||||
# Load strategy using values set above
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
strategy = StrategyResolver({'strategy': strategy_name,
|
||||
'user_data_dir': user_data_dir,
|
||||
'strategy_path': strategy_location}).strategy
|
||||
strategy = StrategyResolver.load_strategy(config)
|
||||
|
||||
# Generate buy/sell signals using strategy
|
||||
df = strategy.analyze_ticker(candles, {'pair': pair})
|
||||
@@ -86,7 +88,7 @@ Analyze a trades dataframe (also used below for plotting)
|
||||
from freqtrade.data.btanalysis import load_backtest_data
|
||||
|
||||
# Load backtest results
|
||||
trades = load_backtest_data(user_data_dir / "backtest_results/backtest-result.json")
|
||||
trades = load_backtest_data(config["user_data_dir"] / "backtest_results/backtest-result.json")
|
||||
|
||||
# Show value-counts per pair
|
||||
trades.groupby("pair")["sell_reason"].value_counts()
|
||||
|
@@ -55,7 +55,7 @@ official commands. You can ask at any moment for help with `/help`.
|
||||
| `/reload_conf` | | Reloads the configuration file
|
||||
| `/show_config` | | Shows part of the current configuration with relevant settings to operation
|
||||
| `/status` | | Lists all open trades
|
||||
| `/status table` | | List all open trades in a table format
|
||||
| `/status table` | | List all open trades in a table format. Pending buy orders are marked with an asterisk (*) Pending sell orders are marked with a double asterisk (**)
|
||||
| `/count` | | Displays number of trades used and available
|
||||
| `/profit` | | Display a summary of your profit/loss from close trades and some stats about your performance
|
||||
| `/forcesell <trade_id>` | | Instantly sells the given trade (Ignoring `minimum_roi`).
|
||||
|
206
docs/utils.md
206
docs/utils.md
@@ -36,6 +36,38 @@ optional arguments:
|
||||
└── sample_strategy.py
|
||||
```
|
||||
|
||||
## Create new config
|
||||
|
||||
Creates a new configuration file, asking some questions which are important selections for a configuration.
|
||||
|
||||
```
|
||||
usage: freqtrade new-config [-h] [-c PATH]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`
|
||||
to read config from stdin.
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
Only vital questions are asked. Freqtrade offers a lot more configuration possibilities, which are listed in the [Configuration documentation](configuration.md#configuration-parameters)
|
||||
|
||||
### Create config examples
|
||||
|
||||
```
|
||||
$ freqtrade new-config --config config_binance.json
|
||||
|
||||
? Do you want to enable Dry-run (simulated trades)? Yes
|
||||
? Please insert your stake currency: BTC
|
||||
? Please insert your stake amount: 0.05
|
||||
? Please insert max_open_trades (Integer or 'unlimited'): 5
|
||||
? Please insert your ticker interval: 15m
|
||||
? Please insert your display Currency (for reporting): USD
|
||||
? Select exchange binance
|
||||
? Do you want to enable Telegram? No
|
||||
```
|
||||
|
||||
## Create new strategy
|
||||
|
||||
Creates a new strategy from a template similar to SampleStrategy.
|
||||
@@ -108,6 +140,97 @@ With custom user directory
|
||||
freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt
|
||||
```
|
||||
|
||||
## List Strategies and List Hyperopts
|
||||
|
||||
Use the `list-strategies` subcommand to see all strategies in one particular directory and the `list-hyperopts` subcommand to list custom Hyperopts.
|
||||
|
||||
These subcommands are useful for finding problems in your environment with loading strategies or hyperopt classes: modules with strategies or hyperopt classes that contain errors and failed to load are printed in red (LOAD FAILED), while strategies or hyperopt classes with duplicate names are printed in yellow (DUPLICATE NAME).
|
||||
|
||||
```
|
||||
usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[--strategy-path PATH] [-1] [--no-color]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--strategy-path PATH Specify additional strategy lookup path.
|
||||
-1, --one-column Print output in one column.
|
||||
--no-color Disable colorization of hyperopt results. May be
|
||||
useful if you are redirecting output to a file.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
```
|
||||
usage: freqtrade list-hyperopts [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH]
|
||||
[--hyperopt-path PATH] [-1] [--no-color]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--hyperopt-path PATH Specify additional lookup path for Hyperopt and
|
||||
Hyperopt Loss functions.
|
||||
-1, --one-column Print output in one column.
|
||||
--no-color Disable colorization of hyperopt results. May be
|
||||
useful if you are redirecting output to a file.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
Using these commands will try to load all python files from a directory. This can be a security risk if untrusted files reside in this directory, since all module-level code is executed.
|
||||
|
||||
Example: Search default strategies and hyperopts directories (within the default userdir).
|
||||
|
||||
``` bash
|
||||
freqtrade list-strategies
|
||||
freqtrade list-hyperopts
|
||||
```
|
||||
|
||||
Example: Search strategies and hyperopts directory within the userdir.
|
||||
|
||||
``` bash
|
||||
freqtrade list-strategies --userdir ~/.freqtrade/
|
||||
freqtrade list-hyperopts --userdir ~/.freqtrade/
|
||||
```
|
||||
|
||||
Example: Search dedicated strategy path.
|
||||
|
||||
``` bash
|
||||
freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/
|
||||
```
|
||||
|
||||
Example: Search dedicated hyperopt path.
|
||||
|
||||
``` bash
|
||||
freqtrade list-hyperopt --hyperopt-path ~/.freqtrade/hyperopts/
|
||||
```
|
||||
|
||||
## List Exchanges
|
||||
|
||||
Use the `list-exchanges` subcommand to see the exchanges available for the bot.
|
||||
@@ -138,20 +261,31 @@ All exchanges supported by the ccxt library: _1btcxe, acx, adara, allcoin, anxpr
|
||||
Use the `list-timeframes` subcommand to see the list of ticker intervals (timeframes) available for the exchange.
|
||||
|
||||
```
|
||||
usage: freqtrade list-timeframes [-h] [--exchange EXCHANGE] [-1]
|
||||
usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no
|
||||
config is provided.
|
||||
--exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no config is provided.
|
||||
-1, --one-column Print output in one column.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`
|
||||
to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
|
||||
```
|
||||
|
||||
* Example: see the timeframes for the 'binance' exchange, set in the configuration file:
|
||||
|
||||
```
|
||||
$ freqtrade -c config_binance.json list-timeframes
|
||||
$ freqtrade list-timeframes -c config_binance.json
|
||||
...
|
||||
Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
|
||||
```
|
||||
@@ -175,14 +309,16 @@ You can print info about any pair/market with these subcommands - and you can fi
|
||||
These subcommands have same usage and same set of available options:
|
||||
|
||||
```
|
||||
usage: freqtrade list-markets [-h] [--exchange EXCHANGE] [--print-list]
|
||||
[--print-json] [-1] [--print-csv]
|
||||
usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
||||
[--print-list] [--print-json] [-1] [--print-csv]
|
||||
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]
|
||||
[-a]
|
||||
|
||||
usage: freqtrade list-pairs [-h] [--exchange EXCHANGE] [--print-list]
|
||||
[--print-json] [-1] [--print-csv]
|
||||
usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [--exchange EXCHANGE]
|
||||
[--print-list] [--print-json] [-1] [--print-csv]
|
||||
[--base BASE_CURRENCY [BASE_CURRENCY ...]]
|
||||
[--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]
|
||||
|
||||
@@ -201,6 +337,22 @@ optional arguments:
|
||||
Specify quote currency(-ies). Space-separated list.
|
||||
-a, --all Print all pairs or market symbols. By default only
|
||||
active ones are shown.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
|
||||
```
|
||||
|
||||
By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded
|
||||
@@ -222,7 +374,7 @@ $ freqtrade list-pairs --quote USD --print-json
|
||||
human-readable list with summary:
|
||||
|
||||
```
|
||||
$ freqtrade -c config_binance.json list-pairs --all --base BTC ETH --quote USDT USD --print-list
|
||||
$ freqtrade list-pairs -c config_binance.json --all --base BTC ETH --quote USDT USD --print-list
|
||||
```
|
||||
|
||||
* Print all markets on exchange "Kraken", in the tabular format:
|
||||
@@ -270,17 +422,49 @@ You can list the hyperoptimization epochs the Hyperopt module evaluated previous
|
||||
```
|
||||
usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]
|
||||
[-d PATH] [--userdir PATH] [--best]
|
||||
[--profitable] [--no-color] [--print-json]
|
||||
[--no-details]
|
||||
[--profitable] [--min-trades INT]
|
||||
[--max-trades INT] [--min-avg-time FLOAT]
|
||||
[--max-avg-time FLOAT] [--min-avg-profit FLOAT]
|
||||
[--max-avg-profit FLOAT]
|
||||
[--min-total-profit FLOAT]
|
||||
[--max-total-profit FLOAT] [--no-color]
|
||||
[--print-json] [--no-details]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--best Select only best epochs.
|
||||
--profitable Select only profitable epochs.
|
||||
--min-trades INT Select epochs with more than INT trades.
|
||||
--max-trades INT Select epochs with less than INT trades.
|
||||
--min-avg-time FLOAT Select epochs on above average time.
|
||||
--max-avg-time FLOAT Select epochs on under average time.
|
||||
--min-avg-profit FLOAT
|
||||
Select epochs on above average profit.
|
||||
--max-avg-profit FLOAT
|
||||
Select epochs on below average profit.
|
||||
--min-total-profit FLOAT
|
||||
Select epochs on above total profit.
|
||||
--max-total-profit FLOAT
|
||||
Select epochs on below total profit.
|
||||
--no-color Disable colorization of hyperopt results. May be
|
||||
useful if you are redirecting output to a file.
|
||||
--print-json Print best result detailization in JSON format.
|
||||
--no-details Do not print best epoch details.
|
||||
|
||||
Common arguments:
|
||||
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
|
||||
--logfile FILE Log to the file specified. Special values are:
|
||||
'syslog', 'journald'. See the documentation for more
|
||||
details.
|
||||
-V, --version show program's version number and exit
|
||||
-c PATH, --config PATH
|
||||
Specify configuration file (default: `config.json`).
|
||||
Multiple --config options may be used. Can be set to
|
||||
`-` to read config from stdin.
|
||||
-d PATH, --datadir PATH
|
||||
Path to directory with historical backtesting data.
|
||||
--userdir PATH, --user-data-dir PATH
|
||||
Path to userdata directory.
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
@@ -15,11 +15,21 @@ Sample configuration (tested using IFTTT).
|
||||
"value2": "limit {limit:8f}",
|
||||
"value3": "{stake_amount:8f} {stake_currency}"
|
||||
},
|
||||
"webhookbuycancel": {
|
||||
"value1": "Cancelling Open Buy Order for {pair}",
|
||||
"value2": "limit {limit:8f}",
|
||||
"value3": "{stake_amount:8f} {stake_currency}"
|
||||
},
|
||||
"webhooksell": {
|
||||
"value1": "Selling {pair}",
|
||||
"value2": "limit {limit:8f}",
|
||||
"value3": "profit: {profit_amount:8f} {stake_currency}"
|
||||
},
|
||||
"webhooksellcancel": {
|
||||
"value1": "Cancelling Open Sell Order for {pair}",
|
||||
"value2": "limit {limit:8f}",
|
||||
"value3": "profit: {profit_amount:8f} {stake_currency}"
|
||||
},
|
||||
"webhookstatus": {
|
||||
"value1": "Status: {status}",
|
||||
"value2": "",
|
||||
@@ -40,10 +50,29 @@ Possible parameters are:
|
||||
* `exchange`
|
||||
* `pair`
|
||||
* `limit`
|
||||
* `amount`
|
||||
* `open_date`
|
||||
* `stake_amount`
|
||||
* `stake_currency`
|
||||
* `fiat_currency`
|
||||
* `order_type`
|
||||
* `current_rate`
|
||||
|
||||
### Webhookbuycancel
|
||||
|
||||
The fields in `webhook.webhookbuycancel` are filled when the bot cancels a buy order. Parameters are filled using string.format.
|
||||
Possible parameters are:
|
||||
|
||||
* `exchange`
|
||||
* `pair`
|
||||
* `limit`
|
||||
* `amount`
|
||||
* `open_date`
|
||||
* `stake_amount`
|
||||
* `stake_currency`
|
||||
* `fiat_currency`
|
||||
* `order_type`
|
||||
* `current_rate`
|
||||
|
||||
### Webhooksell
|
||||
|
||||
@@ -63,6 +92,29 @@ Possible parameters are:
|
||||
* `fiat_currency`
|
||||
* `sell_reason`
|
||||
* `order_type`
|
||||
* `open_date`
|
||||
* `close_date`
|
||||
|
||||
### Webhooksellcancel
|
||||
|
||||
The fields in `webhook.webhooksellcancel` are filled when the bot cancels a sell order. Parameters are filled using string.format.
|
||||
Possible parameters are:
|
||||
|
||||
* `exchange`
|
||||
* `pair`
|
||||
* `gain`
|
||||
* `limit`
|
||||
* `amount`
|
||||
* `open_rate`
|
||||
* `current_rate`
|
||||
* `profit_amount`
|
||||
* `profit_percent`
|
||||
* `stake_currency`
|
||||
* `fiat_currency`
|
||||
* `sell_reason`
|
||||
* `order_type`
|
||||
* `open_date`
|
||||
* `close_date`
|
||||
|
||||
### Webhookstatus
|
||||
|
||||
|
@@ -1,44 +1,27 @@
|
||||
""" FreqTrade bot """
|
||||
__version__ = '2019.11'
|
||||
""" Freqtrade bot """
|
||||
__version__ = '2020.02'
|
||||
|
||||
if __version__ == 'develop':
|
||||
|
||||
try:
|
||||
import subprocess
|
||||
|
||||
__version__ = 'develop-' + subprocess.check_output(
|
||||
['git', 'log', '--format="%h"', '-n 1'],
|
||||
stderr=subprocess.DEVNULL).decode("utf-8").rstrip().strip('"')
|
||||
|
||||
# from datetime import datetime
|
||||
# last_release = subprocess.check_output(
|
||||
# ['git', 'tag']
|
||||
# ).decode('utf-8').split()[-1].split(".")
|
||||
# # Releases are in the format "2020.1" - we increment the latest version for dev.
|
||||
# prefix = f"{last_release[0]}.{int(last_release[1]) + 1}"
|
||||
# dev_version = int(datetime.now().timestamp() // 1000)
|
||||
# __version__ = f"{prefix}.dev{dev_version}"
|
||||
|
||||
# subprocess.check_output(
|
||||
# ['git', 'log', '--format="%h"', '-n 1'],
|
||||
# stderr=subprocess.DEVNULL).decode("utf-8").rstrip().strip('"')
|
||||
except Exception:
|
||||
# git not available, ignore
|
||||
pass
|
||||
|
||||
|
||||
class DependencyException(Exception):
|
||||
"""
|
||||
Indicates that an assumed dependency is not met.
|
||||
This could happen when there is currently not enough money on the account.
|
||||
"""
|
||||
|
||||
|
||||
class OperationalException(Exception):
|
||||
"""
|
||||
Requires manual intervention and will usually stop the bot.
|
||||
This happens when an exchange returns an unexpected error during runtime
|
||||
or given configuration is invalid.
|
||||
"""
|
||||
|
||||
|
||||
class InvalidOrderException(Exception):
|
||||
"""
|
||||
This is returned when the order is not valid. Example:
|
||||
If stoploss on exchange order is hit, then trying to cancel the order
|
||||
should return this exception.
|
||||
"""
|
||||
|
||||
|
||||
class TemporaryError(Exception):
|
||||
"""
|
||||
Temporary network or exchange related error.
|
||||
This could happen when an exchange is congested, unavailable, or the user
|
||||
has networking problems. Usually resolves itself after a time.
|
||||
"""
|
||||
|
28
freqtrade/commands/__init__.py
Normal file
28
freqtrade/commands/__init__.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# flake8: noqa: F401
|
||||
"""
|
||||
Commands module.
|
||||
Contains all start-commands, subcommands and CLI Interface creation.
|
||||
|
||||
Note: Be careful with file-scoped imports in these subfiles.
|
||||
as they are parsed on startup, nothing containing optional modules should be loaded.
|
||||
"""
|
||||
from freqtrade.commands.arguments import Arguments
|
||||
from freqtrade.commands.build_config_commands import start_new_config
|
||||
from freqtrade.commands.data_commands import (start_convert_data,
|
||||
start_download_data)
|
||||
from freqtrade.commands.deploy_commands import (start_create_userdir,
|
||||
start_new_hyperopt,
|
||||
start_new_strategy)
|
||||
from freqtrade.commands.hyperopt_commands import (start_hyperopt_list,
|
||||
start_hyperopt_show)
|
||||
from freqtrade.commands.list_commands import (start_list_exchanges,
|
||||
start_list_hyperopts,
|
||||
start_list_markets,
|
||||
start_list_strategies,
|
||||
start_list_timeframes)
|
||||
from freqtrade.commands.optimize_commands import (start_backtesting,
|
||||
start_edge, start_hyperopt)
|
||||
from freqtrade.commands.pairlist_commands import start_test_pairlist
|
||||
from freqtrade.commands.plot_commands import (start_plot_dataframe,
|
||||
start_plot_profit)
|
||||
from freqtrade.commands.trade_commands import start_trading
|
@@ -6,8 +6,8 @@ from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration.cli_options import AVAILABLE_CLI_OPTIONS
|
||||
from freqtrade.commands.cli_options import AVAILABLE_CLI_OPTIONS
|
||||
from freqtrade.constants import DEFAULT_CONFIG
|
||||
|
||||
ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_data_dir"]
|
||||
|
||||
@@ -30,6 +30,10 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
|
||||
|
||||
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
|
||||
|
||||
ARGS_LIST_STRATEGIES = ["strategy_path", "print_one_column", "print_colorized"]
|
||||
|
||||
ARGS_LIST_HYPEROPTS = ["hyperopt_path", "print_one_column", "print_colorized"]
|
||||
|
||||
ARGS_LIST_EXCHANGES = ["print_one_column", "list_exchanges_all"]
|
||||
|
||||
ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||
@@ -41,12 +45,17 @@ ARGS_TEST_PAIRLIST = ["config", "quote_currencies", "print_one_column", "list_pa
|
||||
|
||||
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||
|
||||
ARGS_BUILD_CONFIG = ["config"]
|
||||
|
||||
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||
|
||||
ARGS_BUILD_HYPEROPT = ["user_data_dir", "hyperopt", "template"]
|
||||
|
||||
ARGS_CONVERT_DATA = ["pairs", "format_from", "format_to", "erase"]
|
||||
ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes"]
|
||||
|
||||
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "download_trades", "exchange",
|
||||
"timeframes", "erase"]
|
||||
"timeframes", "erase", "dataformat_ohlcv", "dataformat_trades"]
|
||||
|
||||
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
||||
"db_url", "trade_source", "export", "exportfilename",
|
||||
@@ -55,14 +64,20 @@ ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
||||
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
||||
"trade_source", "ticker_interval"]
|
||||
|
||||
ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable", "print_colorized",
|
||||
"print_json", "hyperopt_list_no_details"]
|
||||
ARGS_HYPEROPT_LIST = ["hyperopt_list_best", "hyperopt_list_profitable",
|
||||
"hyperopt_list_min_trades", "hyperopt_list_max_trades",
|
||||
"hyperopt_list_min_avg_time", "hyperopt_list_max_avg_time",
|
||||
"hyperopt_list_min_avg_profit", "hyperopt_list_max_avg_profit",
|
||||
"hyperopt_list_min_total_profit", "hyperopt_list_max_total_profit",
|
||||
"print_colorized", "print_json", "hyperopt_list_no_details"]
|
||||
|
||||
ARGS_HYPEROPT_SHOW = ["hyperopt_list_best", "hyperopt_list_profitable", "hyperopt_show_index",
|
||||
"print_json", "hyperopt_show_no_header"]
|
||||
|
||||
NO_CONF_REQURIED = ["download-data", "list-timeframes", "list-markets", "list-pairs",
|
||||
"hyperopt-list", "hyperopt-show", "plot-dataframe", "plot-profit"]
|
||||
NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes",
|
||||
"list-markets", "list-pairs", "list-strategies",
|
||||
"list-hyperopts", "hyperopt-list", "hyperopt-show",
|
||||
"plot-dataframe", "plot-profit"]
|
||||
|
||||
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-hyperopt", "new-strategy"]
|
||||
|
||||
@@ -96,10 +111,23 @@ class Arguments:
|
||||
# Workaround issue in argparse with action='append' and default value
|
||||
# (see https://bugs.python.org/issue16399)
|
||||
# Allow no-config for certain commands (like downloading / plotting)
|
||||
if ('config' in parsed_arg and parsed_arg.config is None and
|
||||
((Path.cwd() / constants.DEFAULT_CONFIG).is_file() or
|
||||
not ('command' in parsed_arg and parsed_arg.command in NO_CONF_REQURIED))):
|
||||
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
||||
if ('config' in parsed_arg and parsed_arg.config is None):
|
||||
conf_required = ('command' in parsed_arg and parsed_arg.command in NO_CONF_REQURIED)
|
||||
|
||||
if 'user_data_dir' in parsed_arg and parsed_arg.user_data_dir is not None:
|
||||
user_dir = parsed_arg.user_data_dir
|
||||
else:
|
||||
# Default case
|
||||
user_dir = 'user_data'
|
||||
# Try loading from "user_data/config.json"
|
||||
cfgfile = Path(user_dir) / DEFAULT_CONFIG
|
||||
if cfgfile.is_file():
|
||||
parsed_arg.config = [str(cfgfile)]
|
||||
else:
|
||||
# Else use "config.json".
|
||||
cfgfile = Path.cwd() / DEFAULT_CONFIG
|
||||
if cfgfile.is_file() or not conf_required:
|
||||
parsed_arg.config = [DEFAULT_CONFIG]
|
||||
|
||||
return parsed_arg
|
||||
|
||||
@@ -127,13 +155,16 @@ class Arguments:
|
||||
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||
self._build_args(optionlist=['version'], parser=self.parser)
|
||||
|
||||
from freqtrade.optimize import start_backtesting, start_hyperopt, start_edge
|
||||
from freqtrade.utils import (start_create_userdir, start_download_data,
|
||||
from freqtrade.commands import (start_create_userdir, start_convert_data,
|
||||
start_download_data,
|
||||
start_hyperopt_list, start_hyperopt_show,
|
||||
start_list_exchanges, start_list_markets,
|
||||
start_list_exchanges, start_list_hyperopts,
|
||||
start_list_markets, start_list_strategies,
|
||||
start_list_timeframes, start_new_config,
|
||||
start_new_hyperopt, start_new_strategy,
|
||||
start_list_timeframes, start_test_pairlist, start_trading)
|
||||
from freqtrade.plot.plot_utils import start_plot_dataframe, start_plot_profit
|
||||
start_plot_dataframe, start_plot_profit,
|
||||
start_backtesting, start_hyperopt, start_edge,
|
||||
start_test_pairlist, start_trading)
|
||||
|
||||
subparsers = self.parser.add_subparsers(dest='command',
|
||||
# Use custom message when no subhandler is added
|
||||
@@ -173,6 +204,12 @@ class Arguments:
|
||||
create_userdir_cmd.set_defaults(func=start_create_userdir)
|
||||
self._build_args(optionlist=ARGS_CREATE_USERDIR, parser=create_userdir_cmd)
|
||||
|
||||
# add new-config subcommand
|
||||
build_config_cmd = subparsers.add_parser('new-config',
|
||||
help="Create new config")
|
||||
build_config_cmd.set_defaults(func=start_new_config)
|
||||
self._build_args(optionlist=ARGS_BUILD_CONFIG, parser=build_config_cmd)
|
||||
|
||||
# add new-strategy subcommand
|
||||
build_strategy_cmd = subparsers.add_parser('new-strategy',
|
||||
help="Create new strategy")
|
||||
@@ -185,6 +222,24 @@ class Arguments:
|
||||
build_hyperopt_cmd.set_defaults(func=start_new_hyperopt)
|
||||
self._build_args(optionlist=ARGS_BUILD_HYPEROPT, parser=build_hyperopt_cmd)
|
||||
|
||||
# Add list-strategies subcommand
|
||||
list_strategies_cmd = subparsers.add_parser(
|
||||
'list-strategies',
|
||||
help='Print available strategies.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
list_strategies_cmd.set_defaults(func=start_list_strategies)
|
||||
self._build_args(optionlist=ARGS_LIST_STRATEGIES, parser=list_strategies_cmd)
|
||||
|
||||
# Add list-hyperopts subcommand
|
||||
list_hyperopts_cmd = subparsers.add_parser(
|
||||
'list-hyperopts',
|
||||
help='Print available hyperopt classes.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
list_hyperopts_cmd.set_defaults(func=start_list_hyperopts)
|
||||
self._build_args(optionlist=ARGS_LIST_HYPEROPTS, parser=list_hyperopts_cmd)
|
||||
|
||||
# Add list-exchanges subcommand
|
||||
list_exchanges_cmd = subparsers.add_parser(
|
||||
'list-exchanges',
|
||||
@@ -238,6 +293,24 @@ class Arguments:
|
||||
download_data_cmd.set_defaults(func=start_download_data)
|
||||
self._build_args(optionlist=ARGS_DOWNLOAD_DATA, parser=download_data_cmd)
|
||||
|
||||
# Add convert-data subcommand
|
||||
convert_data_cmd = subparsers.add_parser(
|
||||
'convert-data',
|
||||
help='Convert OHLCV data from one format to another.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
convert_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=True))
|
||||
self._build_args(optionlist=ARGS_CONVERT_DATA_OHLCV, parser=convert_data_cmd)
|
||||
|
||||
# Add convert-trade-data subcommand
|
||||
convert_trade_data_cmd = subparsers.add_parser(
|
||||
'convert-trade-data',
|
||||
help='Convert trade-data from one format to another.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
convert_trade_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=False))
|
||||
self._build_args(optionlist=ARGS_CONVERT_DATA, parser=convert_trade_data_cmd)
|
||||
|
||||
# Add Plotting subcommand
|
||||
plot_dataframe_cmd = subparsers.add_parser(
|
||||
'plot-dataframe',
|
193
freqtrade/commands/build_config_commands.py
Normal file
193
freqtrade/commands/build_config_commands.py
Normal file
@@ -0,0 +1,193 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
from questionary import Separator, prompt
|
||||
|
||||
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT
|
||||
from freqtrade.exchange import available_exchanges, MAP_EXCHANGE_CHILDCLASS
|
||||
from freqtrade.misc import render_template
|
||||
from freqtrade.exceptions import OperationalException
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def validate_is_int(val):
|
||||
try:
|
||||
_ = int(val)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def validate_is_float(val):
|
||||
try:
|
||||
_ = float(val)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def ask_user_overwrite(config_path: Path) -> bool:
|
||||
questions = [
|
||||
{
|
||||
"type": "confirm",
|
||||
"name": "overwrite",
|
||||
"message": f"File {config_path} already exists. Overwrite?",
|
||||
"default": False,
|
||||
},
|
||||
]
|
||||
answers = prompt(questions)
|
||||
return answers['overwrite']
|
||||
|
||||
|
||||
def ask_user_config() -> Dict[str, Any]:
|
||||
"""
|
||||
Ask user a few questions to build the configuration.
|
||||
Interactive questions built using https://github.com/tmbo/questionary
|
||||
:returns: Dict with keys to put into template
|
||||
"""
|
||||
questions = [
|
||||
{
|
||||
"type": "confirm",
|
||||
"name": "dry_run",
|
||||
"message": "Do you want to enable Dry-run (simulated trades)?",
|
||||
"default": True,
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"name": "stake_currency",
|
||||
"message": "Please insert your stake currency:",
|
||||
"default": 'BTC',
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"name": "stake_amount",
|
||||
"message": "Please insert your stake amount:",
|
||||
"default": "0.01",
|
||||
"validate": lambda val: val == UNLIMITED_STAKE_AMOUNT or validate_is_float(val),
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"name": "max_open_trades",
|
||||
"message": f"Please insert max_open_trades (Integer or '{UNLIMITED_STAKE_AMOUNT}'):",
|
||||
"default": "3",
|
||||
"validate": lambda val: val == UNLIMITED_STAKE_AMOUNT or validate_is_int(val)
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"name": "ticker_interval",
|
||||
"message": "Please insert your ticker interval:",
|
||||
"default": "5m",
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"name": "fiat_display_currency",
|
||||
"message": "Please insert your display Currency (for reporting):",
|
||||
"default": 'USD',
|
||||
},
|
||||
{
|
||||
"type": "select",
|
||||
"name": "exchange_name",
|
||||
"message": "Select exchange",
|
||||
"choices": [
|
||||
"binance",
|
||||
"binanceje",
|
||||
"binanceus",
|
||||
"bittrex",
|
||||
"kraken",
|
||||
Separator(),
|
||||
"other",
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "autocomplete",
|
||||
"name": "exchange_name",
|
||||
"message": "Type your exchange name (Must be supported by ccxt)",
|
||||
"choices": available_exchanges(),
|
||||
"when": lambda x: x["exchange_name"] == 'other'
|
||||
},
|
||||
{
|
||||
"type": "password",
|
||||
"name": "exchange_key",
|
||||
"message": "Insert Exchange Key",
|
||||
"when": lambda x: not x['dry_run']
|
||||
},
|
||||
{
|
||||
"type": "password",
|
||||
"name": "exchange_secret",
|
||||
"message": "Insert Exchange Secret",
|
||||
"when": lambda x: not x['dry_run']
|
||||
},
|
||||
{
|
||||
"type": "confirm",
|
||||
"name": "telegram",
|
||||
"message": "Do you want to enable Telegram?",
|
||||
"default": False,
|
||||
},
|
||||
{
|
||||
"type": "password",
|
||||
"name": "telegram_token",
|
||||
"message": "Insert Telegram token",
|
||||
"when": lambda x: x['telegram']
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"name": "telegram_chat_id",
|
||||
"message": "Insert Telegram chat id",
|
||||
"when": lambda x: x['telegram']
|
||||
},
|
||||
]
|
||||
answers = prompt(questions)
|
||||
|
||||
if not answers:
|
||||
# Interrupted questionary sessions return an empty dict.
|
||||
raise OperationalException("User interrupted interactive questions.")
|
||||
|
||||
return answers
|
||||
|
||||
|
||||
def deploy_new_config(config_path: Path, selections: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Applies selections to the template and writes the result to config_path
|
||||
:param config_path: Path object for new config file. Should not exist yet
|
||||
:param selecions: Dict containing selections taken by the user.
|
||||
"""
|
||||
from jinja2.exceptions import TemplateNotFound
|
||||
try:
|
||||
exchange_template = MAP_EXCHANGE_CHILDCLASS.get(
|
||||
selections['exchange_name'], selections['exchange_name'])
|
||||
|
||||
selections['exchange'] = render_template(
|
||||
templatefile=f"subtemplates/exchange_{exchange_template}.j2",
|
||||
arguments=selections
|
||||
)
|
||||
except TemplateNotFound:
|
||||
selections['exchange'] = render_template(
|
||||
templatefile=f"subtemplates/exchange_generic.j2",
|
||||
arguments=selections
|
||||
)
|
||||
|
||||
config_text = render_template(templatefile='base_config.json.j2',
|
||||
arguments=selections)
|
||||
|
||||
logger.info(f"Writing config to `{config_path}`.")
|
||||
config_path.write_text(config_text)
|
||||
|
||||
|
||||
def start_new_config(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Create a new strategy from a template
|
||||
Asking the user questions to fill out the templateaccordingly.
|
||||
"""
|
||||
|
||||
config_path = Path(args['config'][0])
|
||||
if config_path.exists():
|
||||
overwrite = ask_user_overwrite(config_path)
|
||||
if overwrite:
|
||||
config_path.unlink()
|
||||
else:
|
||||
raise OperationalException(
|
||||
f"Configuration file `{config_path}` already exists. "
|
||||
"Please delete it or use a different configuration file name.")
|
||||
selections = ask_user_config()
|
||||
deploy_new_config(config_path, selections)
|
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Definition of cli arguments used in arguments.py
|
||||
"""
|
||||
import argparse
|
||||
from argparse import ArgumentTypeError
|
||||
|
||||
from freqtrade import __version__, constants
|
||||
|
||||
@@ -12,7 +12,7 @@ def check_int_positive(value: str) -> int:
|
||||
if uint <= 0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(
|
||||
raise ArgumentTypeError(
|
||||
f"{value} is invalid for this parameter, should be a positive integer value"
|
||||
)
|
||||
return uint
|
||||
@@ -24,7 +24,7 @@ def check_int_nonzero(value: str) -> int:
|
||||
if uint == 0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(
|
||||
raise ArgumentTypeError(
|
||||
f"{value} is invalid for this parameter, should be a non-zero integer value"
|
||||
)
|
||||
return uint
|
||||
@@ -59,7 +59,8 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
),
|
||||
"config": Arg(
|
||||
'-c', '--config',
|
||||
help=f'Specify configuration file (default: `{constants.DEFAULT_CONFIG}`). '
|
||||
help=f'Specify configuration file (default: `userdir/{constants.DEFAULT_CONFIG}` '
|
||||
f'or `config.json` whichever exists). '
|
||||
f'Multiple --config options may be used. '
|
||||
f'Can be set to `-` to read config from stdin.',
|
||||
action='append',
|
||||
@@ -118,14 +119,14 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
help='Specify what timerange of data to use.',
|
||||
),
|
||||
"max_open_trades": Arg(
|
||||
'--max_open_trades',
|
||||
help='Specify max_open_trades to use.',
|
||||
'--max-open-trades',
|
||||
help='Override the value of the `max_open_trades` configuration setting.',
|
||||
type=int,
|
||||
metavar='INT',
|
||||
),
|
||||
"stake_amount": Arg(
|
||||
'--stake_amount',
|
||||
help='Specify stake_amount.',
|
||||
'--stake-amount',
|
||||
help='Override the value of the `stake_amount` configuration setting.',
|
||||
type=float,
|
||||
),
|
||||
# Backtesting
|
||||
@@ -256,7 +257,7 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
help='Specify the class name of the hyperopt loss function class (IHyperOptLoss). '
|
||||
'Different functions can generate completely different results, '
|
||||
'since the target for optimization is different. Built-in Hyperopt-loss-functions are: '
|
||||
'DefaultHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss.'
|
||||
'DefaultHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss, SharpeHyperOptLossDaily.'
|
||||
'(default: `%(default)s`).',
|
||||
metavar='NAME',
|
||||
default=constants.DEFAULT_HYPEROPT_LOSS,
|
||||
@@ -332,6 +333,30 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
'desired timeframe as specified as --timeframes/-t.',
|
||||
action='store_true',
|
||||
),
|
||||
"format_from": Arg(
|
||||
'--format-from',
|
||||
help='Source format for data conversion.',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
required=True,
|
||||
),
|
||||
"format_to": Arg(
|
||||
'--format-to',
|
||||
help='Destination format for data conversion.',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
required=True,
|
||||
),
|
||||
"dataformat_ohlcv": Arg(
|
||||
'--data-format-ohlcv',
|
||||
help='Storage format for downloaded ohlcv data. (default: `%(default)s`).',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
default='json'
|
||||
),
|
||||
"dataformat_trades": Arg(
|
||||
'--data-format-trades',
|
||||
help='Storage format for downloaded trades data. (default: `%(default)s`).',
|
||||
choices=constants.AVAILABLE_DATAHANDLERS,
|
||||
default='jsongz'
|
||||
),
|
||||
"exchange": Arg(
|
||||
'--exchange',
|
||||
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
|
||||
@@ -363,15 +388,13 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
"indicators1": Arg(
|
||||
'--indicators1',
|
||||
help='Set indicators from your strategy you want in the first row of the graph. '
|
||||
'Space-separated list. Example: `ema3 ema5`. Default: `%(default)s`.',
|
||||
default=['sma', 'ema3', 'ema5'],
|
||||
"Space-separated list. Example: `ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.",
|
||||
nargs='+',
|
||||
),
|
||||
"indicators2": Arg(
|
||||
'--indicators2',
|
||||
help='Set indicators from your strategy you want in the third row of the graph. '
|
||||
'Space-separated list. Example: `fastd fastk`. Default: `%(default)s`.',
|
||||
default=['macd', 'macdsignal'],
|
||||
"Space-separated list. Example: `fastd fastk`. Default: `['macd', 'macdsignal']`.",
|
||||
nargs='+',
|
||||
),
|
||||
"plot_limit": Arg(
|
||||
@@ -400,6 +423,54 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
help='Select only best epochs.',
|
||||
action='store_true',
|
||||
),
|
||||
"hyperopt_list_min_trades": Arg(
|
||||
'--min-trades',
|
||||
help='Select epochs with more than INT trades.',
|
||||
type=check_int_positive,
|
||||
metavar='INT',
|
||||
),
|
||||
"hyperopt_list_max_trades": Arg(
|
||||
'--max-trades',
|
||||
help='Select epochs with less than INT trades.',
|
||||
type=check_int_positive,
|
||||
metavar='INT',
|
||||
),
|
||||
"hyperopt_list_min_avg_time": Arg(
|
||||
'--min-avg-time',
|
||||
help='Select epochs on above average time.',
|
||||
type=float,
|
||||
metavar='FLOAT',
|
||||
),
|
||||
"hyperopt_list_max_avg_time": Arg(
|
||||
'--max-avg-time',
|
||||
help='Select epochs on under average time.',
|
||||
type=float,
|
||||
metavar='FLOAT',
|
||||
),
|
||||
"hyperopt_list_min_avg_profit": Arg(
|
||||
'--min-avg-profit',
|
||||
help='Select epochs on above average profit.',
|
||||
type=float,
|
||||
metavar='FLOAT',
|
||||
),
|
||||
"hyperopt_list_max_avg_profit": Arg(
|
||||
'--max-avg-profit',
|
||||
help='Select epochs on below average profit.',
|
||||
type=float,
|
||||
metavar='FLOAT',
|
||||
),
|
||||
"hyperopt_list_min_total_profit": Arg(
|
||||
'--min-total-profit',
|
||||
help='Select epochs on above total profit.',
|
||||
type=float,
|
||||
metavar='FLOAT',
|
||||
),
|
||||
"hyperopt_list_max_total_profit": Arg(
|
||||
'--max-total-profit',
|
||||
help='Select epochs on below total profit.',
|
||||
type=float,
|
||||
metavar='FLOAT',
|
||||
),
|
||||
"hyperopt_list_no_details": Arg(
|
||||
'--no-details',
|
||||
help='Do not print best epoch details.',
|
90
freqtrade/commands/data_commands.py
Normal file
90
freqtrade/commands/data_commands.py
Normal file
@@ -0,0 +1,90 @@
|
||||
import logging
|
||||
import sys
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import arrow
|
||||
|
||||
from freqtrade.configuration import TimeRange, setup_utils_configuration
|
||||
from freqtrade.data.converter import (convert_ohlcv_format,
|
||||
convert_trades_format)
|
||||
from freqtrade.data.history import (convert_trades_to_ohlcv,
|
||||
refresh_backtest_ohlcv_data,
|
||||
refresh_backtest_trades_data)
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.resolvers import ExchangeResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start_download_data(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Download data (former download_backtest_data.py script)
|
||||
"""
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||
|
||||
timerange = TimeRange()
|
||||
if 'days' in config:
|
||||
time_since = arrow.utcnow().shift(days=-config['days']).strftime("%Y%m%d")
|
||||
timerange = TimeRange.parse_timerange(f'{time_since}-')
|
||||
|
||||
if 'pairs' not in config:
|
||||
raise OperationalException(
|
||||
"Downloading data requires a list of pairs. "
|
||||
"Please check the documentation on how to configure this.")
|
||||
|
||||
logger.info(f'About to download pairs: {config["pairs"]}, '
|
||||
f'intervals: {config["timeframes"]} to {config["datadir"]}')
|
||||
|
||||
pairs_not_available: List[str] = []
|
||||
|
||||
# Init exchange
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
# Manual validations of relevant settings
|
||||
exchange.validate_pairs(config['pairs'])
|
||||
for timeframe in config['timeframes']:
|
||||
exchange.validate_timeframes(timeframe)
|
||||
|
||||
try:
|
||||
|
||||
if config.get('download_trades'):
|
||||
pairs_not_available = refresh_backtest_trades_data(
|
||||
exchange, pairs=config["pairs"], datadir=config['datadir'],
|
||||
timerange=timerange, erase=bool(config.get("erase")),
|
||||
data_format=config['dataformat_trades'])
|
||||
|
||||
# Convert downloaded trade data to different timeframes
|
||||
convert_trades_to_ohlcv(
|
||||
pairs=config["pairs"], timeframes=config["timeframes"],
|
||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get("erase")),
|
||||
data_format_ohlcv=config['dataformat_ohlcv'],
|
||||
data_format_trades=config['dataformat_trades'],
|
||||
)
|
||||
else:
|
||||
pairs_not_available = refresh_backtest_ohlcv_data(
|
||||
exchange, pairs=config["pairs"], timeframes=config["timeframes"],
|
||||
datadir=config['datadir'], timerange=timerange, erase=bool(config.get("erase")),
|
||||
data_format=config['dataformat_ohlcv'])
|
||||
|
||||
except KeyboardInterrupt:
|
||||
sys.exit("SIGINT received, aborting ...")
|
||||
|
||||
finally:
|
||||
if pairs_not_available:
|
||||
logger.info(f"Pairs [{','.join(pairs_not_available)}] not available "
|
||||
f"on exchange {exchange.name}.")
|
||||
|
||||
|
||||
def start_convert_data(args: Dict[str, Any], ohlcv: bool = True) -> None:
|
||||
"""
|
||||
Convert data from one format to another
|
||||
"""
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
if ohlcv:
|
||||
convert_ohlcv_format(config,
|
||||
convert_from=args['format_from'], convert_to=args['format_to'],
|
||||
erase=args['erase'])
|
||||
else:
|
||||
convert_trades_format(config,
|
||||
convert_from=args['format_from'], convert_to=args['format_to'],
|
||||
erase=args['erase'])
|
112
freqtrade/commands/deploy_commands.py
Normal file
112
freqtrade/commands/deploy_commands.py
Normal file
@@ -0,0 +1,112 @@
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.configuration.directory_operations import (copy_sample_files,
|
||||
create_userdata_dir)
|
||||
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.misc import render_template
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start_create_userdir(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Create "user_data" directory to contain user data strategies, hyperopt, ...)
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
if "user_data_dir" in args and args["user_data_dir"]:
|
||||
userdir = create_userdata_dir(args["user_data_dir"], create_dir=True)
|
||||
copy_sample_files(userdir, overwrite=args["reset"])
|
||||
else:
|
||||
logger.warning("`create-userdir` requires --userdir to be set.")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def deploy_new_strategy(strategy_name: str, strategy_path: Path, subtemplate: str) -> None:
|
||||
"""
|
||||
Deploy new strategy from template to strategy_path
|
||||
"""
|
||||
indicators = render_template(templatefile=f"subtemplates/indicators_{subtemplate}.j2",)
|
||||
buy_trend = render_template(templatefile=f"subtemplates/buy_trend_{subtemplate}.j2",)
|
||||
sell_trend = render_template(templatefile=f"subtemplates/sell_trend_{subtemplate}.j2",)
|
||||
plot_config = render_template(templatefile=f"subtemplates/plot_config_{subtemplate}.j2",)
|
||||
|
||||
strategy_text = render_template(templatefile='base_strategy.py.j2',
|
||||
arguments={"strategy": strategy_name,
|
||||
"indicators": indicators,
|
||||
"buy_trend": buy_trend,
|
||||
"sell_trend": sell_trend,
|
||||
"plot_config": plot_config,
|
||||
})
|
||||
|
||||
logger.info(f"Writing strategy to `{strategy_path}`.")
|
||||
strategy_path.write_text(strategy_text)
|
||||
|
||||
|
||||
def start_new_strategy(args: Dict[str, Any]) -> None:
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
if "strategy" in args and args["strategy"]:
|
||||
if args["strategy"] == "DefaultStrategy":
|
||||
raise OperationalException("DefaultStrategy is not allowed as name.")
|
||||
|
||||
new_path = config['user_data_dir'] / USERPATH_STRATEGIES / (args["strategy"] + ".py")
|
||||
|
||||
if new_path.exists():
|
||||
raise OperationalException(f"`{new_path}` already exists. "
|
||||
"Please choose another Strategy Name.")
|
||||
|
||||
deploy_new_strategy(args['strategy'], new_path, args['template'])
|
||||
|
||||
else:
|
||||
raise OperationalException("`new-strategy` requires --strategy to be set.")
|
||||
|
||||
|
||||
def deploy_new_hyperopt(hyperopt_name: str, hyperopt_path: Path, subtemplate: str) -> None:
|
||||
"""
|
||||
Deploys a new hyperopt template to hyperopt_path
|
||||
"""
|
||||
buy_guards = render_template(
|
||||
templatefile=f"subtemplates/hyperopt_buy_guards_{subtemplate}.j2",)
|
||||
sell_guards = render_template(
|
||||
templatefile=f"subtemplates/hyperopt_sell_guards_{subtemplate}.j2",)
|
||||
buy_space = render_template(
|
||||
templatefile=f"subtemplates/hyperopt_buy_space_{subtemplate}.j2",)
|
||||
sell_space = render_template(
|
||||
templatefile=f"subtemplates/hyperopt_sell_space_{subtemplate}.j2",)
|
||||
|
||||
strategy_text = render_template(templatefile='base_hyperopt.py.j2',
|
||||
arguments={"hyperopt": hyperopt_name,
|
||||
"buy_guards": buy_guards,
|
||||
"sell_guards": sell_guards,
|
||||
"buy_space": buy_space,
|
||||
"sell_space": sell_space,
|
||||
})
|
||||
|
||||
logger.info(f"Writing hyperopt to `{hyperopt_path}`.")
|
||||
hyperopt_path.write_text(strategy_text)
|
||||
|
||||
|
||||
def start_new_hyperopt(args: Dict[str, Any]) -> None:
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
if "hyperopt" in args and args["hyperopt"]:
|
||||
if args["hyperopt"] == "DefaultHyperopt":
|
||||
raise OperationalException("DefaultHyperopt is not allowed as name.")
|
||||
|
||||
new_path = config['user_data_dir'] / USERPATH_HYPEROPTS / (args["hyperopt"] + ".py")
|
||||
|
||||
if new_path.exists():
|
||||
raise OperationalException(f"`{new_path}` already exists. "
|
||||
"Please choose another Strategy Name.")
|
||||
deploy_new_hyperopt(args['hyperopt'], new_path, args['template'])
|
||||
else:
|
||||
raise OperationalException("`new-hyperopt` requires --hyperopt to be set.")
|
184
freqtrade/commands/hyperopt_commands.py
Executable file
184
freqtrade/commands/hyperopt_commands.py
Executable file
@@ -0,0 +1,184 @@
|
||||
import logging
|
||||
from operator import itemgetter
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from colorama import init as colorama_init
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start_hyperopt_list(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
List hyperopt epochs previously evaluated
|
||||
"""
|
||||
from freqtrade.optimize.hyperopt import Hyperopt
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
print_colorized = config.get('print_colorized', False)
|
||||
print_json = config.get('print_json', False)
|
||||
no_details = config.get('hyperopt_list_no_details', False)
|
||||
no_header = False
|
||||
|
||||
filteroptions = {
|
||||
'only_best': config.get('hyperopt_list_best', False),
|
||||
'only_profitable': config.get('hyperopt_list_profitable', False),
|
||||
'filter_min_trades': config.get('hyperopt_list_min_trades', 0),
|
||||
'filter_max_trades': config.get('hyperopt_list_max_trades', 0),
|
||||
'filter_min_avg_time': config.get('hyperopt_list_min_avg_time', None),
|
||||
'filter_max_avg_time': config.get('hyperopt_list_max_avg_time', None),
|
||||
'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit', None),
|
||||
'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit', None),
|
||||
'filter_min_total_profit': config.get('hyperopt_list_min_total_profit', None),
|
||||
'filter_max_total_profit': config.get('hyperopt_list_max_total_profit', None)
|
||||
}
|
||||
|
||||
trials_file = (config['user_data_dir'] /
|
||||
'hyperopt_results' / 'hyperopt_results.pickle')
|
||||
|
||||
# Previous evaluations
|
||||
trials = Hyperopt.load_previous_results(trials_file)
|
||||
total_epochs = len(trials)
|
||||
|
||||
trials = _hyperopt_filter_trials(trials, filteroptions)
|
||||
|
||||
# TODO: fetch the interval for epochs to print from the cli option
|
||||
epoch_start, epoch_stop = 0, None
|
||||
|
||||
if print_colorized:
|
||||
colorama_init(autoreset=True)
|
||||
|
||||
try:
|
||||
# Human-friendly indexes used here (starting from 1)
|
||||
for val in trials[epoch_start:epoch_stop]:
|
||||
Hyperopt.print_results_explanation(val, total_epochs,
|
||||
not filteroptions['only_best'], print_colorized)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print('User interrupted..')
|
||||
|
||||
if trials and not no_details:
|
||||
sorted_trials = sorted(trials, key=itemgetter('loss'))
|
||||
results = sorted_trials[0]
|
||||
Hyperopt.print_epoch_details(results, total_epochs, print_json, no_header)
|
||||
|
||||
|
||||
def start_hyperopt_show(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Show details of a hyperopt epoch previously evaluated
|
||||
"""
|
||||
from freqtrade.optimize.hyperopt import Hyperopt
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
filteroptions = {
|
||||
'only_best': config.get('hyperopt_list_best', False),
|
||||
'only_profitable': config.get('hyperopt_list_profitable', False),
|
||||
'filter_min_trades': config.get('hyperopt_list_min_trades', 0),
|
||||
'filter_max_trades': config.get('hyperopt_list_max_trades', 0),
|
||||
'filter_min_avg_time': config.get('hyperopt_list_min_avg_time', None),
|
||||
'filter_max_avg_time': config.get('hyperopt_list_max_avg_time', None),
|
||||
'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit', None),
|
||||
'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit', None),
|
||||
'filter_min_total_profit': config.get('hyperopt_list_min_total_profit', None),
|
||||
'filter_max_total_profit': config.get('hyperopt_list_max_total_profit', None)
|
||||
}
|
||||
no_header = config.get('hyperopt_show_no_header', False)
|
||||
|
||||
trials_file = (config['user_data_dir'] /
|
||||
'hyperopt_results' / 'hyperopt_results.pickle')
|
||||
|
||||
# Previous evaluations
|
||||
trials = Hyperopt.load_previous_results(trials_file)
|
||||
total_epochs = len(trials)
|
||||
|
||||
trials = _hyperopt_filter_trials(trials, filteroptions)
|
||||
trials_epochs = len(trials)
|
||||
|
||||
n = config.get('hyperopt_show_index', -1)
|
||||
if n > trials_epochs:
|
||||
raise OperationalException(
|
||||
f"The index of the epoch to show should be less than {trials_epochs + 1}.")
|
||||
if n < -trials_epochs:
|
||||
raise OperationalException(
|
||||
f"The index of the epoch to show should be greater than {-trials_epochs - 1}.")
|
||||
|
||||
# Translate epoch index from human-readable format to pythonic
|
||||
if n > 0:
|
||||
n -= 1
|
||||
|
||||
print_json = config.get('print_json', False)
|
||||
|
||||
if trials:
|
||||
val = trials[n]
|
||||
Hyperopt.print_epoch_details(val, total_epochs, print_json, no_header,
|
||||
header_str="Epoch details")
|
||||
|
||||
|
||||
def _hyperopt_filter_trials(trials: List, filteroptions: dict) -> List:
|
||||
"""
|
||||
Filter our items from the list of hyperopt results
|
||||
"""
|
||||
if filteroptions['only_best']:
|
||||
trials = [x for x in trials if x['is_best']]
|
||||
if filteroptions['only_profitable']:
|
||||
trials = [x for x in trials if x['results_metrics']['profit'] > 0]
|
||||
if filteroptions['filter_min_trades'] > 0:
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['trade_count'] > filteroptions['filter_min_trades']
|
||||
]
|
||||
if filteroptions['filter_max_trades'] > 0:
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['trade_count'] < filteroptions['filter_max_trades']
|
||||
]
|
||||
if filteroptions['filter_min_avg_time'] is not None:
|
||||
trials = [x for x in trials if x['results_metrics']['trade_count'] > 0]
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['duration'] > filteroptions['filter_min_avg_time']
|
||||
]
|
||||
if filteroptions['filter_max_avg_time'] is not None:
|
||||
trials = [x for x in trials if x['results_metrics']['trade_count'] > 0]
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['duration'] < filteroptions['filter_max_avg_time']
|
||||
]
|
||||
if filteroptions['filter_min_avg_profit'] is not None:
|
||||
trials = [x for x in trials if x['results_metrics']['trade_count'] > 0]
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['avg_profit']
|
||||
> filteroptions['filter_min_avg_profit']
|
||||
]
|
||||
if filteroptions['filter_max_avg_profit'] is not None:
|
||||
trials = [x for x in trials if x['results_metrics']['trade_count'] > 0]
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['avg_profit']
|
||||
< filteroptions['filter_max_avg_profit']
|
||||
]
|
||||
if filteroptions['filter_min_total_profit'] is not None:
|
||||
trials = [x for x in trials if x['results_metrics']['trade_count'] > 0]
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['profit'] > filteroptions['filter_min_total_profit']
|
||||
]
|
||||
if filteroptions['filter_max_total_profit'] is not None:
|
||||
trials = [x for x in trials if x['results_metrics']['trade_count'] > 0]
|
||||
trials = [
|
||||
x for x in trials
|
||||
if x['results_metrics']['profit'] < filteroptions['filter_max_total_profit']
|
||||
]
|
||||
|
||||
logger.info(f"{len(trials)} " +
|
||||
("best " if filteroptions['only_best'] else "") +
|
||||
("profitable " if filteroptions['only_profitable'] else "") +
|
||||
"epochs found.")
|
||||
|
||||
return trials
|
199
freqtrade/commands/list_commands.py
Normal file
199
freqtrade/commands/list_commands.py
Normal file
@@ -0,0 +1,199 @@
|
||||
import csv
|
||||
import logging
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from colorama import init as colorama_init
|
||||
from colorama import Fore, Style
|
||||
import rapidjson
|
||||
from tabulate import tabulate
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.constants import USERPATH_HYPEROPTS, USERPATH_STRATEGIES
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import (available_exchanges, ccxt_exchanges,
|
||||
market_is_active, symbol_is_pair)
|
||||
from freqtrade.misc import plural
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start_list_exchanges(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Print available exchanges
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
exchanges = ccxt_exchanges() if args['list_exchanges_all'] else available_exchanges()
|
||||
if args['print_one_column']:
|
||||
print('\n'.join(exchanges))
|
||||
else:
|
||||
if args['list_exchanges_all']:
|
||||
print(f"All exchanges supported by the ccxt library: {', '.join(exchanges)}")
|
||||
else:
|
||||
print(f"Exchanges available for Freqtrade: {', '.join(exchanges)}")
|
||||
|
||||
|
||||
def _print_objs_tabular(objs: List, print_colorized: bool) -> None:
|
||||
if print_colorized:
|
||||
colorama_init(autoreset=True)
|
||||
red = Fore.RED
|
||||
yellow = Fore.YELLOW
|
||||
reset = Style.RESET_ALL
|
||||
else:
|
||||
red = ''
|
||||
yellow = ''
|
||||
reset = ''
|
||||
|
||||
names = [s['name'] for s in objs]
|
||||
objss_to_print = [{
|
||||
'name': s['name'] if s['name'] else "--",
|
||||
'location': s['location'].name,
|
||||
'status': (red + "LOAD FAILED" + reset if s['class'] is None
|
||||
else "OK" if names.count(s['name']) == 1
|
||||
else yellow + "DUPLICATE NAME" + reset)
|
||||
} for s in objs]
|
||||
|
||||
print(tabulate(objss_to_print, headers='keys', tablefmt='pipe'))
|
||||
|
||||
|
||||
def start_list_strategies(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Print files with Strategy custom classes available in the directory
|
||||
"""
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
directory = Path(config.get('strategy_path', config['user_data_dir'] / USERPATH_STRATEGIES))
|
||||
strategy_objs = StrategyResolver.search_all_objects(directory, not args['print_one_column'])
|
||||
# Sort alphabetically
|
||||
strategy_objs = sorted(strategy_objs, key=lambda x: x['name'])
|
||||
|
||||
if args['print_one_column']:
|
||||
print('\n'.join([s['name'] for s in strategy_objs]))
|
||||
else:
|
||||
_print_objs_tabular(strategy_objs, config.get('print_colorized', False))
|
||||
|
||||
|
||||
def start_list_hyperopts(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Print files with HyperOpt custom classes available in the directory
|
||||
"""
|
||||
from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver
|
||||
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
|
||||
|
||||
directory = Path(config.get('hyperopt_path', config['user_data_dir'] / USERPATH_HYPEROPTS))
|
||||
hyperopt_objs = HyperOptResolver.search_all_objects(directory, not args['print_one_column'])
|
||||
# Sort alphabetically
|
||||
hyperopt_objs = sorted(hyperopt_objs, key=lambda x: x['name'])
|
||||
|
||||
if args['print_one_column']:
|
||||
print('\n'.join([s['name'] for s in hyperopt_objs]))
|
||||
else:
|
||||
_print_objs_tabular(hyperopt_objs, config.get('print_colorized', False))
|
||||
|
||||
|
||||
def start_list_timeframes(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Print ticker intervals (timeframes) available on Exchange
|
||||
"""
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||
# Do not use ticker_interval set in the config
|
||||
config['ticker_interval'] = None
|
||||
|
||||
# Init exchange
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
|
||||
if args['print_one_column']:
|
||||
print('\n'.join(exchange.timeframes))
|
||||
else:
|
||||
print(f"Timeframes available for the exchange `{exchange.name}`: "
|
||||
f"{', '.join(exchange.timeframes)}")
|
||||
|
||||
|
||||
def start_list_markets(args: Dict[str, Any], pairs_only: bool = False) -> None:
|
||||
"""
|
||||
Print pairs/markets on the exchange
|
||||
:param args: Cli args from Arguments()
|
||||
:param pairs_only: if True print only pairs, otherwise print all instruments (markets)
|
||||
:return: None
|
||||
"""
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||
|
||||
# Init exchange
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
|
||||
# By default only active pairs/markets are to be shown
|
||||
active_only = not args.get('list_pairs_all', False)
|
||||
|
||||
base_currencies = args.get('base_currencies', [])
|
||||
quote_currencies = args.get('quote_currencies', [])
|
||||
|
||||
try:
|
||||
pairs = exchange.get_markets(base_currencies=base_currencies,
|
||||
quote_currencies=quote_currencies,
|
||||
pairs_only=pairs_only,
|
||||
active_only=active_only)
|
||||
# Sort the pairs/markets by symbol
|
||||
pairs = OrderedDict(sorted(pairs.items()))
|
||||
except Exception as e:
|
||||
raise OperationalException(f"Cannot get markets. Reason: {e}") from e
|
||||
|
||||
else:
|
||||
summary_str = ((f"Exchange {exchange.name} has {len(pairs)} ") +
|
||||
("active " if active_only else "") +
|
||||
(plural(len(pairs), "pair" if pairs_only else "market")) +
|
||||
(f" with {', '.join(base_currencies)} as base "
|
||||
f"{plural(len(base_currencies), 'currency', 'currencies')}"
|
||||
if base_currencies else "") +
|
||||
(" and" if base_currencies and quote_currencies else "") +
|
||||
(f" with {', '.join(quote_currencies)} as quote "
|
||||
f"{plural(len(quote_currencies), 'currency', 'currencies')}"
|
||||
if quote_currencies else ""))
|
||||
|
||||
headers = ["Id", "Symbol", "Base", "Quote", "Active",
|
||||
*(['Is pair'] if not pairs_only else [])]
|
||||
|
||||
tabular_data = []
|
||||
for _, v in pairs.items():
|
||||
tabular_data.append({'Id': v['id'], 'Symbol': v['symbol'],
|
||||
'Base': v['base'], 'Quote': v['quote'],
|
||||
'Active': market_is_active(v),
|
||||
**({'Is pair': symbol_is_pair(v['symbol'])}
|
||||
if not pairs_only else {})})
|
||||
|
||||
if (args.get('print_one_column', False) or
|
||||
args.get('list_pairs_print_json', False) or
|
||||
args.get('print_csv', False)):
|
||||
# Print summary string in the log in case of machine-readable
|
||||
# regular formats.
|
||||
logger.info(f"{summary_str}.")
|
||||
else:
|
||||
# Print empty string separating leading logs and output in case of
|
||||
# human-readable formats.
|
||||
print()
|
||||
|
||||
if len(pairs):
|
||||
if args.get('print_list', False):
|
||||
# print data as a list, with human-readable summary
|
||||
print(f"{summary_str}: {', '.join(pairs.keys())}.")
|
||||
elif args.get('print_one_column', False):
|
||||
print('\n'.join(pairs.keys()))
|
||||
elif args.get('list_pairs_print_json', False):
|
||||
print(rapidjson.dumps(list(pairs.keys()), default=str))
|
||||
elif args.get('print_csv', False):
|
||||
writer = csv.DictWriter(sys.stdout, fieldnames=headers)
|
||||
writer.writeheader()
|
||||
writer.writerows(tabular_data)
|
||||
else:
|
||||
# print data as a table, with the human-readable summary
|
||||
print(f"{summary_str}:")
|
||||
print(tabulate(tabular_data, headers='keys', tablefmt='pipe'))
|
||||
elif not (args.get('print_one_column', False) or
|
||||
args.get('list_pairs_print_json', False) or
|
||||
args.get('print_csv', False)):
|
||||
print(f"{summary_str}.")
|
102
freqtrade/commands/optimize_commands.py
Normal file
102
freqtrade/commands/optimize_commands.py
Normal file
@@ -0,0 +1,102 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.exceptions import DependencyException, OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_optimize_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:
|
||||
"""
|
||||
Prepare the configuration for the Hyperopt module
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
config = setup_utils_configuration(args, method)
|
||||
|
||||
if method == RunMode.BACKTEST:
|
||||
if config['stake_amount'] == constants.UNLIMITED_STAKE_AMOUNT:
|
||||
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
||||
constants.UNLIMITED_STAKE_AMOUNT)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def start_backtesting(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Start Backtesting script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
# Import here to avoid loading backtesting module when it's not used
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
|
||||
# Initialize configuration
|
||||
config = setup_optimize_configuration(args, RunMode.BACKTEST)
|
||||
|
||||
logger.info('Starting freqtrade in Backtesting mode')
|
||||
|
||||
# Initialize backtesting object
|
||||
backtesting = Backtesting(config)
|
||||
backtesting.start()
|
||||
|
||||
|
||||
def start_hyperopt(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Start hyperopt script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
# Import here to avoid loading hyperopt module when it's not used
|
||||
try:
|
||||
from filelock import FileLock, Timeout
|
||||
from freqtrade.optimize.hyperopt import Hyperopt
|
||||
except ImportError as e:
|
||||
raise OperationalException(
|
||||
f"{e}. Please ensure that the hyperopt dependencies are installed.") from e
|
||||
# Initialize configuration
|
||||
config = setup_optimize_configuration(args, RunMode.HYPEROPT)
|
||||
|
||||
logger.info('Starting freqtrade in Hyperopt mode')
|
||||
|
||||
lock = FileLock(Hyperopt.get_lock_filename(config))
|
||||
|
||||
try:
|
||||
with lock.acquire(timeout=1):
|
||||
|
||||
# Remove noisy log messages
|
||||
logging.getLogger('hyperopt.tpe').setLevel(logging.WARNING)
|
||||
logging.getLogger('filelock').setLevel(logging.WARNING)
|
||||
|
||||
# Initialize backtesting object
|
||||
hyperopt = Hyperopt(config)
|
||||
hyperopt.start()
|
||||
|
||||
except Timeout:
|
||||
logger.info("Another running instance of freqtrade Hyperopt detected.")
|
||||
logger.info("Simultaneous execution of multiple Hyperopt commands is not supported. "
|
||||
"Hyperopt module is resource hungry. Please run your Hyperopt sequentially "
|
||||
"or on separate machines.")
|
||||
logger.info("Quitting now.")
|
||||
# TODO: return False here in order to help freqtrade to exit
|
||||
# with non-zero exit code...
|
||||
# Same in Edge and Backtesting start() functions.
|
||||
|
||||
|
||||
def start_edge(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Start Edge script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
from freqtrade.optimize.edge_cli import EdgeCli
|
||||
# Initialize configuration
|
||||
config = setup_optimize_configuration(args, RunMode.EDGE)
|
||||
logger.info('Starting freqtrade in Edge mode')
|
||||
|
||||
# Initialize Edge object
|
||||
edge_cli = EdgeCli(config)
|
||||
edge_cli.start()
|
42
freqtrade/commands/pairlist_commands.py
Normal file
42
freqtrade/commands/pairlist_commands.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
import rapidjson
|
||||
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.resolvers import ExchangeResolver
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start_test_pairlist(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Test Pairlist configuration
|
||||
"""
|
||||
from freqtrade.pairlist.pairlistmanager import PairListManager
|
||||
config = setup_utils_configuration(args, RunMode.UTIL_EXCHANGE)
|
||||
|
||||
exchange = ExchangeResolver.load_exchange(config['exchange']['name'], config, validate=False)
|
||||
|
||||
quote_currencies = args.get('quote_currencies')
|
||||
if not quote_currencies:
|
||||
quote_currencies = [config.get('stake_currency')]
|
||||
results = {}
|
||||
for curr in quote_currencies:
|
||||
config['stake_currency'] = curr
|
||||
# Do not use ticker_interval set in the config
|
||||
pairlists = PairListManager(exchange, config)
|
||||
pairlists.refresh_pairlist()
|
||||
results[curr] = pairlists.whitelist
|
||||
|
||||
for curr, pairlist in results.items():
|
||||
if not args.get('print_one_column', False):
|
||||
print(f"Pairs for {curr}: ")
|
||||
|
||||
if args.get('print_one_column', False):
|
||||
print('\n'.join(pairlist))
|
||||
elif args.get('list_pairs_print_json', False):
|
||||
print(rapidjson.dumps(list(pairlist), default=str))
|
||||
else:
|
||||
print(pairlist)
|
@@ -1,11 +1,11 @@
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.configuration import setup_utils_configuration
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.utils import setup_utils_configuration
|
||||
|
||||
|
||||
def validate_plot_args(args: Dict[str, Any]):
|
||||
def validate_plot_args(args: Dict[str, Any]) -> None:
|
||||
if not args.get('datadir') and not args.get('config'):
|
||||
raise OperationalException(
|
||||
"You need to specify either `--datadir` or `--config` "
|
27
freqtrade/commands/trade_commands.py
Normal file
27
freqtrade/commands/trade_commands.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import logging
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start_trading(args: Dict[str, Any]) -> int:
|
||||
"""
|
||||
Main entry point for trading mode
|
||||
"""
|
||||
# Import here to avoid loading worker module when it's not used
|
||||
from freqtrade.worker import Worker
|
||||
|
||||
# Create and run worker
|
||||
worker = None
|
||||
try:
|
||||
worker = Worker(args)
|
||||
worker.run()
|
||||
except KeyboardInterrupt:
|
||||
logger.info('SIGINT received, aborting ...')
|
||||
finally:
|
||||
if worker:
|
||||
logger.info("worker found ... calling exit")
|
||||
worker.exit()
|
||||
return 0
|
@@ -1,5 +1,7 @@
|
||||
from freqtrade.configuration.arguments import Arguments # noqa: F401
|
||||
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials # noqa: F401
|
||||
from freqtrade.configuration.timerange import TimeRange # noqa: F401
|
||||
from freqtrade.configuration.configuration import Configuration # noqa: F401
|
||||
from freqtrade.configuration.config_validation import validate_config_consistency # noqa: F401
|
||||
# flake8: noqa: F401
|
||||
|
||||
from freqtrade.configuration.config_setup import setup_utils_configuration
|
||||
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials
|
||||
from freqtrade.configuration.timerange import TimeRange
|
||||
from freqtrade.configuration.configuration import Configuration
|
||||
from freqtrade.configuration.config_validation import validate_config_consistency
|
||||
|
@@ -1,16 +1,16 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import (available_exchanges, get_exchange_bad_reason,
|
||||
is_exchange_known_ccxt, is_exchange_bad,
|
||||
is_exchange_bad, is_exchange_known_ccxt,
|
||||
is_exchange_officially_supported)
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def remove_credentials(config: Dict[str, Any]):
|
||||
def remove_credentials(config: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Removes exchange keys from the configuration and specifies dry-run
|
||||
Used for backtesting / hyperopt / edge and utils.
|
||||
|
25
freqtrade/configuration/config_setup.py
Normal file
25
freqtrade/configuration/config_setup.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from .config_validation import validate_config_consistency
|
||||
from .configuration import Configuration
|
||||
from .check_exchange import remove_credentials
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_utils_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:
|
||||
"""
|
||||
Prepare the configuration for utils subcommands
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
configuration = Configuration(args, method)
|
||||
config = configuration.get_config()
|
||||
|
||||
# Ensure we do not use Exchange credentials
|
||||
remove_credentials(config)
|
||||
validate_config_consistency(config)
|
||||
|
||||
return config
|
@@ -1,10 +1,12 @@
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any, Dict
|
||||
|
||||
from jsonschema import Draft4Validator, validators
|
||||
from jsonschema.exceptions import ValidationError, best_match
|
||||
|
||||
from freqtrade import constants, OperationalException
|
||||
from freqtrade import constants
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -41,15 +43,20 @@ def validate_config_schema(conf: Dict[str, Any]) -> Dict[str, Any]:
|
||||
:param conf: Config in JSON format
|
||||
:return: Returns the config if valid, otherwise throw an exception
|
||||
"""
|
||||
conf_schema = deepcopy(constants.CONF_SCHEMA)
|
||||
if conf.get('runmode', RunMode.OTHER) in (RunMode.DRY_RUN, RunMode.LIVE):
|
||||
conf_schema['required'] = constants.SCHEMA_TRADE_REQUIRED
|
||||
else:
|
||||
conf_schema['required'] = constants.SCHEMA_MINIMAL_REQUIRED
|
||||
try:
|
||||
FreqtradeValidator(constants.CONF_SCHEMA).validate(conf)
|
||||
FreqtradeValidator(conf_schema).validate(conf)
|
||||
return conf
|
||||
except ValidationError as e:
|
||||
logger.critical(
|
||||
f"Invalid configuration. See config.json.example. Reason: {e}"
|
||||
)
|
||||
raise ValidationError(
|
||||
best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
|
||||
best_match(Draft4Validator(conf_schema).iter_errors(conf)).message
|
||||
)
|
||||
|
||||
|
||||
@@ -66,12 +73,24 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
||||
_validate_trailing_stoploss(conf)
|
||||
_validate_edge(conf)
|
||||
_validate_whitelist(conf)
|
||||
_validate_unlimited_amount(conf)
|
||||
|
||||
# validate configuration before returning
|
||||
logger.info('Validating configuration ...')
|
||||
validate_config_schema(conf)
|
||||
|
||||
|
||||
def _validate_unlimited_amount(conf: Dict[str, Any]) -> None:
|
||||
"""
|
||||
If edge is disabled, either max_open_trades or stake_amount need to be set.
|
||||
:raise: OperationalException if config validation failed
|
||||
"""
|
||||
if (not conf.get('edge', {}).get('enabled')
|
||||
and conf.get('max_open_trades') == float('inf')
|
||||
and conf.get('stake_amount') == constants.UNLIMITED_STAKE_AMOUNT):
|
||||
raise OperationalException("`max_open_trades` and `stake_amount` cannot both be unlimited.")
|
||||
|
||||
|
||||
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
|
||||
|
||||
if conf.get('stoploss') == 0.0:
|
||||
|
@@ -7,15 +7,16 @@ from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from freqtrade import OperationalException, constants
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration.check_exchange import check_exchange
|
||||
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||
from freqtrade.configuration.directory_operations import (create_datadir,
|
||||
create_userdata_dir)
|
||||
from freqtrade.configuration.load_config import load_config_file
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.loggers import setup_logging
|
||||
from freqtrade.misc import deep_merge_dicts, json_load
|
||||
from freqtrade.state import RunMode, TRADING_MODES, NON_UTIL_MODES
|
||||
from freqtrade.state import NON_UTIL_MODES, TRADING_MODES, RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -223,13 +224,13 @@ class Configuration:
|
||||
logger.info('max_open_trades set to unlimited ...')
|
||||
elif 'max_open_trades' in self.args and self.args["max_open_trades"]:
|
||||
config.update({'max_open_trades': self.args["max_open_trades"]})
|
||||
logger.info('Parameter --max_open_trades detected, '
|
||||
logger.info('Parameter --max-open-trades detected, '
|
||||
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||
elif config['runmode'] in NON_UTIL_MODES:
|
||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||
|
||||
self._args_to_config(config, argname='stake_amount',
|
||||
logstring='Parameter --stake_amount detected, '
|
||||
logstring='Parameter --stake-amount detected, '
|
||||
'overriding stake_amount to: {} ...')
|
||||
|
||||
self._args_to_config(config, argname='fee',
|
||||
@@ -309,6 +310,30 @@ class Configuration:
|
||||
self._args_to_config(config, argname='hyperopt_list_profitable',
|
||||
logstring='Parameter --profitable detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_min_trades',
|
||||
logstring='Parameter --min-trades detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_max_trades',
|
||||
logstring='Parameter --max-trades detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_min_avg_time',
|
||||
logstring='Parameter --min-avg-time detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_max_avg_time',
|
||||
logstring='Parameter --max-avg-time detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_min_avg_profit',
|
||||
logstring='Parameter --min-avg-profit detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_max_avg_profit',
|
||||
logstring='Parameter --max-avg-profit detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_min_total_profit',
|
||||
logstring='Parameter --min-total-profit detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_max_total_profit',
|
||||
logstring='Parameter --max-total-profit detected: {}')
|
||||
|
||||
self._args_to_config(config, argname='hyperopt_list_no_details',
|
||||
logstring='Parameter --no-details detected: {}')
|
||||
|
||||
@@ -339,9 +364,16 @@ class Configuration:
|
||||
|
||||
self._args_to_config(config, argname='days',
|
||||
logstring='Detected --days: {}')
|
||||
|
||||
self._args_to_config(config, argname='download_trades',
|
||||
logstring='Detected --dl-trades: {}')
|
||||
|
||||
self._args_to_config(config, argname='dataformat_ohlcv',
|
||||
logstring='Using "{}" to store OHLCV data.')
|
||||
|
||||
self._args_to_config(config, argname='dataformat_trades',
|
||||
logstring='Using "{}" to store trades data.')
|
||||
|
||||
def _process_runmode(self, config: Dict[str, Any]) -> None:
|
||||
|
||||
if not self.runmode:
|
||||
@@ -403,7 +435,7 @@ class Configuration:
|
||||
config['pairs'] = config.get('exchange', {}).get('pair_whitelist')
|
||||
else:
|
||||
# Fall back to /dl_path/pairs.json
|
||||
pairs_file = Path(config['datadir']) / "pairs.json"
|
||||
pairs_file = config['datadir'] / "pairs.json"
|
||||
if pairs_file.exists():
|
||||
with pairs_file.open('r') as f:
|
||||
config['pairs'] = json_load(f)
|
||||
|
@@ -5,7 +5,7 @@ Functions to handle deprecated settings
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -13,7 +13,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
def check_conflicting_settings(config: Dict[str, Any],
|
||||
section1: str, name1: str,
|
||||
section2: str, name2: str):
|
||||
section2: str, name2: str) -> None:
|
||||
section1_config = config.get(section1, {})
|
||||
section2_config = config.get(section2, {})
|
||||
if name1 in section1_config and name2 in section2_config:
|
||||
@@ -28,7 +28,7 @@ def check_conflicting_settings(config: Dict[str, Any],
|
||||
|
||||
def process_deprecated_setting(config: Dict[str, Any],
|
||||
section1: str, name1: str,
|
||||
section2: str, name2: str):
|
||||
section2: str, name2: str) -> None:
|
||||
section2_config = config.get(section2, {})
|
||||
|
||||
if name2 in section2_config:
|
||||
@@ -80,3 +80,13 @@ def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||
f"Using precision_filter setting is deprecated and has been replaced by"
|
||||
"PrecisionFilter. Please refer to the docs on configuration details")
|
||||
config['pairlists'].append({'method': 'PrecisionFilter'})
|
||||
|
||||
if (config.get('edge', {}).get('enabled', False)
|
||||
and 'capital_available_percentage' in config.get('edge', {})):
|
||||
logger.warning(
|
||||
"DEPRECATED: "
|
||||
"Using 'edge.capital_available_percentage' has been deprecated in favor of "
|
||||
"'tradable_balance_ratio'. Please migrate your configuration to "
|
||||
"'tradable_balance_ratio' and remove 'capital_available_percentage' "
|
||||
"from the edge configuration."
|
||||
)
|
||||
|
@@ -3,13 +3,13 @@ import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.constants import USER_DATA_FILES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> str:
|
||||
def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> Path:
|
||||
|
||||
folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data")
|
||||
if not datadir:
|
||||
@@ -20,10 +20,10 @@ def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> str
|
||||
if not folder.is_dir():
|
||||
folder.mkdir(parents=True)
|
||||
logger.info(f'Created data directory: {datadir}')
|
||||
return str(folder)
|
||||
return folder
|
||||
|
||||
|
||||
def create_userdata_dir(directory: str, create_dir=False) -> Path:
|
||||
def create_userdata_dir(directory: str, create_dir: bool = False) -> Path:
|
||||
"""
|
||||
Create userdata directory structure.
|
||||
if create_dir is True, then the parent-directory will be created if it does not exist.
|
||||
|
@@ -6,7 +6,7 @@ import logging
|
||||
import sys
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
@@ -7,6 +7,7 @@ from typing import Optional
|
||||
|
||||
import arrow
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -30,7 +31,7 @@ class TimeRange:
|
||||
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
||||
and self.startts == other.startts and self.stopts == other.stopts)
|
||||
|
||||
def subtract_start(self, seconds) -> None:
|
||||
def subtract_start(self, seconds: int) -> None:
|
||||
"""
|
||||
Subtracts <seconds> from startts if startts is set.
|
||||
:param seconds: Seconds to subtract from starttime
|
||||
@@ -59,7 +60,7 @@ class TimeRange:
|
||||
self.starttype = 'date'
|
||||
|
||||
@staticmethod
|
||||
def parse_timerange(text: Optional[str]):
|
||||
def parse_timerange(text: Optional[str]) -> 'TimeRange':
|
||||
"""
|
||||
Parse the value of the argument --timerange to determine what is the range desired
|
||||
:param text: value from --timerange
|
||||
|
@@ -10,35 +10,33 @@ HYPEROPT_EPOCH = 100 # epochs
|
||||
RETRY_TIMEOUT = 30 # sec
|
||||
DEFAULT_HYPEROPT_LOSS = 'DefaultHyperOptLoss'
|
||||
DEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'
|
||||
DEFAULT_DB_DRYRUN_URL = 'sqlite://'
|
||||
DEFAULT_DB_DRYRUN_URL = 'sqlite:///tradesv3.dryrun.sqlite'
|
||||
UNLIMITED_STAKE_AMOUNT = 'unlimited'
|
||||
DEFAULT_AMOUNT_RESERVE_PERCENT = 0.05
|
||||
REQUIRED_ORDERTIF = ['buy', 'sell']
|
||||
REQUIRED_ORDERTYPES = ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']
|
||||
ORDERTYPE_POSSIBILITIES = ['limit', 'market']
|
||||
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc']
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'PrecisionFilter', 'PriceFilter']
|
||||
DRY_RUN_WALLET = 999.9
|
||||
AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList',
|
||||
'PrecisionFilter', 'PriceFilter', 'SpreadFilter']
|
||||
AVAILABLE_DATAHANDLERS = ['json', 'jsongz']
|
||||
DRY_RUN_WALLET = 1000
|
||||
MATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons
|
||||
DEFAULT_DATAFRAME_COLUMNS = ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
|
||||
USERPATH_HYPEROPTS = 'hyperopts'
|
||||
USERPATH_STRATEGY = 'strategies'
|
||||
USERPATH_STRATEGIES = 'strategies'
|
||||
USERPATH_NOTEBOOKS = 'notebooks'
|
||||
|
||||
# Soure files with destination directories within user-directory
|
||||
USER_DATA_FILES = {
|
||||
'sample_strategy.py': USERPATH_STRATEGY,
|
||||
'sample_strategy.py': USERPATH_STRATEGIES,
|
||||
'sample_hyperopt_advanced.py': USERPATH_HYPEROPTS,
|
||||
'sample_hyperopt_loss.py': USERPATH_HYPEROPTS,
|
||||
'sample_hyperopt.py': USERPATH_HYPEROPTS,
|
||||
'strategy_analysis_example.ipynb': 'notebooks',
|
||||
'strategy_analysis_example.ipynb': USERPATH_NOTEBOOKS,
|
||||
}
|
||||
|
||||
TIMEFRAMES = [
|
||||
'1m', '3m', '5m', '15m', '30m',
|
||||
'1h', '2h', '4h', '6h', '8h', '12h',
|
||||
'1d', '3d', '1w',
|
||||
]
|
||||
|
||||
SUPPORTED_FIAT = [
|
||||
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
|
||||
"EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
|
||||
@@ -66,16 +64,26 @@ CONF_SCHEMA = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'max_open_trades': {'type': ['integer', 'number'], 'minimum': -1},
|
||||
'ticker_interval': {'type': 'string', 'enum': TIMEFRAMES},
|
||||
'stake_currency': {'type': 'string', 'enum': ['BTC', 'XBT', 'ETH', 'USDT', 'EUR', 'USD']},
|
||||
'ticker_interval': {'type': 'string'},
|
||||
'stake_currency': {'type': 'string'},
|
||||
'stake_amount': {
|
||||
'type': ['number', 'string'],
|
||||
'minimum': 0.0001,
|
||||
'pattern': UNLIMITED_STAKE_AMOUNT
|
||||
},
|
||||
'tradable_balance_ratio': {
|
||||
'type': 'number',
|
||||
'minimum': 0.1,
|
||||
'maximum': 1,
|
||||
'default': 0.99
|
||||
},
|
||||
'amend_last_stake_amount': {'type': 'boolean', 'default': False},
|
||||
'last_stake_amount_min_ratio': {
|
||||
'type': 'number', 'minimum': 0.0, 'maximum': 1.0, 'default': 0.5
|
||||
},
|
||||
'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},
|
||||
'dry_run': {'type': 'boolean'},
|
||||
'dry_run_wallet': {'type': 'number'},
|
||||
'dry_run_wallet': {'type': 'number', 'default': DRY_RUN_WALLET},
|
||||
'process_only_new_candles': {'type': 'boolean'},
|
||||
'minimal_roi': {
|
||||
'type': 'object',
|
||||
@@ -185,7 +193,9 @@ CONF_SCHEMA = {
|
||||
'properties': {
|
||||
'enabled': {'type': 'boolean'},
|
||||
'webhookbuy': {'type': 'object'},
|
||||
'webhookbuycancel': {'type': 'object'},
|
||||
'webhooksell': {'type': 'object'},
|
||||
'webhooksellcancel': {'type': 'object'},
|
||||
'webhookstatus': {'type': 'object'},
|
||||
},
|
||||
},
|
||||
@@ -209,11 +219,22 @@ CONF_SCHEMA = {
|
||||
'forcebuy_enable': {'type': 'boolean'},
|
||||
'internals': {
|
||||
'type': 'object',
|
||||
'default': {},
|
||||
'properties': {
|
||||
'process_throttle_secs': {'type': 'integer'},
|
||||
'interval': {'type': 'integer'},
|
||||
'sd_notify': {'type': 'boolean'},
|
||||
}
|
||||
},
|
||||
'dataformat_ohlcv': {
|
||||
'type': 'string',
|
||||
'enum': AVAILABLE_DATAHANDLERS,
|
||||
'default': 'json'
|
||||
},
|
||||
'dataformat_trades': {
|
||||
'type': 'string',
|
||||
'enum': AVAILABLE_DATAHANDLERS,
|
||||
'default': 'jsongz'
|
||||
}
|
||||
},
|
||||
'definitions': {
|
||||
@@ -266,18 +287,32 @@ CONF_SCHEMA = {
|
||||
'max_trade_duration_minute': {'type': 'integer'},
|
||||
'remove_pumps': {'type': 'boolean'}
|
||||
},
|
||||
'required': ['process_throttle_secs', 'allowed_risk', 'capital_available_percentage']
|
||||
'required': ['process_throttle_secs', 'allowed_risk']
|
||||
}
|
||||
},
|
||||
'required': [
|
||||
}
|
||||
|
||||
SCHEMA_TRADE_REQUIRED = [
|
||||
'exchange',
|
||||
'max_open_trades',
|
||||
'stake_currency',
|
||||
'stake_amount',
|
||||
'tradable_balance_ratio',
|
||||
'last_stake_amount_min_ratio',
|
||||
'dry_run',
|
||||
'dry_run_wallet',
|
||||
'bid_strategy',
|
||||
'unfilledtimeout',
|
||||
'stoploss',
|
||||
'minimal_roi',
|
||||
'internals',
|
||||
'dataformat_ohlcv',
|
||||
'dataformat_trades',
|
||||
]
|
||||
|
||||
SCHEMA_MINIMAL_REQUIRED = [
|
||||
'exchange',
|
||||
'dry_run',
|
||||
'dataformat_ohlcv',
|
||||
'dataformat_trades',
|
||||
]
|
||||
}
|
||||
|
@@ -3,7 +3,7 @@ Helpers when analyzing backtest data
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
from typing import Dict, Union
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
@@ -20,7 +20,7 @@ BT_DATA_COLUMNS = ["pair", "profitperc", "open_time", "close_time", "index", "du
|
||||
"open_rate", "close_rate", "open_at_end", "sell_reason"]
|
||||
|
||||
|
||||
def load_backtest_data(filename) -> pd.DataFrame:
|
||||
def load_backtest_data(filename: Union[Path, str]) -> pd.DataFrame:
|
||||
"""
|
||||
Load backtest data file.
|
||||
:param filename: pathlib.Path object, or string pointing to the file.
|
||||
@@ -47,7 +47,7 @@ def load_backtest_data(filename) -> pd.DataFrame:
|
||||
utc=True,
|
||||
infer_datetime_format=True
|
||||
)
|
||||
df['profitabs'] = df['close_rate'] - df['open_rate']
|
||||
df['profit'] = df['close_rate'] - df['open_rate']
|
||||
df = df.sort_values("open_time").reset_index(drop=True)
|
||||
return df
|
||||
|
||||
@@ -108,7 +108,7 @@ def load_trades_from_db(db_url: str) -> pd.DataFrame:
|
||||
trades = pd.DataFrame([(t.pair,
|
||||
t.open_date.replace(tzinfo=timezone.utc),
|
||||
t.close_date.replace(tzinfo=timezone.utc) if t.close_date else None,
|
||||
t.calc_profit(), t.calc_profit_percent(),
|
||||
t.calc_profit(), t.calc_profit_ratio(),
|
||||
t.open_rate, t.close_rate, t.amount,
|
||||
(round((t.close_date.timestamp() - t.open_date.timestamp()) / 60, 2)
|
||||
if t.close_date else None),
|
||||
@@ -151,7 +151,8 @@ def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> p
|
||||
return trades
|
||||
|
||||
|
||||
def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = "close"):
|
||||
def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame],
|
||||
column: str = "close") -> pd.DataFrame:
|
||||
"""
|
||||
Combine multiple dataframes "column"
|
||||
:param tickers: Dict of Dataframes, dict key should be pair.
|
||||
|
@@ -2,10 +2,13 @@
|
||||
Functions to convert data from one format to another
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
import pandas as pd
|
||||
from pandas import DataFrame, to_datetime
|
||||
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -24,7 +27,7 @@ def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *,
|
||||
:return: DataFrame
|
||||
"""
|
||||
logger.debug("Parsing tickerlist to dataframe")
|
||||
cols = ['date', 'open', 'high', 'low', 'close', 'volume']
|
||||
cols = DEFAULT_DATAFRAME_COLUMNS
|
||||
frame = DataFrame(ticker, columns=cols)
|
||||
|
||||
frame['date'] = to_datetime(frame['date'],
|
||||
@@ -37,9 +40,29 @@ def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *,
|
||||
# and fail with exception...
|
||||
frame = frame.astype(dtype={'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float',
|
||||
'volume': 'float'})
|
||||
return clean_ohlcv_dataframe(frame, timeframe, pair,
|
||||
fill_missing=fill_missing,
|
||||
drop_incomplete=drop_incomplete)
|
||||
|
||||
|
||||
def clean_ohlcv_dataframe(data: DataFrame, timeframe: str, pair: str, *,
|
||||
fill_missing: bool = True,
|
||||
drop_incomplete: bool = True) -> DataFrame:
|
||||
"""
|
||||
Clense a ohlcv dataframe by
|
||||
* Grouping it by date (removes duplicate tics)
|
||||
* dropping last candles if requested
|
||||
* Filling up missing data (if requested)
|
||||
:param data: DataFrame containing ohlcv data.
|
||||
:param timeframe: timeframe (e.g. 5m). Used to fill up eventual missing data
|
||||
:param pair: Pair this data is for (used to warn if fillup was necessary)
|
||||
:param fill_missing: fill up missing candles with 0 candles
|
||||
(see ohlcv_fill_up_missing_data for details)
|
||||
:param drop_incomplete: Drop the last candle of the dataframe, assuming it's incomplete
|
||||
:return: DataFrame
|
||||
"""
|
||||
# group by index and aggregate results to eliminate duplicate ticks
|
||||
frame = frame.groupby(by='date', as_index=False, sort=True).agg({
|
||||
data = data.groupby(by='date', as_index=False, sort=True).agg({
|
||||
'open': 'first',
|
||||
'high': 'max',
|
||||
'low': 'min',
|
||||
@@ -48,13 +71,13 @@ def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *,
|
||||
})
|
||||
# eliminate partial candle
|
||||
if drop_incomplete:
|
||||
frame.drop(frame.tail(1).index, inplace=True)
|
||||
data.drop(data.tail(1).index, inplace=True)
|
||||
logger.debug('Dropping last candle')
|
||||
|
||||
if fill_missing:
|
||||
return ohlcv_fill_up_missing_data(frame, timeframe, pair)
|
||||
return ohlcv_fill_up_missing_data(data, timeframe, pair)
|
||||
else:
|
||||
return frame
|
||||
return data
|
||||
|
||||
|
||||
def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str) -> DataFrame:
|
||||
@@ -92,8 +115,26 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str)
|
||||
return df
|
||||
|
||||
|
||||
def trim_dataframe(df: DataFrame, timerange, df_date_col: str = 'date') -> DataFrame:
|
||||
"""
|
||||
Trim dataframe based on given timerange
|
||||
:param df: Dataframe to trim
|
||||
:param timerange: timerange (use start and end date if available)
|
||||
:param: df_date_col: Column in the dataframe to use as Date column
|
||||
:return: trimmed dataframe
|
||||
"""
|
||||
if timerange.starttype == 'date':
|
||||
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||
df = df.loc[df[df_date_col] >= start, :]
|
||||
if timerange.stoptype == 'date':
|
||||
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||
df = df.loc[df[df_date_col] <= stop, :]
|
||||
return df
|
||||
|
||||
|
||||
def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
||||
"""
|
||||
TODO: This should get a dedicated test
|
||||
Gets order book list, returns dataframe with below format per suggested by creslin
|
||||
-------------------------------------------------------------------
|
||||
b_sum b_size bids asks a_size a_sum
|
||||
@@ -116,12 +157,13 @@ def order_book_to_dataframe(bids: list, asks: list) -> DataFrame:
|
||||
return frame
|
||||
|
||||
|
||||
def trades_to_ohlcv(trades: list, timeframe: str) -> list:
|
||||
def trades_to_ohlcv(trades: list, timeframe: str) -> DataFrame:
|
||||
"""
|
||||
Converts trades list to ohlcv list
|
||||
TODO: This should get a dedicated test
|
||||
:param trades: List of trades, as returned by ccxt.fetch_trades.
|
||||
:param timeframe: Ticker timeframe to resample data to
|
||||
:return: ohlcv timeframe as list (as returned by ccxt.fetch_ohlcv)
|
||||
:return: ohlcv Dataframe.
|
||||
"""
|
||||
from freqtrade.exchange import timeframe_to_minutes
|
||||
ticker_minutes = timeframe_to_minutes(timeframe)
|
||||
@@ -131,8 +173,68 @@ def trades_to_ohlcv(trades: list, timeframe: str) -> list:
|
||||
|
||||
df_new = df['price'].resample(f'{ticker_minutes}min').ohlc()
|
||||
df_new['volume'] = df['amount'].resample(f'{ticker_minutes}min').sum()
|
||||
df_new['date'] = df_new.index.astype("int64") // 10 ** 6
|
||||
df_new['date'] = df_new.index
|
||||
# Drop 0 volume rows
|
||||
df_new = df_new.dropna()
|
||||
columns = ["date", "open", "high", "low", "close", "volume"]
|
||||
return list(zip(*[df_new[x].values.tolist() for x in columns]))
|
||||
return df_new[DEFAULT_DATAFRAME_COLUMNS]
|
||||
|
||||
|
||||
def convert_trades_format(config: Dict[str, Any], 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 souce 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(config: Dict[str, Any], convert_from: str, convert_to: str, erase: bool):
|
||||
"""
|
||||
Convert ohlcv from one format to another format.
|
||||
:param config: Config dictionary
|
||||
:param convert_from: Source format
|
||||
:param convert_to: Target format
|
||||
:param erase: Erase souce 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)
|
||||
timeframes = config.get('timeframes', [config.get('ticker_interval')])
|
||||
logger.info(f"Converting OHLCV for timeframe {timeframes}")
|
||||
|
||||
if 'pairs' not in config:
|
||||
config['pairs'] = []
|
||||
# Check timeframes or fall back to ticker_interval.
|
||||
for timeframe in timeframes:
|
||||
config['pairs'].extend(src.ohlcv_get_pairs(config['datadir'],
|
||||
timeframe))
|
||||
logger.info(f"Converting OHLCV for {config['pairs']}")
|
||||
|
||||
for timeframe in timeframes:
|
||||
for pair in config['pairs']:
|
||||
data = src.ohlcv_load(pair=pair, timeframe=timeframe,
|
||||
timerange=None,
|
||||
fill_missing=False,
|
||||
drop_incomplete=False,
|
||||
startup_candles=0)
|
||||
logger.info(f"Converting {len(data)} candles for {pair}")
|
||||
trg.ohlcv_store(pair=pair, timeframe=timeframe, data=data)
|
||||
if erase and convert_from != convert_to:
|
||||
logger.info(f"Deleting source data for {pair} / {timeframe}")
|
||||
src.ohlcv_purge(pair=pair, timeframe=timeframe)
|
||||
|
@@ -5,7 +5,6 @@ including Klines, tickers, historic data
|
||||
Common Interface for bot and strategy to access data.
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from pandas import DataFrame
|
||||
@@ -65,7 +64,7 @@ class DataProvider:
|
||||
"""
|
||||
return load_pair_history(pair=pair,
|
||||
timeframe=timeframe or self._config['ticker_interval'],
|
||||
datadir=Path(self._config['datadir'])
|
||||
datadir=self._config['datadir']
|
||||
)
|
||||
|
||||
def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame:
|
||||
|
@@ -1,484 +0,0 @@
|
||||
"""
|
||||
Handle historic data (ohlcv).
|
||||
|
||||
Includes:
|
||||
* load data for a pair (or a list of pairs) from disk
|
||||
* download data from exchange and store to disk
|
||||
"""
|
||||
|
||||
import logging
|
||||
import operator
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import OperationalException, misc
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.data.converter import parse_ticker_dataframe, trades_to_ohlcv
|
||||
from freqtrade.exchange import Exchange, timeframe_to_minutes, timeframe_to_seconds
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def trim_tickerlist(tickerlist: List[Dict], timerange: TimeRange) -> List[Dict]:
|
||||
"""
|
||||
Trim tickerlist based on given timerange
|
||||
"""
|
||||
if not tickerlist:
|
||||
return tickerlist
|
||||
|
||||
start_index = 0
|
||||
stop_index = len(tickerlist)
|
||||
|
||||
if timerange.starttype == 'date':
|
||||
while (start_index < len(tickerlist) and
|
||||
tickerlist[start_index][0] < timerange.startts * 1000):
|
||||
start_index += 1
|
||||
|
||||
if timerange.stoptype == 'date':
|
||||
while (stop_index > 0 and
|
||||
tickerlist[stop_index-1][0] > timerange.stopts * 1000):
|
||||
stop_index -= 1
|
||||
|
||||
if start_index > stop_index:
|
||||
raise ValueError(f'The timerange [{timerange.startts},{timerange.stopts}] is incorrect')
|
||||
|
||||
return tickerlist[start_index:stop_index]
|
||||
|
||||
|
||||
def trim_dataframe(df: DataFrame, timerange: TimeRange, df_date_col: str = 'date') -> DataFrame:
|
||||
"""
|
||||
Trim dataframe based on given timerange
|
||||
:param df: Dataframe to trim
|
||||
:param timerange: timerange (use start and end date if available)
|
||||
:param: df_date_col: Column in the dataframe to use as Date column
|
||||
:return: trimmed dataframe
|
||||
"""
|
||||
if timerange.starttype == 'date':
|
||||
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||
df = df.loc[df[df_date_col] >= start, :]
|
||||
if timerange.stoptype == 'date':
|
||||
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||
df = df.loc[df[df_date_col] <= stop, :]
|
||||
return df
|
||||
|
||||
|
||||
def load_tickerdata_file(datadir: Path, pair: str, timeframe: str,
|
||||
timerange: Optional[TimeRange] = None) -> Optional[list]:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
:return: tickerlist or None if unsuccessful
|
||||
"""
|
||||
filename = pair_data_filename(datadir, pair, timeframe)
|
||||
pairdata = misc.file_load_json(filename)
|
||||
if not pairdata:
|
||||
return []
|
||||
|
||||
if timerange:
|
||||
pairdata = trim_tickerlist(pairdata, timerange)
|
||||
return pairdata
|
||||
|
||||
|
||||
def store_tickerdata_file(datadir: Path, pair: str,
|
||||
timeframe: str, data: list, is_zip: bool = False):
|
||||
"""
|
||||
Stores tickerdata to file
|
||||
"""
|
||||
filename = pair_data_filename(datadir, pair, timeframe)
|
||||
misc.file_dump_json(filename, data, is_zip=is_zip)
|
||||
|
||||
|
||||
def load_trades_file(datadir: Path, pair: str,
|
||||
timerange: Optional[TimeRange] = None) -> List[Dict]:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
:return: tradelist or empty list if unsuccesful
|
||||
"""
|
||||
filename = pair_trades_filename(datadir, pair)
|
||||
tradesdata = misc.file_load_json(filename)
|
||||
if not tradesdata:
|
||||
return []
|
||||
|
||||
return tradesdata
|
||||
|
||||
|
||||
def store_trades_file(datadir: Path, pair: str,
|
||||
data: list, is_zip: bool = True):
|
||||
"""
|
||||
Stores tickerdata to file
|
||||
"""
|
||||
filename = pair_trades_filename(datadir, pair)
|
||||
misc.file_dump_json(filename, data, is_zip=is_zip)
|
||||
|
||||
|
||||
def _validate_pairdata(pair, pairdata, timerange: TimeRange):
|
||||
if timerange.starttype == 'date' and pairdata[0][0] > timerange.startts * 1000:
|
||||
logger.warning('Missing data at start for pair %s, data starts at %s',
|
||||
pair, arrow.get(pairdata[0][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||
if timerange.stoptype == 'date' and pairdata[-1][0] < timerange.stopts * 1000:
|
||||
logger.warning('Missing data at end for pair %s, data ends at %s',
|
||||
pair, arrow.get(pairdata[-1][0] // 1000).strftime('%Y-%m-%d %H:%M:%S'))
|
||||
|
||||
|
||||
def load_pair_history(pair: str,
|
||||
timeframe: str,
|
||||
datadir: Path,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
refresh_pairs: bool = False,
|
||||
exchange: Optional[Exchange] = None,
|
||||
fill_up_missing: bool = True,
|
||||
drop_incomplete: bool = True,
|
||||
startup_candles: int = 0,
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Loads cached ticker history for the given pair.
|
||||
:param pair: Pair to load data for
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:param datadir: Path to the data storage location.
|
||||
:param timerange: Limit data to be loaded to this timerange
|
||||
:param refresh_pairs: Refresh pairs from exchange.
|
||||
(Note: Requires exchange to be passed as well.)
|
||||
:param exchange: Exchange object (needed when using "refresh_pairs")
|
||||
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||
:param startup_candles: Additional candles to load at the start of the period
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
|
||||
timerange_startup = deepcopy(timerange)
|
||||
if startup_candles > 0 and timerange_startup:
|
||||
timerange_startup.subtract_start(timeframe_to_seconds(timeframe) * startup_candles)
|
||||
|
||||
# The user forced the refresh of pairs
|
||||
if refresh_pairs:
|
||||
download_pair_history(datadir=datadir,
|
||||
exchange=exchange,
|
||||
pair=pair,
|
||||
timeframe=timeframe,
|
||||
timerange=timerange)
|
||||
|
||||
pairdata = load_tickerdata_file(datadir, pair, timeframe, timerange=timerange_startup)
|
||||
|
||||
if pairdata:
|
||||
if timerange_startup:
|
||||
_validate_pairdata(pair, pairdata, timerange_startup)
|
||||
return parse_ticker_dataframe(pairdata, timeframe, pair=pair,
|
||||
fill_missing=fill_up_missing,
|
||||
drop_incomplete=drop_incomplete)
|
||||
else:
|
||||
logger.warning(
|
||||
f'No history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||
'Use `freqtrade download-data` to download the data'
|
||||
)
|
||||
return DataFrame()
|
||||
|
||||
|
||||
def load_data(datadir: Path,
|
||||
timeframe: str,
|
||||
pairs: List[str],
|
||||
refresh_pairs: bool = False,
|
||||
exchange: Optional[Exchange] = None,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
fill_up_missing: bool = True,
|
||||
startup_candles: int = 0,
|
||||
fail_without_data: bool = False
|
||||
) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Loads ticker history data for a list of pairs
|
||||
:param datadir: Path to the data storage location.
|
||||
:param timeframe: Ticker Timeframe (e.g. "5m")
|
||||
:param pairs: List of pairs to load
|
||||
:param refresh_pairs: Refresh pairs from exchange.
|
||||
(Note: Requires exchange to be passed as well.)
|
||||
:param exchange: Exchange object (needed when using "refresh_pairs")
|
||||
:param timerange: Limit data to be loaded to this timerange
|
||||
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||
:param startup_candles: Additional candles to load at the start of the period
|
||||
:param fail_without_data: Raise OperationalException if no data is found.
|
||||
:return: dict(<pair>:<Dataframe>)
|
||||
TODO: refresh_pairs is still used by edge to keep the data uptodate.
|
||||
This should be replaced in the future. Instead, writing the current candles to disk
|
||||
from dataprovider should be implemented, as this would avoid loading ohlcv data twice.
|
||||
exchange and refresh_pairs are then not needed here nor in load_pair_history.
|
||||
"""
|
||||
result: Dict[str, DataFrame] = {}
|
||||
if startup_candles > 0 and timerange:
|
||||
logger.info(f'Using indicator startup period: {startup_candles} ...')
|
||||
|
||||
for pair in pairs:
|
||||
hist = load_pair_history(pair=pair, timeframe=timeframe,
|
||||
datadir=datadir, timerange=timerange,
|
||||
refresh_pairs=refresh_pairs,
|
||||
exchange=exchange,
|
||||
fill_up_missing=fill_up_missing,
|
||||
startup_candles=startup_candles)
|
||||
if not hist.empty:
|
||||
result[pair] = hist
|
||||
|
||||
if fail_without_data and not result:
|
||||
raise OperationalException("No data found. Terminating.")
|
||||
return result
|
||||
|
||||
|
||||
def pair_data_filename(datadir: Path, pair: str, timeframe: str) -> Path:
|
||||
pair_s = pair.replace("/", "_")
|
||||
filename = datadir.joinpath(f'{pair_s}-{timeframe}.json')
|
||||
return filename
|
||||
|
||||
|
||||
def pair_trades_filename(datadir: Path, pair: str) -> Path:
|
||||
pair_s = pair.replace("/", "_")
|
||||
filename = datadir.joinpath(f'{pair_s}-trades.json.gz')
|
||||
return filename
|
||||
|
||||
|
||||
def _load_cached_data_for_updating(datadir: Path, pair: str, timeframe: str,
|
||||
timerange: Optional[TimeRange]) -> Tuple[List[Any],
|
||||
Optional[int]]:
|
||||
"""
|
||||
Load cached data to download more data.
|
||||
If timerange is passed in, checks whether data from an before the stored data will be
|
||||
downloaded.
|
||||
If that's the case then what's available should be completely overwritten.
|
||||
Only used by download_pair_history().
|
||||
"""
|
||||
|
||||
since_ms = None
|
||||
|
||||
# user sets timerange, so find the start time
|
||||
if timerange:
|
||||
if timerange.starttype == 'date':
|
||||
since_ms = timerange.startts * 1000
|
||||
elif timerange.stoptype == 'line':
|
||||
num_minutes = timerange.stopts * timeframe_to_minutes(timeframe)
|
||||
since_ms = arrow.utcnow().shift(minutes=num_minutes).timestamp * 1000
|
||||
|
||||
# read the cached file
|
||||
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
||||
data = load_tickerdata_file(datadir, pair, timeframe)
|
||||
# remove the last item, could be incomplete candle
|
||||
if data:
|
||||
data.pop()
|
||||
else:
|
||||
data = []
|
||||
|
||||
if data:
|
||||
if since_ms and since_ms < data[0][0]:
|
||||
# Earlier data than existing data requested, redownload all
|
||||
data = []
|
||||
else:
|
||||
# a part of the data was already downloaded, so download unexist data only
|
||||
since_ms = data[-1][0] + 1
|
||||
|
||||
return (data, since_ms)
|
||||
|
||||
|
||||
def download_pair_history(datadir: Path,
|
||||
exchange: Optional[Exchange],
|
||||
pair: str,
|
||||
timeframe: str = '5m',
|
||||
timerange: Optional[TimeRange] = None) -> bool:
|
||||
"""
|
||||
Download latest candles from the exchange for the pair and timeframe passed in parameters
|
||||
The data is downloaded starting from the last correct data that
|
||||
exists in a cache. If timerange starts earlier than the data in the cache,
|
||||
the full data will be redownloaded
|
||||
|
||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||
|
||||
:param pair: pair to download
|
||||
:param timeframe: Ticker Timeframe (e.g 5m)
|
||||
:param timerange: range of time to download
|
||||
:return: bool with success state
|
||||
"""
|
||||
if not exchange:
|
||||
raise OperationalException(
|
||||
"Exchange needs to be initialized when downloading pair history data"
|
||||
)
|
||||
|
||||
try:
|
||||
logger.info(
|
||||
f'Download history data for pair: "{pair}", timeframe: {timeframe} '
|
||||
f'and store in {datadir}.'
|
||||
)
|
||||
|
||||
data, since_ms = _load_cached_data_for_updating(datadir, pair, timeframe, timerange)
|
||||
|
||||
logger.debug("Current Start: %s", misc.format_ms_time(data[1][0]) if data else 'None')
|
||||
logger.debug("Current End: %s", misc.format_ms_time(data[-1][0]) if data else 'None')
|
||||
|
||||
# Default since_ms to 30 days if nothing is given
|
||||
new_data = exchange.get_historic_ohlcv(pair=pair, timeframe=timeframe,
|
||||
since_ms=since_ms if since_ms
|
||||
else
|
||||
int(arrow.utcnow().shift(
|
||||
days=-30).float_timestamp) * 1000)
|
||||
data.extend(new_data)
|
||||
|
||||
logger.debug("New Start: %s", misc.format_ms_time(data[0][0]))
|
||||
logger.debug("New End: %s", misc.format_ms_time(data[-1][0]))
|
||||
|
||||
store_tickerdata_file(datadir, pair, timeframe, data=data)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||
f'Error: {e}'
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
||||
dl_path: Path, timerange: Optional[TimeRange] = None,
|
||||
erase=False) -> List[str]:
|
||||
"""
|
||||
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
||||
Used by freqtrade download-data
|
||||
:return: Pairs not available
|
||||
"""
|
||||
pairs_not_available = []
|
||||
for pair in pairs:
|
||||
if pair not in exchange.markets:
|
||||
pairs_not_available.append(pair)
|
||||
logger.info(f"Skipping pair {pair}...")
|
||||
continue
|
||||
for timeframe in timeframes:
|
||||
|
||||
dl_file = pair_data_filename(dl_path, pair, timeframe)
|
||||
if erase and dl_file.exists():
|
||||
logger.info(
|
||||
f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||
dl_file.unlink()
|
||||
|
||||
logger.info(f'Downloading pair {pair}, interval {timeframe}.')
|
||||
download_pair_history(datadir=dl_path, exchange=exchange,
|
||||
pair=pair, timeframe=str(timeframe),
|
||||
timerange=timerange)
|
||||
return pairs_not_available
|
||||
|
||||
|
||||
def download_trades_history(datadir: Path,
|
||||
exchange: Exchange,
|
||||
pair: str,
|
||||
timerange: Optional[TimeRange] = None) -> bool:
|
||||
"""
|
||||
Download trade history from the exchange.
|
||||
Appends to previously downloaded trades data.
|
||||
"""
|
||||
try:
|
||||
|
||||
since = timerange.startts * 1000 if timerange and timerange.starttype == 'date' else None
|
||||
|
||||
trades = load_trades_file(datadir, pair)
|
||||
|
||||
from_id = trades[-1]['id'] if trades else None
|
||||
|
||||
logger.debug("Current Start: %s", trades[0]['datetime'] if trades else 'None')
|
||||
logger.debug("Current End: %s", trades[-1]['datetime'] if trades else 'None')
|
||||
|
||||
new_trades = exchange.get_historic_trades(pair=pair,
|
||||
since=since if since else
|
||||
int(arrow.utcnow().shift(
|
||||
days=-30).float_timestamp) * 1000,
|
||||
# until=xxx,
|
||||
from_id=from_id,
|
||||
)
|
||||
trades.extend(new_trades[1])
|
||||
store_trades_file(datadir, pair, trades)
|
||||
|
||||
logger.debug("New Start: %s", trades[0]['datetime'])
|
||||
logger.debug("New End: %s", trades[-1]['datetime'])
|
||||
logger.info(f"New Amount of trades: {len(trades)}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f'Failed to download historic trades for pair: "{pair}". '
|
||||
f'Error: {e}'
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def refresh_backtest_trades_data(exchange: Exchange, pairs: List[str], datadir: Path,
|
||||
timerange: TimeRange, erase=False) -> List[str]:
|
||||
"""
|
||||
Refresh stored trades data.
|
||||
Used by freqtrade download-data
|
||||
:return: Pairs not available
|
||||
"""
|
||||
pairs_not_available = []
|
||||
for pair in pairs:
|
||||
if pair not in exchange.markets:
|
||||
pairs_not_available.append(pair)
|
||||
logger.info(f"Skipping pair {pair}...")
|
||||
continue
|
||||
|
||||
dl_file = pair_trades_filename(datadir, pair)
|
||||
if erase and dl_file.exists():
|
||||
logger.info(
|
||||
f'Deleting existing data for pair {pair}.')
|
||||
dl_file.unlink()
|
||||
|
||||
logger.info(f'Downloading trades for pair {pair}.')
|
||||
download_trades_history(datadir=datadir, exchange=exchange,
|
||||
pair=pair,
|
||||
timerange=timerange)
|
||||
return pairs_not_available
|
||||
|
||||
|
||||
def convert_trades_to_ohlcv(pairs: List[str], timeframes: List[str],
|
||||
datadir: Path, timerange: TimeRange, erase=False) -> None:
|
||||
"""
|
||||
Convert stored trades data to ohlcv data
|
||||
"""
|
||||
for pair in pairs:
|
||||
trades = load_trades_file(datadir, pair)
|
||||
for timeframe in timeframes:
|
||||
ohlcv_file = pair_data_filename(datadir, pair, timeframe)
|
||||
if erase and ohlcv_file.exists():
|
||||
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||
ohlcv_file.unlink()
|
||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||
# Store ohlcv
|
||||
store_tickerdata_file(datadir, pair, timeframe, data=ohlcv)
|
||||
|
||||
|
||||
def get_timeframe(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||
"""
|
||||
Get the maximum timeframe for the given backtest data
|
||||
:param data: dictionary with preprocessed backtesting data
|
||||
:return: tuple containing min_date, max_date
|
||||
"""
|
||||
timeframe = [
|
||||
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
||||
for frame in data.values()
|
||||
]
|
||||
return min(timeframe, key=operator.itemgetter(0))[0], \
|
||||
max(timeframe, key=operator.itemgetter(1))[1]
|
||||
|
||||
|
||||
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
||||
max_date: datetime, timeframe_mins: int) -> bool:
|
||||
"""
|
||||
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
||||
|
||||
:param data: preprocessed backtesting data (as DataFrame)
|
||||
:param pair: pair used for log output.
|
||||
:param min_date: start-date of the data
|
||||
:param max_date: end-date of the data
|
||||
:param timeframe_mins: ticker Timeframe in minutes
|
||||
"""
|
||||
# total difference in minutes / timeframe-minutes
|
||||
expected_frames = int((max_date - min_date).total_seconds() // 60 // timeframe_mins)
|
||||
found_missing = False
|
||||
dflen = len(data)
|
||||
if dflen < expected_frames:
|
||||
found_missing = True
|
||||
logger.warning("%s has missing frames: expected %s, got %s, that's %s missing values",
|
||||
pair, expected_frames, dflen, expected_frames - dflen)
|
||||
return found_missing
|
14
freqtrade/data/history/__init__.py
Normal file
14
freqtrade/data/history/__init__.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
Handle historic data (ohlcv).
|
||||
|
||||
Includes:
|
||||
* load data for a pair (or a list of pairs) from disk
|
||||
* download data from exchange and store to disk
|
||||
"""
|
||||
|
||||
from .history_utils import (convert_trades_to_ohlcv, # noqa: F401
|
||||
get_timerange, load_data, load_pair_history,
|
||||
refresh_backtest_ohlcv_data,
|
||||
refresh_backtest_trades_data, refresh_data,
|
||||
validate_backtest_data)
|
||||
from .idatahandler import get_datahandler # noqa: F401
|
375
freqtrade/data/history/history_utils.py
Normal file
375
freqtrade/data/history/history_utils.py
Normal file
@@ -0,0 +1,375 @@
|
||||
import logging
|
||||
import operator
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
||||
from freqtrade.data.converter import parse_ticker_dataframe, trades_to_ohlcv
|
||||
from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def load_pair_history(pair: str,
|
||||
timeframe: str,
|
||||
datadir: Path, *,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
fill_up_missing: bool = True,
|
||||
drop_incomplete: bool = True,
|
||||
startup_candles: int = 0,
|
||||
data_format: str = None,
|
||||
data_handler: IDataHandler = None,
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Load cached ticker history for the given pair.
|
||||
|
||||
:param pair: Pair to load data for
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:param datadir: Path to the data storage location.
|
||||
:param data_format: Format of the data. Ignored if data_handler is set.
|
||||
:param timerange: Limit data to be loaded to this timerange
|
||||
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||
:param startup_candles: Additional candles to load at the start of the period
|
||||
:param data_handler: Initialized data-handler to use.
|
||||
Will be initialized from data_format if not set
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
data_handler = get_datahandler(datadir, data_format, data_handler)
|
||||
|
||||
return data_handler.ohlcv_load(pair=pair,
|
||||
timeframe=timeframe,
|
||||
timerange=timerange,
|
||||
fill_missing=fill_up_missing,
|
||||
drop_incomplete=drop_incomplete,
|
||||
startup_candles=startup_candles,
|
||||
)
|
||||
|
||||
|
||||
def load_data(datadir: Path,
|
||||
timeframe: str,
|
||||
pairs: List[str], *,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
fill_up_missing: bool = True,
|
||||
startup_candles: int = 0,
|
||||
fail_without_data: bool = False,
|
||||
data_format: str = 'json',
|
||||
) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Load ticker history data for a list of pairs.
|
||||
|
||||
:param datadir: Path to the data storage location.
|
||||
:param timeframe: Ticker Timeframe (e.g. "5m")
|
||||
:param pairs: List of pairs to load
|
||||
:param timerange: Limit data to be loaded to this timerange
|
||||
:param fill_up_missing: Fill missing values with "No action"-candles
|
||||
:param startup_candles: Additional candles to load at the start of the period
|
||||
:param fail_without_data: Raise OperationalException if no data is found.
|
||||
:param data_format: Data format which should be used. Defaults to json
|
||||
:return: dict(<pair>:<Dataframe>)
|
||||
"""
|
||||
result: Dict[str, DataFrame] = {}
|
||||
if startup_candles > 0 and timerange:
|
||||
logger.info(f'Using indicator startup period: {startup_candles} ...')
|
||||
|
||||
data_handler = get_datahandler(datadir, data_format)
|
||||
|
||||
for pair in pairs:
|
||||
hist = load_pair_history(pair=pair, timeframe=timeframe,
|
||||
datadir=datadir, timerange=timerange,
|
||||
fill_up_missing=fill_up_missing,
|
||||
startup_candles=startup_candles,
|
||||
data_handler=data_handler
|
||||
)
|
||||
if not hist.empty:
|
||||
result[pair] = hist
|
||||
|
||||
if fail_without_data and not result:
|
||||
raise OperationalException("No data found. Terminating.")
|
||||
return result
|
||||
|
||||
|
||||
def refresh_data(datadir: Path,
|
||||
timeframe: str,
|
||||
pairs: List[str],
|
||||
exchange: Exchange,
|
||||
data_format: str = None,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Refresh ticker history data for a list of pairs.
|
||||
|
||||
:param datadir: Path to the data storage location.
|
||||
:param timeframe: Ticker Timeframe (e.g. "5m")
|
||||
:param pairs: List of pairs to load
|
||||
:param exchange: Exchange object
|
||||
:param timerange: Limit data to be loaded to this timerange
|
||||
"""
|
||||
data_handler = get_datahandler(datadir, data_format)
|
||||
for pair in pairs:
|
||||
_download_pair_history(pair=pair, timeframe=timeframe,
|
||||
datadir=datadir, timerange=timerange,
|
||||
exchange=exchange, data_handler=data_handler)
|
||||
|
||||
|
||||
def _load_cached_data_for_updating(pair: str, timeframe: str, timerange: Optional[TimeRange],
|
||||
data_handler: IDataHandler) -> Tuple[DataFrame, Optional[int]]:
|
||||
"""
|
||||
Load cached data to download more data.
|
||||
If timerange is passed in, checks whether data from an before the stored data will be
|
||||
downloaded.
|
||||
If that's the case then what's available should be completely overwritten.
|
||||
Otherwise downloads always start at the end of the available data to avoid data gaps.
|
||||
Note: Only used by download_pair_history().
|
||||
"""
|
||||
start = None
|
||||
if timerange:
|
||||
if timerange.starttype == 'date':
|
||||
# TODO: convert to date for conversion
|
||||
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||
|
||||
# Intentionally don't pass timerange in - since we need to load the full dataset.
|
||||
data = data_handler.ohlcv_load(pair, timeframe=timeframe,
|
||||
timerange=None, fill_missing=False,
|
||||
drop_incomplete=True, warn_no_data=False)
|
||||
if not data.empty:
|
||||
if start and start < data.iloc[0]['date']:
|
||||
# Earlier data than existing data requested, redownload all
|
||||
data = DataFrame(columns=DEFAULT_DATAFRAME_COLUMNS)
|
||||
else:
|
||||
start = data.iloc[-1]['date']
|
||||
|
||||
start_ms = int(start.timestamp() * 1000) if start else None
|
||||
return data, start_ms
|
||||
|
||||
|
||||
def _download_pair_history(datadir: Path,
|
||||
exchange: Exchange,
|
||||
pair: str, *,
|
||||
timeframe: str = '5m',
|
||||
timerange: Optional[TimeRange] = None,
|
||||
data_handler: IDataHandler = None) -> bool:
|
||||
"""
|
||||
Download latest candles from the exchange for the pair and timeframe passed in parameters
|
||||
The data is downloaded starting from the last correct data that
|
||||
exists in a cache. If timerange starts earlier than the data in the cache,
|
||||
the full data will be redownloaded
|
||||
|
||||
Based on @Rybolov work: https://github.com/rybolov/freqtrade-data
|
||||
|
||||
:param pair: pair to download
|
||||
:param timeframe: Ticker Timeframe (e.g 5m)
|
||||
:param timerange: range of time to download
|
||||
:return: bool with success state
|
||||
"""
|
||||
data_handler = get_datahandler(datadir, data_handler=data_handler)
|
||||
|
||||
try:
|
||||
logger.info(
|
||||
f'Download history data for pair: "{pair}", timeframe: {timeframe} '
|
||||
f'and store in {datadir}.'
|
||||
)
|
||||
|
||||
# data, since_ms = _load_cached_data_for_updating_old(datadir, pair, timeframe, timerange)
|
||||
data, since_ms = _load_cached_data_for_updating(pair, timeframe, timerange,
|
||||
data_handler=data_handler)
|
||||
|
||||
logger.debug("Current Start: %s",
|
||||
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
logger.debug("Current End: %s",
|
||||
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
|
||||
# Default since_ms to 30 days if nothing is given
|
||||
new_data = exchange.get_historic_ohlcv(pair=pair,
|
||||
timeframe=timeframe,
|
||||
since_ms=since_ms if since_ms else
|
||||
int(arrow.utcnow().shift(
|
||||
days=-30).float_timestamp) * 1000
|
||||
)
|
||||
# TODO: Maybe move parsing to exchange class (?)
|
||||
new_dataframe = parse_ticker_dataframe(new_data, timeframe, pair,
|
||||
fill_missing=False, drop_incomplete=True)
|
||||
if data.empty:
|
||||
data = new_dataframe
|
||||
else:
|
||||
data = data.append(new_dataframe)
|
||||
|
||||
logger.debug("New Start: %s",
|
||||
f"{data.iloc[0]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
logger.debug("New End: %s",
|
||||
f"{data.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}" if not data.empty else 'None')
|
||||
|
||||
data_handler.ohlcv_store(pair, timeframe, data=data)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f'Failed to download history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||
f'Error: {e}'
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes: List[str],
|
||||
datadir: Path, timerange: Optional[TimeRange] = None,
|
||||
erase: bool = False, data_format: str = None) -> List[str]:
|
||||
"""
|
||||
Refresh stored ohlcv data for backtesting and hyperopt operations.
|
||||
Used by freqtrade download-data subcommand.
|
||||
:return: List of pairs that are not available.
|
||||
"""
|
||||
pairs_not_available = []
|
||||
data_handler = get_datahandler(datadir, data_format)
|
||||
for pair in pairs:
|
||||
if pair not in exchange.markets:
|
||||
pairs_not_available.append(pair)
|
||||
logger.info(f"Skipping pair {pair}...")
|
||||
continue
|
||||
for timeframe in timeframes:
|
||||
|
||||
if erase:
|
||||
if data_handler.ohlcv_purge(pair, timeframe):
|
||||
logger.info(
|
||||
f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||
|
||||
logger.info(f'Downloading pair {pair}, interval {timeframe}.')
|
||||
_download_pair_history(datadir=datadir, exchange=exchange,
|
||||
pair=pair, timeframe=str(timeframe),
|
||||
timerange=timerange, data_handler=data_handler)
|
||||
return pairs_not_available
|
||||
|
||||
|
||||
def _download_trades_history(exchange: Exchange,
|
||||
pair: str, *,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
data_handler: IDataHandler
|
||||
) -> bool:
|
||||
"""
|
||||
Download trade history from the exchange.
|
||||
Appends to previously downloaded trades data.
|
||||
"""
|
||||
try:
|
||||
|
||||
since = timerange.startts * 1000 if timerange and timerange.starttype == 'date' else None
|
||||
|
||||
trades = data_handler.trades_load(pair)
|
||||
|
||||
from_id = trades[-1]['id'] if trades else None
|
||||
|
||||
logger.debug("Current Start: %s", trades[0]['datetime'] if trades else 'None')
|
||||
logger.debug("Current End: %s", trades[-1]['datetime'] if trades else 'None')
|
||||
|
||||
# Default since_ms to 30 days if nothing is given
|
||||
new_trades = exchange.get_historic_trades(pair=pair,
|
||||
since=since if since else
|
||||
int(arrow.utcnow().shift(
|
||||
days=-30).float_timestamp) * 1000,
|
||||
from_id=from_id,
|
||||
)
|
||||
trades.extend(new_trades[1])
|
||||
data_handler.trades_store(pair, data=trades)
|
||||
|
||||
logger.debug("New Start: %s", trades[0]['datetime'])
|
||||
logger.debug("New End: %s", trades[-1]['datetime'])
|
||||
logger.info(f"New Amount of trades: {len(trades)}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f'Failed to download historic trades for pair: "{pair}". '
|
||||
f'Error: {e}'
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def refresh_backtest_trades_data(exchange: Exchange, pairs: List[str], datadir: Path,
|
||||
timerange: TimeRange, erase: bool = False,
|
||||
data_format: str = 'jsongz') -> List[str]:
|
||||
"""
|
||||
Refresh stored trades data for backtesting and hyperopt operations.
|
||||
Used by freqtrade download-data subcommand.
|
||||
:return: List of pairs that are not available.
|
||||
"""
|
||||
pairs_not_available = []
|
||||
data_handler = get_datahandler(datadir, data_format=data_format)
|
||||
for pair in pairs:
|
||||
if pair not in exchange.markets:
|
||||
pairs_not_available.append(pair)
|
||||
logger.info(f"Skipping pair {pair}...")
|
||||
continue
|
||||
|
||||
if erase:
|
||||
if data_handler.trades_purge(pair):
|
||||
logger.info(f'Deleting existing data for pair {pair}.')
|
||||
|
||||
logger.info(f'Downloading trades for pair {pair}.')
|
||||
_download_trades_history(exchange=exchange,
|
||||
pair=pair,
|
||||
timerange=timerange,
|
||||
data_handler=data_handler)
|
||||
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 = 'json',
|
||||
data_format_trades: str = 'jsongz') -> 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):
|
||||
logger.info(f'Deleting existing data for pair {pair}, interval {timeframe}.')
|
||||
ohlcv = trades_to_ohlcv(trades, timeframe)
|
||||
# Store ohlcv
|
||||
data_handler_ohlcv.ohlcv_store(pair, timeframe, data=ohlcv)
|
||||
|
||||
|
||||
def get_timerange(data: Dict[str, DataFrame]) -> Tuple[arrow.Arrow, arrow.Arrow]:
|
||||
"""
|
||||
Get the maximum common timerange for the given backtest data.
|
||||
|
||||
:param data: dictionary with preprocessed backtesting data
|
||||
:return: tuple containing min_date, max_date
|
||||
"""
|
||||
timeranges = [
|
||||
(arrow.get(frame['date'].min()), arrow.get(frame['date'].max()))
|
||||
for frame in data.values()
|
||||
]
|
||||
return (min(timeranges, key=operator.itemgetter(0))[0],
|
||||
max(timeranges, key=operator.itemgetter(1))[1])
|
||||
|
||||
|
||||
def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime,
|
||||
max_date: datetime, timeframe_min: int) -> bool:
|
||||
"""
|
||||
Validates preprocessed backtesting data for missing values and shows warnings about it that.
|
||||
|
||||
:param data: preprocessed backtesting data (as DataFrame)
|
||||
:param pair: pair used for log output.
|
||||
:param min_date: start-date of the data
|
||||
:param max_date: end-date of the data
|
||||
:param timeframe_min: ticker Timeframe in minutes
|
||||
"""
|
||||
# total difference in minutes / timeframe-minutes
|
||||
expected_frames = int((max_date - min_date).total_seconds() // 60 // timeframe_min)
|
||||
found_missing = False
|
||||
dflen = len(data)
|
||||
if dflen < expected_frames:
|
||||
found_missing = True
|
||||
logger.warning("%s has missing frames: expected %s, got %s, that's %s missing values",
|
||||
pair, expected_frames, dflen, expected_frames - dflen)
|
||||
return found_missing
|
220
freqtrade/data/history/idatahandler.py
Normal file
220
freqtrade/data/history/idatahandler.py
Normal file
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
Abstract datahandler interface.
|
||||
It's subclasses handle and storing data from disk.
|
||||
|
||||
"""
|
||||
import logging
|
||||
from abc import ABC, abstractclassmethod, abstractmethod
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Type
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.data.converter import clean_ohlcv_dataframe, trim_dataframe
|
||||
from freqtrade.exchange import timeframe_to_seconds
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IDataHandler(ABC):
|
||||
|
||||
def __init__(self, datadir: Path) -> None:
|
||||
self._datadir = datadir
|
||||
|
||||
@abstractclassmethod
|
||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
for the specified timeframe
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param timeframe: Timeframe to search pairs for
|
||||
:return: List of Pairs
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def ohlcv_store(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
||||
"""
|
||||
Store data in json format "values".
|
||||
format looks as follows:
|
||||
[[<date>,<open>,<high>,<low>,<close>]]
|
||||
:param pair: Pair - used to generate filename
|
||||
:timeframe: Timeframe - used to generate filename
|
||||
:data: Dataframe containing OHLCV data
|
||||
:return: None
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Internal method used to load data for one pair from disk.
|
||||
Implements the loading and conversion to a Pandas dataframe.
|
||||
Timerange trimming and dataframe validation happens outside of this method.
|
||||
:param pair: Pair to load data
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:param timerange: Limit data to be loaded to this timerange.
|
||||
Optionally implemented by subclasses to avoid loading
|
||||
all data where possible.
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def ohlcv_purge(self, pair: str, timeframe: str) -> bool:
|
||||
"""
|
||||
Remove data for this pair
|
||||
:param pair: Delete data for this pair.
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:return: True when deleted, false if file did not exist.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def ohlcv_append(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
||||
"""
|
||||
Append data to existing data structures
|
||||
:param pair: Pair
|
||||
:param timeframe: Timeframe this ohlcv data is for
|
||||
:param data: Data to append.
|
||||
"""
|
||||
|
||||
@abstractclassmethod
|
||||
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs for which trade data is available in this
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:return: List of Pairs
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def trades_store(self, pair: str, data: List[Dict]) -> None:
|
||||
"""
|
||||
Store trades data (list of Dicts) to file
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Dicts containing trade data
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def trades_append(self, pair: str, data: List[Dict]):
|
||||
"""
|
||||
Append data to existing files
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Dicts containing trade data
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> List[Dict]:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
:param pair: Load trades for this pair
|
||||
:param timerange: Timerange to load trades for - currently not implemented
|
||||
:return: List of trades
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def trades_purge(self, pair: str) -> bool:
|
||||
"""
|
||||
Remove data for this pair
|
||||
:param pair: Delete data for this pair.
|
||||
:return: True when deleted, false if file did not exist.
|
||||
"""
|
||||
|
||||
def ohlcv_load(self, pair, timeframe: str,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
fill_missing: bool = True,
|
||||
drop_incomplete: bool = True,
|
||||
startup_candles: int = 0,
|
||||
warn_no_data: bool = True
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Load cached ticker history for the given pair.
|
||||
|
||||
:param pair: Pair to load data for
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:param timerange: Limit data to be loaded to this timerange
|
||||
:param fill_missing: Fill missing values with "No action"-candles
|
||||
:param drop_incomplete: Drop last candle assuming it may be incomplete.
|
||||
:param startup_candles: Additional candles to load at the start of the period
|
||||
:param warn_no_data: Log a warning message when no data is found
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
# Fix startup period
|
||||
timerange_startup = deepcopy(timerange)
|
||||
if startup_candles > 0 and timerange_startup:
|
||||
timerange_startup.subtract_start(timeframe_to_seconds(timeframe) * startup_candles)
|
||||
|
||||
pairdf = self._ohlcv_load(pair, timeframe,
|
||||
timerange=timerange_startup)
|
||||
if pairdf.empty:
|
||||
if warn_no_data:
|
||||
logger.warning(
|
||||
f'No history data for pair: "{pair}", timeframe: {timeframe}. '
|
||||
'Use `freqtrade download-data` to download the data'
|
||||
)
|
||||
return pairdf
|
||||
else:
|
||||
enddate = pairdf.iloc[-1]['date']
|
||||
|
||||
if timerange_startup:
|
||||
self._validate_pairdata(pair, pairdf, timerange_startup)
|
||||
pairdf = trim_dataframe(pairdf, timerange_startup)
|
||||
|
||||
# incomplete candles should only be dropped if we didn't trim the end beforehand.
|
||||
return clean_ohlcv_dataframe(pairdf, timeframe,
|
||||
pair=pair,
|
||||
fill_missing=fill_missing,
|
||||
drop_incomplete=(drop_incomplete and
|
||||
enddate == pairdf.iloc[-1]['date']))
|
||||
|
||||
def _validate_pairdata(self, pair, pairdata: DataFrame, timerange: TimeRange):
|
||||
"""
|
||||
Validates pairdata for missing data at start end end and logs warnings.
|
||||
:param pairdata: Dataframe to validate
|
||||
:param timerange: Timerange specified for start and end dates
|
||||
"""
|
||||
|
||||
if timerange.starttype == 'date':
|
||||
start = datetime.fromtimestamp(timerange.startts, tz=timezone.utc)
|
||||
if pairdata.iloc[0]['date'] > start:
|
||||
logger.warning(f"Missing data at start for pair {pair}, "
|
||||
f"data starts at {pairdata.iloc[0]['date']:%Y-%m-%d %H:%M:%S}")
|
||||
if timerange.stoptype == 'date':
|
||||
stop = datetime.fromtimestamp(timerange.stopts, tz=timezone.utc)
|
||||
if pairdata.iloc[-1]['date'] < stop:
|
||||
logger.warning(f"Missing data at end for pair {pair}, "
|
||||
f"data ends at {pairdata.iloc[-1]['date']:%Y-%m-%d %H:%M:%S}")
|
||||
|
||||
|
||||
def get_datahandlerclass(datatype: str) -> Type[IDataHandler]:
|
||||
"""
|
||||
Get datahandler class.
|
||||
Could be done using Resolvers, but since this may be called often and resolvers
|
||||
are rather expensive, doing this directly should improve performance.
|
||||
:param datatype: datatype to use.
|
||||
:return: Datahandler class
|
||||
"""
|
||||
|
||||
if datatype == 'json':
|
||||
from .jsondatahandler import JsonDataHandler
|
||||
return JsonDataHandler
|
||||
elif datatype == 'jsongz':
|
||||
from .jsondatahandler import JsonGzDataHandler
|
||||
return JsonGzDataHandler
|
||||
else:
|
||||
raise ValueError(f"No datahandler for datatype {datatype} available.")
|
||||
|
||||
|
||||
def get_datahandler(datadir: Path, data_format: str = None,
|
||||
data_handler: IDataHandler = None) -> IDataHandler:
|
||||
"""
|
||||
:param datadir: Folder to save data
|
||||
:data_format: dataformat to use
|
||||
:data_handler: returns this datahandler if it exists or initializes a new one
|
||||
"""
|
||||
|
||||
if not data_handler:
|
||||
HandlerClass = get_datahandlerclass(data_format or 'json')
|
||||
data_handler = HandlerClass(datadir)
|
||||
return data_handler
|
179
freqtrade/data/history/jsondatahandler.py
Normal file
179
freqtrade/data/history/jsondatahandler.py
Normal file
@@ -0,0 +1,179 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import numpy as np
|
||||
from pandas import DataFrame, read_json, to_datetime
|
||||
|
||||
from freqtrade import misc
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
from .idatahandler import IDataHandler
|
||||
|
||||
|
||||
class JsonDataHandler(IDataHandler):
|
||||
|
||||
_use_zip = False
|
||||
_columns = DEFAULT_DATAFRAME_COLUMNS
|
||||
|
||||
@classmethod
|
||||
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs with ohlcv data available in this datadir
|
||||
for the specified timeframe
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:param timeframe: Timeframe to search pairs for
|
||||
:return: List of Pairs
|
||||
"""
|
||||
|
||||
_tmp = [re.search(r'^(\S+)(?=\-' + timeframe + '.json)', p.name)
|
||||
for p in datadir.glob(f"*{timeframe}.{cls._get_file_extension()}")]
|
||||
# Check if regex found something and only return these results
|
||||
return [match[0].replace('_', '/') for match in _tmp if match]
|
||||
|
||||
def ohlcv_store(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
||||
"""
|
||||
Store data in json format "values".
|
||||
format looks as follows:
|
||||
[[<date>,<open>,<high>,<low>,<close>]]
|
||||
:param pair: Pair - used to generate filename
|
||||
:timeframe: Timeframe - used to generate filename
|
||||
:data: Dataframe containing OHLCV data
|
||||
:return: None
|
||||
"""
|
||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
||||
_data = data.copy()
|
||||
# Convert date to int
|
||||
_data['date'] = _data['date'].astype(np.int64) // 1000 // 1000
|
||||
|
||||
# Reset index, select only appropriate columns and save as json
|
||||
_data.reset_index(drop=True).loc[:, self._columns].to_json(
|
||||
filename, orient="values",
|
||||
compression='gzip' if self._use_zip else None)
|
||||
|
||||
def _ohlcv_load(self, pair: str, timeframe: str,
|
||||
timerange: Optional[TimeRange] = None,
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Internal method used to load data for one pair from disk.
|
||||
Implements the loading and conversion to a Pandas dataframe.
|
||||
Timerange trimming and dataframe validation happens outside of this method.
|
||||
:param pair: Pair to load data
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:param timerange: Limit data to be loaded to this timerange.
|
||||
Optionally implemented by subclasses to avoid loading
|
||||
all data where possible.
|
||||
:return: DataFrame with ohlcv data, or empty DataFrame
|
||||
"""
|
||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
||||
if not filename.exists():
|
||||
return DataFrame(columns=self._columns)
|
||||
pairdata = read_json(filename, orient='values')
|
||||
pairdata.columns = self._columns
|
||||
pairdata = pairdata.astype(dtype={'open': 'float', 'high': 'float',
|
||||
'low': 'float', 'close': 'float', 'volume': 'float'})
|
||||
pairdata['date'] = to_datetime(pairdata['date'],
|
||||
unit='ms',
|
||||
utc=True,
|
||||
infer_datetime_format=True)
|
||||
return pairdata
|
||||
|
||||
def ohlcv_purge(self, pair: str, timeframe: str) -> bool:
|
||||
"""
|
||||
Remove data for this pair
|
||||
:param pair: Delete data for this pair.
|
||||
:param timeframe: Ticker timeframe (e.g. "5m")
|
||||
:return: True when deleted, false if file did not exist.
|
||||
"""
|
||||
filename = self._pair_data_filename(self._datadir, pair, timeframe)
|
||||
if filename.exists():
|
||||
filename.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
def ohlcv_append(self, pair: str, timeframe: str, data: DataFrame) -> None:
|
||||
"""
|
||||
Append data to existing data structures
|
||||
:param pair: Pair
|
||||
:param timeframe: Timeframe this ohlcv data is for
|
||||
:param data: Data to append.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def trades_get_pairs(cls, datadir: Path) -> List[str]:
|
||||
"""
|
||||
Returns a list of all pairs for which trade data is available in this
|
||||
:param datadir: Directory to search for ohlcv files
|
||||
:return: List of Pairs
|
||||
"""
|
||||
_tmp = [re.search(r'^(\S+)(?=\-trades.json)', p.name)
|
||||
for p in datadir.glob(f"*trades.{cls._get_file_extension()}")]
|
||||
# Check if regex found something and only return these results to avoid exceptions.
|
||||
return [match[0].replace('_', '/') for match in _tmp if match]
|
||||
|
||||
def trades_store(self, pair: str, data: List[Dict]) -> None:
|
||||
"""
|
||||
Store trades data (list of Dicts) to file
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Dicts containing trade data
|
||||
"""
|
||||
filename = self._pair_trades_filename(self._datadir, pair)
|
||||
misc.file_dump_json(filename, data, is_zip=self._use_zip)
|
||||
|
||||
def trades_append(self, pair: str, data: List[Dict]):
|
||||
"""
|
||||
Append data to existing files
|
||||
:param pair: Pair - used for filename
|
||||
:param data: List of Dicts containing trade data
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def trades_load(self, pair: str, timerange: Optional[TimeRange] = None) -> List[Dict]:
|
||||
"""
|
||||
Load a pair from file, either .json.gz or .json
|
||||
# TODO: respect timerange ...
|
||||
:param pair: Load trades for this pair
|
||||
:param timerange: Timerange to load trades for - currently not implemented
|
||||
:return: List of trades
|
||||
"""
|
||||
filename = self._pair_trades_filename(self._datadir, pair)
|
||||
tradesdata = misc.file_load_json(filename)
|
||||
if not tradesdata:
|
||||
return []
|
||||
|
||||
return tradesdata
|
||||
|
||||
def trades_purge(self, pair: str) -> bool:
|
||||
"""
|
||||
Remove data for this pair
|
||||
:param pair: Delete data for this pair.
|
||||
:return: True when deleted, false if file did not exist.
|
||||
"""
|
||||
filename = self._pair_trades_filename(self._datadir, pair)
|
||||
if filename.exists():
|
||||
filename.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _pair_data_filename(cls, datadir: Path, pair: str, timeframe: str) -> Path:
|
||||
pair_s = misc.pair_to_filename(pair)
|
||||
filename = datadir.joinpath(f'{pair_s}-{timeframe}.{cls._get_file_extension()}')
|
||||
return filename
|
||||
|
||||
@classmethod
|
||||
def _get_file_extension(cls):
|
||||
return "json.gz" if cls._use_zip else "json"
|
||||
|
||||
@classmethod
|
||||
def _pair_trades_filename(cls, datadir: Path, pair: str) -> Path:
|
||||
pair_s = misc.pair_to_filename(pair)
|
||||
filename = datadir.joinpath(f'{pair_s}-trades.{cls._get_file_extension()}')
|
||||
return filename
|
||||
|
||||
|
||||
class JsonGzDataHandler(JsonDataHandler):
|
||||
|
||||
_use_zip = True
|
@@ -1,456 +1 @@
|
||||
# pragma pylint: disable=W0603
|
||||
""" Edge positioning package """
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, NamedTuple
|
||||
|
||||
import arrow
|
||||
import numpy as np
|
||||
import utils_find_1st as utf1st
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import constants, OperationalException
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.strategy.interface import SellType
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PairInfo(NamedTuple):
|
||||
stoploss: float
|
||||
winrate: float
|
||||
risk_reward_ratio: float
|
||||
required_risk_reward: float
|
||||
expectancy: float
|
||||
nb_trades: int
|
||||
avg_trade_duration: float
|
||||
|
||||
|
||||
class Edge:
|
||||
"""
|
||||
Calculates Win Rate, Risk Reward Ratio, Expectancy
|
||||
against historical data for a give set of markets and a strategy
|
||||
it then adjusts stoploss and position size accordingly
|
||||
and force it into the strategy
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
config: Dict = {}
|
||||
_cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||
|
||||
def __init__(self, config: Dict[str, Any], exchange, strategy) -> None:
|
||||
|
||||
self.config = config
|
||||
self.exchange = exchange
|
||||
self.strategy = strategy
|
||||
|
||||
self.edge_config = self.config.get('edge', {})
|
||||
self._cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||
self._final_pairs: list = []
|
||||
|
||||
# checking max_open_trades. it should be -1 as with Edge
|
||||
# the number of trades is determined by position size
|
||||
if self.config['max_open_trades'] != float('inf'):
|
||||
logger.critical('max_open_trades should be -1 in config !')
|
||||
|
||||
if self.config['stake_amount'] != constants.UNLIMITED_STAKE_AMOUNT:
|
||||
raise OperationalException('Edge works only with unlimited stake amount')
|
||||
|
||||
self._capital_percentage: float = self.edge_config.get('capital_available_percentage')
|
||||
self._allowed_risk: float = self.edge_config.get('allowed_risk')
|
||||
self._since_number_of_days: int = self.edge_config.get('calculate_since_number_of_days', 14)
|
||||
self._last_updated: int = 0 # Timestamp of pairs last updated time
|
||||
self._refresh_pairs = True
|
||||
|
||||
self._stoploss_range_min = float(self.edge_config.get('stoploss_range_min', -0.01))
|
||||
self._stoploss_range_max = float(self.edge_config.get('stoploss_range_max', -0.05))
|
||||
self._stoploss_range_step = float(self.edge_config.get('stoploss_range_step', -0.001))
|
||||
|
||||
# calculating stoploss range
|
||||
self._stoploss_range = np.arange(
|
||||
self._stoploss_range_min,
|
||||
self._stoploss_range_max,
|
||||
self._stoploss_range_step
|
||||
)
|
||||
|
||||
self._timerange: TimeRange = TimeRange.parse_timerange("%s-" % arrow.now().shift(
|
||||
days=-1 * self._since_number_of_days).format('YYYYMMDD'))
|
||||
if config.get('fee'):
|
||||
self.fee = config['fee']
|
||||
else:
|
||||
self.fee = self.exchange.get_fee()
|
||||
|
||||
def calculate(self) -> bool:
|
||||
pairs = self.config['exchange']['pair_whitelist']
|
||||
heartbeat = self.edge_config.get('process_throttle_secs')
|
||||
|
||||
if (self._last_updated > 0) and (
|
||||
self._last_updated + heartbeat > arrow.utcnow().timestamp):
|
||||
return False
|
||||
|
||||
data: Dict[str, Any] = {}
|
||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
||||
|
||||
data = history.load_data(
|
||||
datadir=Path(self.config['datadir']),
|
||||
pairs=pairs,
|
||||
timeframe=self.strategy.ticker_interval,
|
||||
refresh_pairs=self._refresh_pairs,
|
||||
exchange=self.exchange,
|
||||
timerange=self._timerange,
|
||||
startup_candles=self.strategy.startup_candle_count,
|
||||
)
|
||||
|
||||
if not data:
|
||||
# Reinitializing cached pairs
|
||||
self._cached_pairs = {}
|
||||
logger.critical("No data found. Edge is stopped ...")
|
||||
return False
|
||||
|
||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||
|
||||
# Print timeframe
|
||||
min_date, max_date = history.get_timeframe(preprocessed)
|
||||
logger.info(
|
||||
'Measuring data from %s up to %s (%s days) ...',
|
||||
min_date.isoformat(),
|
||||
max_date.isoformat(),
|
||||
(max_date - min_date).days
|
||||
)
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'high', 'low']
|
||||
|
||||
trades: list = []
|
||||
for pair, pair_data in preprocessed.items():
|
||||
# Sorting dataframe by date and reset index
|
||||
pair_data = pair_data.sort_values(by=['date'])
|
||||
pair_data = pair_data.reset_index(drop=True)
|
||||
|
||||
ticker_data = self.strategy.advise_sell(
|
||||
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||
|
||||
trades += self._find_trades_for_stoploss_range(ticker_data, pair, self._stoploss_range)
|
||||
|
||||
# If no trade found then exit
|
||||
if len(trades) == 0:
|
||||
logger.info("No trades found.")
|
||||
return False
|
||||
|
||||
# Fill missing, calculable columns, profit, duration , abs etc.
|
||||
trades_df = self._fill_calculable_fields(DataFrame(trades))
|
||||
self._cached_pairs = self._process_expectancy(trades_df)
|
||||
self._last_updated = arrow.utcnow().timestamp
|
||||
|
||||
return True
|
||||
|
||||
def stake_amount(self, pair: str, free_capital: float,
|
||||
total_capital: float, capital_in_trade: float) -> float:
|
||||
stoploss = self.stoploss(pair)
|
||||
available_capital = (total_capital + capital_in_trade) * self._capital_percentage
|
||||
allowed_capital_at_risk = available_capital * self._allowed_risk
|
||||
max_position_size = abs(allowed_capital_at_risk / stoploss)
|
||||
position_size = min(max_position_size, free_capital)
|
||||
if pair in self._cached_pairs:
|
||||
logger.info(
|
||||
'winrate: %s, expectancy: %s, position size: %s, pair: %s,'
|
||||
' capital in trade: %s, free capital: %s, total capital: %s,'
|
||||
' stoploss: %s, available capital: %s.',
|
||||
self._cached_pairs[pair].winrate,
|
||||
self._cached_pairs[pair].expectancy,
|
||||
position_size, pair,
|
||||
capital_in_trade, free_capital, total_capital,
|
||||
stoploss, available_capital
|
||||
)
|
||||
return round(position_size, 15)
|
||||
|
||||
def stoploss(self, pair: str) -> float:
|
||||
if pair in self._cached_pairs:
|
||||
return self._cached_pairs[pair].stoploss
|
||||
else:
|
||||
logger.warning('tried to access stoploss of a non-existing pair, '
|
||||
'strategy stoploss is returned instead.')
|
||||
return self.strategy.stoploss
|
||||
|
||||
def adjust(self, pairs) -> list:
|
||||
"""
|
||||
Filters out and sorts "pairs" according to Edge calculated pairs
|
||||
"""
|
||||
final = []
|
||||
for pair, info in self._cached_pairs.items():
|
||||
if info.expectancy > float(self.edge_config.get('minimum_expectancy', 0.2)) and \
|
||||
info.winrate > float(self.edge_config.get('minimum_winrate', 0.60)) and \
|
||||
pair in pairs:
|
||||
final.append(pair)
|
||||
|
||||
if self._final_pairs != final:
|
||||
self._final_pairs = final
|
||||
if self._final_pairs:
|
||||
logger.info(
|
||||
'Minimum expectancy and minimum winrate are met only for %s,'
|
||||
' so other pairs are filtered out.',
|
||||
self._final_pairs
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
'Edge removed all pairs as no pair with minimum expectancy '
|
||||
'and minimum winrate was found !'
|
||||
)
|
||||
|
||||
return self._final_pairs
|
||||
|
||||
def accepted_pairs(self) -> list:
|
||||
"""
|
||||
return a list of accepted pairs along with their winrate, expectancy and stoploss
|
||||
"""
|
||||
final = []
|
||||
for pair, info in self._cached_pairs.items():
|
||||
if info.expectancy > float(self.edge_config.get('minimum_expectancy', 0.2)) and \
|
||||
info.winrate > float(self.edge_config.get('minimum_winrate', 0.60)):
|
||||
final.append({
|
||||
'Pair': pair,
|
||||
'Winrate': info.winrate,
|
||||
'Expectancy': info.expectancy,
|
||||
'Stoploss': info.stoploss,
|
||||
})
|
||||
return final
|
||||
|
||||
def _fill_calculable_fields(self, result: DataFrame) -> DataFrame:
|
||||
"""
|
||||
The result frame contains a number of columns that are calculable
|
||||
from other columns. These are left blank till all rows are added,
|
||||
to be populated in single vector calls.
|
||||
|
||||
Columns to be populated are:
|
||||
- Profit
|
||||
- trade duration
|
||||
- profit abs
|
||||
:param result Dataframe
|
||||
:return: result Dataframe
|
||||
"""
|
||||
|
||||
# stake and fees
|
||||
# stake = 0.015
|
||||
# 0.05% is 0.0005
|
||||
# fee = 0.001
|
||||
|
||||
# we set stake amount to an arbitrary amount.
|
||||
# as it doesn't change the calculation.
|
||||
# all returned values are relative. they are percentages.
|
||||
stake = 0.015
|
||||
fee = self.fee
|
||||
open_fee = fee / 2
|
||||
close_fee = fee / 2
|
||||
|
||||
result['trade_duration'] = result['close_time'] - result['open_time']
|
||||
|
||||
result['trade_duration'] = result['trade_duration'].map(
|
||||
lambda x: int(x.total_seconds() / 60))
|
||||
|
||||
# Spends, Takes, Profit, Absolute Profit
|
||||
|
||||
# Buy Price
|
||||
result['buy_vol'] = stake / result['open_rate'] # How many target are we buying
|
||||
result['buy_fee'] = stake * open_fee
|
||||
result['buy_spend'] = stake + result['buy_fee'] # How much we're spending
|
||||
|
||||
# Sell price
|
||||
result['sell_sum'] = result['buy_vol'] * result['close_rate']
|
||||
result['sell_fee'] = result['sell_sum'] * close_fee
|
||||
result['sell_take'] = result['sell_sum'] - result['sell_fee']
|
||||
|
||||
# profit_percent
|
||||
result['profit_percent'] = (result['sell_take'] - result['buy_spend']) / result['buy_spend']
|
||||
|
||||
# Absolute profit
|
||||
result['profit_abs'] = result['sell_take'] - result['buy_spend']
|
||||
|
||||
return result
|
||||
|
||||
def _process_expectancy(self, results: DataFrame) -> Dict[str, Any]:
|
||||
"""
|
||||
This calculates WinRate, Required Risk Reward, Risk Reward and Expectancy of all pairs
|
||||
The calulation will be done per pair and per strategy.
|
||||
"""
|
||||
# Removing pairs having less than min_trades_number
|
||||
min_trades_number = self.edge_config.get('min_trade_number', 10)
|
||||
results = results.groupby(['pair', 'stoploss']).filter(lambda x: len(x) > min_trades_number)
|
||||
###################################
|
||||
|
||||
# Removing outliers (Only Pumps) from the dataset
|
||||
# The method to detect outliers is to calculate standard deviation
|
||||
# Then every value more than (standard deviation + 2*average) is out (pump)
|
||||
#
|
||||
# Removing Pumps
|
||||
if self.edge_config.get('remove_pumps', False):
|
||||
results = results.groupby(['pair', 'stoploss']).apply(
|
||||
lambda x: x[x['profit_abs'] < 2 * x['profit_abs'].std() + x['profit_abs'].mean()])
|
||||
##########################################################################
|
||||
|
||||
# Removing trades having a duration more than X minutes (set in config)
|
||||
max_trade_duration = self.edge_config.get('max_trade_duration_minute', 1440)
|
||||
results = results[results.trade_duration < max_trade_duration]
|
||||
#######################################################################
|
||||
|
||||
if results.empty:
|
||||
return {}
|
||||
|
||||
groupby_aggregator = {
|
||||
'profit_abs': [
|
||||
('nb_trades', 'count'), # number of all trades
|
||||
('profit_sum', lambda x: x[x > 0].sum()), # cumulative profit of all winning trades
|
||||
('loss_sum', lambda x: abs(x[x < 0].sum())), # cumulative loss of all losing trades
|
||||
('nb_win_trades', lambda x: x[x > 0].count()) # number of winning trades
|
||||
],
|
||||
'trade_duration': [('avg_trade_duration', 'mean')]
|
||||
}
|
||||
|
||||
# Group by (pair and stoploss) by applying above aggregator
|
||||
df = results.groupby(['pair', 'stoploss'])['profit_abs', 'trade_duration'].agg(
|
||||
groupby_aggregator).reset_index(col_level=1)
|
||||
|
||||
# Dropping level 0 as we don't need it
|
||||
df.columns = df.columns.droplevel(0)
|
||||
|
||||
# Calculating number of losing trades, average win and average loss
|
||||
df['nb_loss_trades'] = df['nb_trades'] - df['nb_win_trades']
|
||||
df['average_win'] = df['profit_sum'] / df['nb_win_trades']
|
||||
df['average_loss'] = df['loss_sum'] / df['nb_loss_trades']
|
||||
|
||||
# Win rate = number of profitable trades / number of trades
|
||||
df['winrate'] = df['nb_win_trades'] / df['nb_trades']
|
||||
|
||||
# risk_reward_ratio = average win / average loss
|
||||
df['risk_reward_ratio'] = df['average_win'] / df['average_loss']
|
||||
|
||||
# required_risk_reward = (1 / winrate) - 1
|
||||
df['required_risk_reward'] = (1 / df['winrate']) - 1
|
||||
|
||||
# expectancy = (risk_reward_ratio * winrate) - (lossrate)
|
||||
df['expectancy'] = (df['risk_reward_ratio'] * df['winrate']) - (1 - df['winrate'])
|
||||
|
||||
# sort by expectancy and stoploss
|
||||
df = df.sort_values(by=['expectancy', 'stoploss'], ascending=False).groupby(
|
||||
'pair').first().sort_values(by=['expectancy'], ascending=False).reset_index()
|
||||
|
||||
final = {}
|
||||
for x in df.itertuples():
|
||||
final[x.pair] = PairInfo(
|
||||
x.stoploss,
|
||||
x.winrate,
|
||||
x.risk_reward_ratio,
|
||||
x.required_risk_reward,
|
||||
x.expectancy,
|
||||
x.nb_trades,
|
||||
x.avg_trade_duration
|
||||
)
|
||||
|
||||
# Returning a list of pairs in order of "expectancy"
|
||||
return final
|
||||
|
||||
def _find_trades_for_stoploss_range(self, ticker_data, pair, stoploss_range):
|
||||
buy_column = ticker_data['buy'].values
|
||||
sell_column = ticker_data['sell'].values
|
||||
date_column = ticker_data['date'].values
|
||||
ohlc_columns = ticker_data[['open', 'high', 'low', 'close']].values
|
||||
|
||||
result: list = []
|
||||
for stoploss in stoploss_range:
|
||||
result += self._detect_next_stop_or_sell_point(
|
||||
buy_column, sell_column, date_column, ohlc_columns, round(stoploss, 6), pair
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
||||
ohlc_columns, stoploss, pair):
|
||||
"""
|
||||
Iterate through ohlc_columns in order to find the next trade
|
||||
Next trade opens from the first buy signal noticed to
|
||||
The sell or stoploss signal after it.
|
||||
It then cuts OHLC, buy_column, sell_column and date_column.
|
||||
Cut from (the exit trade index) + 1.
|
||||
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
result: list = []
|
||||
start_point = 0
|
||||
|
||||
while True:
|
||||
open_trade_index = utf1st.find_1st(buy_column, 1, utf1st.cmp_equal)
|
||||
|
||||
# Return empty if we don't find trade entry (i.e. buy==1) or
|
||||
# we find a buy but at the end of array
|
||||
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
||||
break
|
||||
else:
|
||||
# When a buy signal is seen,
|
||||
# trade opens in reality on the next candle
|
||||
open_trade_index += 1
|
||||
|
||||
stop_price_percentage = stoploss + 1
|
||||
open_price = ohlc_columns[open_trade_index, 0]
|
||||
stop_price = (open_price * stop_price_percentage)
|
||||
|
||||
# Searching for the index where stoploss is hit
|
||||
stop_index = utf1st.find_1st(
|
||||
ohlc_columns[open_trade_index:, 2], stop_price, utf1st.cmp_smaller)
|
||||
|
||||
# If we don't find it then we assume stop_index will be far in future (infinite number)
|
||||
if stop_index == -1:
|
||||
stop_index = float('inf')
|
||||
|
||||
# Searching for the index where sell is hit
|
||||
sell_index = utf1st.find_1st(sell_column[open_trade_index:], 1, utf1st.cmp_equal)
|
||||
|
||||
# If we don't find it then we assume sell_index will be far in future (infinite number)
|
||||
if sell_index == -1:
|
||||
sell_index = float('inf')
|
||||
|
||||
# Check if we don't find any stop or sell point (in that case trade remains open)
|
||||
# It is not interesting for Edge to consider it so we simply ignore the trade
|
||||
# And stop iterating there is no more entry
|
||||
if stop_index == sell_index == float('inf'):
|
||||
break
|
||||
|
||||
if stop_index <= sell_index:
|
||||
exit_index = open_trade_index + stop_index
|
||||
exit_type = SellType.STOP_LOSS
|
||||
exit_price = stop_price
|
||||
elif stop_index > sell_index:
|
||||
# If exit is SELL then we exit at the next candle
|
||||
exit_index = open_trade_index + sell_index + 1
|
||||
|
||||
# Check if we have the next candle
|
||||
if len(ohlc_columns) - 1 < exit_index:
|
||||
break
|
||||
|
||||
exit_type = SellType.SELL_SIGNAL
|
||||
exit_price = ohlc_columns[exit_index, 0]
|
||||
|
||||
trade = {'pair': pair,
|
||||
'stoploss': stoploss,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': date_column[open_trade_index],
|
||||
'close_time': date_column[exit_index],
|
||||
'open_index': start_point + open_trade_index,
|
||||
'close_index': start_point + exit_index,
|
||||
'trade_duration': '',
|
||||
'open_rate': round(open_price, 15),
|
||||
'close_rate': round(exit_price, 15),
|
||||
'exit_type': exit_type
|
||||
}
|
||||
|
||||
result.append(trade)
|
||||
|
||||
# Giving a view of exit_index till the end of array
|
||||
buy_column = buy_column[exit_index:]
|
||||
sell_column = sell_column[exit_index:]
|
||||
date_column = date_column[exit_index:]
|
||||
ohlc_columns = ohlc_columns[exit_index:]
|
||||
start_point += exit_index
|
||||
|
||||
return result
|
||||
from .edge_positioning import Edge, PairInfo # noqa: F401
|
||||
|
465
freqtrade/edge/edge_positioning.py
Normal file
465
freqtrade/edge/edge_positioning.py
Normal file
@@ -0,0 +1,465 @@
|
||||
# pragma pylint: disable=W0603
|
||||
""" Edge positioning package """
|
||||
import logging
|
||||
from typing import Any, Dict, List, NamedTuple
|
||||
|
||||
import arrow
|
||||
import numpy as np
|
||||
import utils_find_1st as utf1st
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.strategy.interface import SellType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PairInfo(NamedTuple):
|
||||
stoploss: float
|
||||
winrate: float
|
||||
risk_reward_ratio: float
|
||||
required_risk_reward: float
|
||||
expectancy: float
|
||||
nb_trades: int
|
||||
avg_trade_duration: float
|
||||
|
||||
|
||||
class Edge:
|
||||
"""
|
||||
Calculates Win Rate, Risk Reward Ratio, Expectancy
|
||||
against historical data for a give set of markets and a strategy
|
||||
it then adjusts stoploss and position size accordingly
|
||||
and force it into the strategy
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
config: Dict = {}
|
||||
_cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||
|
||||
def __init__(self, config: Dict[str, Any], exchange, strategy) -> None:
|
||||
|
||||
self.config = config
|
||||
self.exchange = exchange
|
||||
self.strategy = strategy
|
||||
|
||||
self.edge_config = self.config.get('edge', {})
|
||||
self._cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs
|
||||
self._final_pairs: list = []
|
||||
|
||||
# checking max_open_trades. it should be -1 as with Edge
|
||||
# the number of trades is determined by position size
|
||||
if self.config['max_open_trades'] != float('inf'):
|
||||
logger.critical('max_open_trades should be -1 in config !')
|
||||
|
||||
if self.config['stake_amount'] != constants.UNLIMITED_STAKE_AMOUNT:
|
||||
raise OperationalException('Edge works only with unlimited stake amount')
|
||||
|
||||
# Deprecated capital_available_percentage. Will use tradable_balance_ratio in the future.
|
||||
self._capital_percentage: float = self.edge_config.get(
|
||||
'capital_available_percentage', self.config['tradable_balance_ratio'])
|
||||
self._allowed_risk: float = self.edge_config.get('allowed_risk')
|
||||
self._since_number_of_days: int = self.edge_config.get('calculate_since_number_of_days', 14)
|
||||
self._last_updated: int = 0 # Timestamp of pairs last updated time
|
||||
self._refresh_pairs = True
|
||||
|
||||
self._stoploss_range_min = float(self.edge_config.get('stoploss_range_min', -0.01))
|
||||
self._stoploss_range_max = float(self.edge_config.get('stoploss_range_max', -0.05))
|
||||
self._stoploss_range_step = float(self.edge_config.get('stoploss_range_step', -0.001))
|
||||
|
||||
# calculating stoploss range
|
||||
self._stoploss_range = np.arange(
|
||||
self._stoploss_range_min,
|
||||
self._stoploss_range_max,
|
||||
self._stoploss_range_step
|
||||
)
|
||||
|
||||
self._timerange: TimeRange = TimeRange.parse_timerange("%s-" % arrow.now().shift(
|
||||
days=-1 * self._since_number_of_days).format('YYYYMMDD'))
|
||||
if config.get('fee'):
|
||||
self.fee = config['fee']
|
||||
else:
|
||||
self.fee = self.exchange.get_fee(symbol=self.config['exchange']['pair_whitelist'][0])
|
||||
|
||||
def calculate(self) -> bool:
|
||||
pairs = self.config['exchange']['pair_whitelist']
|
||||
heartbeat = self.edge_config.get('process_throttle_secs')
|
||||
|
||||
if (self._last_updated > 0) and (
|
||||
self._last_updated + heartbeat > arrow.utcnow().timestamp):
|
||||
return False
|
||||
|
||||
data: Dict[str, Any] = {}
|
||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||
logger.info('Using local backtesting data (using whitelist in given config) ...')
|
||||
|
||||
if self._refresh_pairs:
|
||||
history.refresh_data(
|
||||
datadir=self.config['datadir'],
|
||||
pairs=pairs,
|
||||
exchange=self.exchange,
|
||||
timeframe=self.strategy.ticker_interval,
|
||||
timerange=self._timerange,
|
||||
)
|
||||
|
||||
data = history.load_data(
|
||||
datadir=self.config['datadir'],
|
||||
pairs=pairs,
|
||||
timeframe=self.strategy.ticker_interval,
|
||||
timerange=self._timerange,
|
||||
startup_candles=self.strategy.startup_candle_count,
|
||||
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
||||
)
|
||||
|
||||
if not data:
|
||||
# Reinitializing cached pairs
|
||||
self._cached_pairs = {}
|
||||
logger.critical("No data found. Edge is stopped ...")
|
||||
return False
|
||||
|
||||
preprocessed = self.strategy.tickerdata_to_dataframe(data)
|
||||
|
||||
# Print timeframe
|
||||
min_date, max_date = history.get_timerange(preprocessed)
|
||||
logger.info(
|
||||
'Measuring data from %s up to %s (%s days) ...',
|
||||
min_date.isoformat(),
|
||||
max_date.isoformat(),
|
||||
(max_date - min_date).days
|
||||
)
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'high', 'low']
|
||||
|
||||
trades: list = []
|
||||
for pair, pair_data in preprocessed.items():
|
||||
# Sorting dataframe by date and reset index
|
||||
pair_data = pair_data.sort_values(by=['date'])
|
||||
pair_data = pair_data.reset_index(drop=True)
|
||||
|
||||
ticker_data = self.strategy.advise_sell(
|
||||
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||
|
||||
trades += self._find_trades_for_stoploss_range(ticker_data, pair, self._stoploss_range)
|
||||
|
||||
# If no trade found then exit
|
||||
if len(trades) == 0:
|
||||
logger.info("No trades found.")
|
||||
return False
|
||||
|
||||
# Fill missing, calculable columns, profit, duration , abs etc.
|
||||
trades_df = self._fill_calculable_fields(DataFrame(trades))
|
||||
self._cached_pairs = self._process_expectancy(trades_df)
|
||||
self._last_updated = arrow.utcnow().timestamp
|
||||
|
||||
return True
|
||||
|
||||
def stake_amount(self, pair: str, free_capital: float,
|
||||
total_capital: float, capital_in_trade: float) -> float:
|
||||
stoploss = self.stoploss(pair)
|
||||
available_capital = (total_capital + capital_in_trade) * self._capital_percentage
|
||||
allowed_capital_at_risk = available_capital * self._allowed_risk
|
||||
max_position_size = abs(allowed_capital_at_risk / stoploss)
|
||||
position_size = min(max_position_size, free_capital)
|
||||
if pair in self._cached_pairs:
|
||||
logger.info(
|
||||
'winrate: %s, expectancy: %s, position size: %s, pair: %s,'
|
||||
' capital in trade: %s, free capital: %s, total capital: %s,'
|
||||
' stoploss: %s, available capital: %s.',
|
||||
self._cached_pairs[pair].winrate,
|
||||
self._cached_pairs[pair].expectancy,
|
||||
position_size, pair,
|
||||
capital_in_trade, free_capital, total_capital,
|
||||
stoploss, available_capital
|
||||
)
|
||||
return round(position_size, 15)
|
||||
|
||||
def stoploss(self, pair: str) -> float:
|
||||
if pair in self._cached_pairs:
|
||||
return self._cached_pairs[pair].stoploss
|
||||
else:
|
||||
logger.warning('tried to access stoploss of a non-existing pair, '
|
||||
'strategy stoploss is returned instead.')
|
||||
return self.strategy.stoploss
|
||||
|
||||
def adjust(self, pairs: List[str]) -> list:
|
||||
"""
|
||||
Filters out and sorts "pairs" according to Edge calculated pairs
|
||||
"""
|
||||
final = []
|
||||
for pair, info in self._cached_pairs.items():
|
||||
if info.expectancy > float(self.edge_config.get('minimum_expectancy', 0.2)) and \
|
||||
info.winrate > float(self.edge_config.get('minimum_winrate', 0.60)) and \
|
||||
pair in pairs:
|
||||
final.append(pair)
|
||||
|
||||
if self._final_pairs != final:
|
||||
self._final_pairs = final
|
||||
if self._final_pairs:
|
||||
logger.info(
|
||||
'Minimum expectancy and minimum winrate are met only for %s,'
|
||||
' so other pairs are filtered out.',
|
||||
self._final_pairs
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
'Edge removed all pairs as no pair with minimum expectancy '
|
||||
'and minimum winrate was found !'
|
||||
)
|
||||
|
||||
return self._final_pairs
|
||||
|
||||
def accepted_pairs(self) -> list:
|
||||
"""
|
||||
return a list of accepted pairs along with their winrate, expectancy and stoploss
|
||||
"""
|
||||
final = []
|
||||
for pair, info in self._cached_pairs.items():
|
||||
if info.expectancy > float(self.edge_config.get('minimum_expectancy', 0.2)) and \
|
||||
info.winrate > float(self.edge_config.get('minimum_winrate', 0.60)):
|
||||
final.append({
|
||||
'Pair': pair,
|
||||
'Winrate': info.winrate,
|
||||
'Expectancy': info.expectancy,
|
||||
'Stoploss': info.stoploss,
|
||||
})
|
||||
return final
|
||||
|
||||
def _fill_calculable_fields(self, result: DataFrame) -> DataFrame:
|
||||
"""
|
||||
The result frame contains a number of columns that are calculable
|
||||
from other columns. These are left blank till all rows are added,
|
||||
to be populated in single vector calls.
|
||||
|
||||
Columns to be populated are:
|
||||
- Profit
|
||||
- trade duration
|
||||
- profit abs
|
||||
:param result Dataframe
|
||||
:return: result Dataframe
|
||||
"""
|
||||
|
||||
# stake and fees
|
||||
# stake = 0.015
|
||||
# 0.05% is 0.0005
|
||||
# fee = 0.001
|
||||
|
||||
# we set stake amount to an arbitrary amount.
|
||||
# as it doesn't change the calculation.
|
||||
# all returned values are relative. they are percentages.
|
||||
stake = 0.015
|
||||
fee = self.fee
|
||||
open_fee = fee / 2
|
||||
close_fee = fee / 2
|
||||
|
||||
result['trade_duration'] = result['close_time'] - result['open_time']
|
||||
|
||||
result['trade_duration'] = result['trade_duration'].map(
|
||||
lambda x: int(x.total_seconds() / 60))
|
||||
|
||||
# Spends, Takes, Profit, Absolute Profit
|
||||
|
||||
# Buy Price
|
||||
result['buy_vol'] = stake / result['open_rate'] # How many target are we buying
|
||||
result['buy_fee'] = stake * open_fee
|
||||
result['buy_spend'] = stake + result['buy_fee'] # How much we're spending
|
||||
|
||||
# Sell price
|
||||
result['sell_sum'] = result['buy_vol'] * result['close_rate']
|
||||
result['sell_fee'] = result['sell_sum'] * close_fee
|
||||
result['sell_take'] = result['sell_sum'] - result['sell_fee']
|
||||
|
||||
# profit_percent
|
||||
result['profit_percent'] = (result['sell_take'] - result['buy_spend']) / result['buy_spend']
|
||||
|
||||
# Absolute profit
|
||||
result['profit_abs'] = result['sell_take'] - result['buy_spend']
|
||||
|
||||
return result
|
||||
|
||||
def _process_expectancy(self, results: DataFrame) -> Dict[str, Any]:
|
||||
"""
|
||||
This calculates WinRate, Required Risk Reward, Risk Reward and Expectancy of all pairs
|
||||
The calulation will be done per pair and per strategy.
|
||||
"""
|
||||
# Removing pairs having less than min_trades_number
|
||||
min_trades_number = self.edge_config.get('min_trade_number', 10)
|
||||
results = results.groupby(['pair', 'stoploss']).filter(lambda x: len(x) > min_trades_number)
|
||||
###################################
|
||||
|
||||
# Removing outliers (Only Pumps) from the dataset
|
||||
# The method to detect outliers is to calculate standard deviation
|
||||
# Then every value more than (standard deviation + 2*average) is out (pump)
|
||||
#
|
||||
# Removing Pumps
|
||||
if self.edge_config.get('remove_pumps', False):
|
||||
results = results.groupby(['pair', 'stoploss']).apply(
|
||||
lambda x: x[x['profit_abs'] < 2 * x['profit_abs'].std() + x['profit_abs'].mean()])
|
||||
##########################################################################
|
||||
|
||||
# Removing trades having a duration more than X minutes (set in config)
|
||||
max_trade_duration = self.edge_config.get('max_trade_duration_minute', 1440)
|
||||
results = results[results.trade_duration < max_trade_duration]
|
||||
#######################################################################
|
||||
|
||||
if results.empty:
|
||||
return {}
|
||||
|
||||
groupby_aggregator = {
|
||||
'profit_abs': [
|
||||
('nb_trades', 'count'), # number of all trades
|
||||
('profit_sum', lambda x: x[x > 0].sum()), # cumulative profit of all winning trades
|
||||
('loss_sum', lambda x: abs(x[x < 0].sum())), # cumulative loss of all losing trades
|
||||
('nb_win_trades', lambda x: x[x > 0].count()) # number of winning trades
|
||||
],
|
||||
'trade_duration': [('avg_trade_duration', 'mean')]
|
||||
}
|
||||
|
||||
# Group by (pair and stoploss) by applying above aggregator
|
||||
df = results.groupby(['pair', 'stoploss'])['profit_abs', 'trade_duration'].agg(
|
||||
groupby_aggregator).reset_index(col_level=1)
|
||||
|
||||
# Dropping level 0 as we don't need it
|
||||
df.columns = df.columns.droplevel(0)
|
||||
|
||||
# Calculating number of losing trades, average win and average loss
|
||||
df['nb_loss_trades'] = df['nb_trades'] - df['nb_win_trades']
|
||||
df['average_win'] = df['profit_sum'] / df['nb_win_trades']
|
||||
df['average_loss'] = df['loss_sum'] / df['nb_loss_trades']
|
||||
|
||||
# Win rate = number of profitable trades / number of trades
|
||||
df['winrate'] = df['nb_win_trades'] / df['nb_trades']
|
||||
|
||||
# risk_reward_ratio = average win / average loss
|
||||
df['risk_reward_ratio'] = df['average_win'] / df['average_loss']
|
||||
|
||||
# required_risk_reward = (1 / winrate) - 1
|
||||
df['required_risk_reward'] = (1 / df['winrate']) - 1
|
||||
|
||||
# expectancy = (risk_reward_ratio * winrate) - (lossrate)
|
||||
df['expectancy'] = (df['risk_reward_ratio'] * df['winrate']) - (1 - df['winrate'])
|
||||
|
||||
# sort by expectancy and stoploss
|
||||
df = df.sort_values(by=['expectancy', 'stoploss'], ascending=False).groupby(
|
||||
'pair').first().sort_values(by=['expectancy'], ascending=False).reset_index()
|
||||
|
||||
final = {}
|
||||
for x in df.itertuples():
|
||||
final[x.pair] = PairInfo(
|
||||
x.stoploss,
|
||||
x.winrate,
|
||||
x.risk_reward_ratio,
|
||||
x.required_risk_reward,
|
||||
x.expectancy,
|
||||
x.nb_trades,
|
||||
x.avg_trade_duration
|
||||
)
|
||||
|
||||
# Returning a list of pairs in order of "expectancy"
|
||||
return final
|
||||
|
||||
def _find_trades_for_stoploss_range(self, ticker_data, pair, stoploss_range):
|
||||
buy_column = ticker_data['buy'].values
|
||||
sell_column = ticker_data['sell'].values
|
||||
date_column = ticker_data['date'].values
|
||||
ohlc_columns = ticker_data[['open', 'high', 'low', 'close']].values
|
||||
|
||||
result: list = []
|
||||
for stoploss in stoploss_range:
|
||||
result += self._detect_next_stop_or_sell_point(
|
||||
buy_column, sell_column, date_column, ohlc_columns, round(stoploss, 6), pair
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
def _detect_next_stop_or_sell_point(self, buy_column, sell_column, date_column,
|
||||
ohlc_columns, stoploss, pair):
|
||||
"""
|
||||
Iterate through ohlc_columns in order to find the next trade
|
||||
Next trade opens from the first buy signal noticed to
|
||||
The sell or stoploss signal after it.
|
||||
It then cuts OHLC, buy_column, sell_column and date_column.
|
||||
Cut from (the exit trade index) + 1.
|
||||
|
||||
Author: https://github.com/mishaker
|
||||
"""
|
||||
|
||||
result: list = []
|
||||
start_point = 0
|
||||
|
||||
while True:
|
||||
open_trade_index = utf1st.find_1st(buy_column, 1, utf1st.cmp_equal)
|
||||
|
||||
# Return empty if we don't find trade entry (i.e. buy==1) or
|
||||
# we find a buy but at the end of array
|
||||
if open_trade_index == -1 or open_trade_index == len(buy_column) - 1:
|
||||
break
|
||||
else:
|
||||
# When a buy signal is seen,
|
||||
# trade opens in reality on the next candle
|
||||
open_trade_index += 1
|
||||
|
||||
stop_price_percentage = stoploss + 1
|
||||
open_price = ohlc_columns[open_trade_index, 0]
|
||||
stop_price = (open_price * stop_price_percentage)
|
||||
|
||||
# Searching for the index where stoploss is hit
|
||||
stop_index = utf1st.find_1st(
|
||||
ohlc_columns[open_trade_index:, 2], stop_price, utf1st.cmp_smaller)
|
||||
|
||||
# If we don't find it then we assume stop_index will be far in future (infinite number)
|
||||
if stop_index == -1:
|
||||
stop_index = float('inf')
|
||||
|
||||
# Searching for the index where sell is hit
|
||||
sell_index = utf1st.find_1st(sell_column[open_trade_index:], 1, utf1st.cmp_equal)
|
||||
|
||||
# If we don't find it then we assume sell_index will be far in future (infinite number)
|
||||
if sell_index == -1:
|
||||
sell_index = float('inf')
|
||||
|
||||
# Check if we don't find any stop or sell point (in that case trade remains open)
|
||||
# It is not interesting for Edge to consider it so we simply ignore the trade
|
||||
# And stop iterating there is no more entry
|
||||
if stop_index == sell_index == float('inf'):
|
||||
break
|
||||
|
||||
if stop_index <= sell_index:
|
||||
exit_index = open_trade_index + stop_index
|
||||
exit_type = SellType.STOP_LOSS
|
||||
exit_price = stop_price
|
||||
elif stop_index > sell_index:
|
||||
# If exit is SELL then we exit at the next candle
|
||||
exit_index = open_trade_index + sell_index + 1
|
||||
|
||||
# Check if we have the next candle
|
||||
if len(ohlc_columns) - 1 < exit_index:
|
||||
break
|
||||
|
||||
exit_type = SellType.SELL_SIGNAL
|
||||
exit_price = ohlc_columns[exit_index, 0]
|
||||
|
||||
trade = {'pair': pair,
|
||||
'stoploss': stoploss,
|
||||
'profit_percent': '',
|
||||
'profit_abs': '',
|
||||
'open_time': date_column[open_trade_index],
|
||||
'close_time': date_column[exit_index],
|
||||
'open_index': start_point + open_trade_index,
|
||||
'close_index': start_point + exit_index,
|
||||
'trade_duration': '',
|
||||
'open_rate': round(open_price, 15),
|
||||
'close_rate': round(exit_price, 15),
|
||||
'exit_type': exit_type
|
||||
}
|
||||
|
||||
result.append(trade)
|
||||
|
||||
# Giving a view of exit_index till the end of array
|
||||
buy_column = buy_column[exit_index:]
|
||||
sell_column = sell_column[exit_index:]
|
||||
date_column = date_column[exit_index:]
|
||||
ohlc_columns = ohlc_columns[exit_index:]
|
||||
start_point += exit_index
|
||||
|
||||
return result
|
37
freqtrade/exceptions.py
Normal file
37
freqtrade/exceptions.py
Normal file
@@ -0,0 +1,37 @@
|
||||
|
||||
|
||||
class FreqtradeException(Exception):
|
||||
"""
|
||||
Freqtrade base exception. Handled at the outermost level.
|
||||
All other exception types are subclasses of this exception type.
|
||||
"""
|
||||
|
||||
|
||||
class OperationalException(FreqtradeException):
|
||||
"""
|
||||
Requires manual intervention and will stop the bot.
|
||||
Most of the time, this is caused by an invalid Configuration.
|
||||
"""
|
||||
|
||||
|
||||
class DependencyException(FreqtradeException):
|
||||
"""
|
||||
Indicates that an assumed dependency is not met.
|
||||
This could happen when there is currently not enough money on the account.
|
||||
"""
|
||||
|
||||
|
||||
class InvalidOrderException(FreqtradeException):
|
||||
"""
|
||||
This is returned when the order is not valid. Example:
|
||||
If stoploss on exchange order is hit, then trying to cancel the order
|
||||
should return this exception.
|
||||
"""
|
||||
|
||||
|
||||
class TemporaryError(FreqtradeException):
|
||||
"""
|
||||
Temporary network or exchange related error.
|
||||
This could happen when an exchange is congested, unavailable, or the user
|
||||
has networking problems. Usually resolves itself after a time.
|
||||
"""
|
@@ -1,18 +1,20 @@
|
||||
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS # noqa: F401
|
||||
from freqtrade.exchange.exchange import Exchange # noqa: F401
|
||||
from freqtrade.exchange.exchange import (get_exchange_bad_reason, # noqa: F401
|
||||
# flake8: noqa: F401
|
||||
from freqtrade.exchange.common import MAP_EXCHANGE_CHILDCLASS
|
||||
from freqtrade.exchange.exchange import Exchange
|
||||
from freqtrade.exchange.exchange import (get_exchange_bad_reason,
|
||||
is_exchange_bad,
|
||||
is_exchange_known_ccxt,
|
||||
is_exchange_officially_supported,
|
||||
ccxt_exchanges,
|
||||
available_exchanges)
|
||||
from freqtrade.exchange.exchange import (timeframe_to_seconds, # noqa: F401
|
||||
from freqtrade.exchange.exchange import (timeframe_to_seconds,
|
||||
timeframe_to_minutes,
|
||||
timeframe_to_msecs,
|
||||
timeframe_to_next_date,
|
||||
timeframe_to_prev_date)
|
||||
from freqtrade.exchange.exchange import (market_is_active, # noqa: F401
|
||||
from freqtrade.exchange.exchange import (market_is_active,
|
||||
symbol_is_pair)
|
||||
from freqtrade.exchange.kraken import Kraken # noqa: F401
|
||||
from freqtrade.exchange.binance import Binance # noqa: F401
|
||||
from freqtrade.exchange.bibox import Bibox # noqa: F401
|
||||
from freqtrade.exchange.kraken import Kraken
|
||||
from freqtrade.exchange.binance import Binance
|
||||
from freqtrade.exchange.bibox import Bibox
|
||||
from freqtrade.exchange.ftx import Ftx
|
||||
|
@@ -4,7 +4,7 @@ from typing import Dict
|
||||
|
||||
import ccxt
|
||||
|
||||
from freqtrade import (DependencyException, InvalidOrderException,
|
||||
from freqtrade.exceptions import (DependencyException, InvalidOrderException,
|
||||
OperationalException, TemporaryError)
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
@@ -32,16 +32,26 @@ class Binance(Exchange):
|
||||
|
||||
return super().get_order_book(pair, limit)
|
||||
|
||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
||||
"""
|
||||
Verify stop_loss against stoploss-order value (limit or price)
|
||||
Returns True if adjustment is necessary.
|
||||
"""
|
||||
return order['type'] == 'stop_loss_limit' and stop_loss > float(order['info']['stopPrice'])
|
||||
|
||||
def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict:
|
||||
"""
|
||||
creates a stoploss limit order.
|
||||
this stoploss-limit is binance-specific.
|
||||
It may work with a limited number of other exchanges, but this has not been tested yet.
|
||||
|
||||
"""
|
||||
# Limit price threshold: As limit price should always be below stop-price
|
||||
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
||||
rate = stop_price * limit_price_pct
|
||||
|
||||
ordertype = "stop_loss_limit"
|
||||
|
||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
||||
stop_price = self.price_to_precision(pair, stop_price)
|
||||
|
||||
# Ensure rate is less than stop price
|
||||
if stop_price <= rate:
|
||||
@@ -57,12 +67,12 @@ class Binance(Exchange):
|
||||
params = self._params.copy()
|
||||
params.update({'stopPrice': stop_price})
|
||||
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
amount = self.amount_to_precision(pair, amount)
|
||||
|
||||
rate = self.symbol_price_prec(pair, rate)
|
||||
rate = self.price_to_precision(pair, rate)
|
||||
|
||||
order = self._api.create_order(pair, ordertype, 'sell',
|
||||
amount, rate, params)
|
||||
order = self._api.create_order(symbol=pair, type=ordertype, side='sell',
|
||||
amount=amount, price=stop_price, params=params)
|
||||
logger.info('stoploss limit order added for %s. '
|
||||
'stop price: %s. limit: %s', pair, stop_price, rate)
|
||||
return order
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
|
||||
from freqtrade import DependencyException, TemporaryError
|
||||
from freqtrade.exceptions import DependencyException, TemporaryError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
@@ -7,22 +7,27 @@ import inspect
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from math import ceil, floor
|
||||
from math import ceil
|
||||
from random import randint
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import arrow
|
||||
import ccxt
|
||||
import ccxt.async_support as ccxt_async
|
||||
from ccxt.base.decimal_to_precision import ROUND_DOWN, ROUND_UP
|
||||
from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE,
|
||||
TRUNCATE, decimal_to_precision)
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade import (DependencyException, InvalidOrderException,
|
||||
OperationalException, TemporaryError, constants)
|
||||
from freqtrade.data.converter import parse_ticker_dataframe
|
||||
from freqtrade.exceptions import (DependencyException, InvalidOrderException,
|
||||
OperationalException, TemporaryError)
|
||||
from freqtrade.exchange.common import BAD_EXCHANGES, retrier, retrier_async
|
||||
from freqtrade.misc import deep_merge_dicts
|
||||
|
||||
|
||||
CcxtModuleType = Any
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -50,7 +55,7 @@ class Exchange:
|
||||
}
|
||||
_ft_has: Dict = {}
|
||||
|
||||
def __init__(self, config: dict, validate: bool = True) -> None:
|
||||
def __init__(self, config: Dict[str, Any], validate: bool = True) -> None:
|
||||
"""
|
||||
Initializes this module with the given config,
|
||||
it does basic validation whether the specified exchange and pairs are valid.
|
||||
@@ -61,8 +66,6 @@ class Exchange:
|
||||
|
||||
self._config.update(config)
|
||||
|
||||
self._cached_ticker: Dict[str, Any] = {}
|
||||
|
||||
# Holds last candle refreshed time of each pair
|
||||
self._pairs_last_refresh_time: Dict[Tuple[str, str], int] = {}
|
||||
# Timestamp of last markets refresh
|
||||
@@ -116,6 +119,7 @@ class Exchange:
|
||||
self._load_markets()
|
||||
|
||||
# Check if all pairs are available
|
||||
self.validate_stakecurrency(config['stake_currency'])
|
||||
self.validate_pairs(config['exchange']['pair_whitelist'])
|
||||
self.validate_ordertypes(config.get('order_types', {}))
|
||||
self.validate_order_time_in_force(config.get('order_time_in_force', {}))
|
||||
@@ -133,7 +137,7 @@ class Exchange:
|
||||
if self._api_async and inspect.iscoroutinefunction(self._api_async.close):
|
||||
asyncio.get_event_loop().run_until_complete(self._api_async.close())
|
||||
|
||||
def _init_ccxt(self, exchange_config: dict, ccxt_module=ccxt,
|
||||
def _init_ccxt(self, exchange_config: Dict[str, Any], ccxt_module: CcxtModuleType = ccxt,
|
||||
ccxt_kwargs: dict = None) -> ccxt.Exchange:
|
||||
"""
|
||||
Initialize ccxt with given config and return valid
|
||||
@@ -188,6 +192,11 @@ class Exchange:
|
||||
self._load_markets()
|
||||
return self._api.markets
|
||||
|
||||
@property
|
||||
def precisionMode(self) -> str:
|
||||
"""exchange ccxt precisionMode"""
|
||||
return self._api.precisionMode
|
||||
|
||||
def get_markets(self, base_currencies: List[str] = None, quote_currencies: List[str] = None,
|
||||
pairs_only: bool = False, active_only: bool = False) -> Dict:
|
||||
"""
|
||||
@@ -210,13 +219,20 @@ class Exchange:
|
||||
markets = {k: v for k, v in markets.items() if market_is_active(v)}
|
||||
return markets
|
||||
|
||||
def klines(self, pair_interval: Tuple[str, str], copy=True) -> DataFrame:
|
||||
def get_quote_currencies(self) -> List[str]:
|
||||
"""
|
||||
Return a list of supported quote currencies
|
||||
"""
|
||||
markets = self.markets
|
||||
return sorted(set([x['quote'] for _, x in markets.items()]))
|
||||
|
||||
def klines(self, pair_interval: Tuple[str, str], copy: bool = True) -> DataFrame:
|
||||
if pair_interval in self._klines:
|
||||
return self._klines[pair_interval].copy() if copy else self._klines[pair_interval]
|
||||
else:
|
||||
return DataFrame()
|
||||
|
||||
def set_sandbox(self, api, exchange_config: dict, name: str):
|
||||
def set_sandbox(self, api: ccxt.Exchange, exchange_config: dict, name: str) -> None:
|
||||
if exchange_config.get('sandbox'):
|
||||
if api.urls.get('test'):
|
||||
api.urls['api'] = api.urls['test']
|
||||
@@ -226,7 +242,7 @@ class Exchange:
|
||||
"Please check your config.json")
|
||||
raise OperationalException(f'Exchange {name} does not provide a sandbox api')
|
||||
|
||||
def _load_async_markets(self, reload=False) -> None:
|
||||
def _load_async_markets(self, reload: bool = False) -> None:
|
||||
try:
|
||||
if self._api_async:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
@@ -259,11 +275,23 @@ class Exchange:
|
||||
except ccxt.BaseError:
|
||||
logger.exception("Could not reload markets.")
|
||||
|
||||
def validate_stakecurrency(self, stake_currency: str) -> None:
|
||||
"""
|
||||
Checks stake-currency against available currencies on the exchange.
|
||||
:param stake_currency: Stake-currency to validate
|
||||
:raise: OperationalException if stake-currency is not available.
|
||||
"""
|
||||
quote_currencies = self.get_quote_currencies()
|
||||
if stake_currency not in quote_currencies:
|
||||
raise OperationalException(
|
||||
f"{stake_currency} is not available as stake on {self.name}. "
|
||||
f"Available currencies are: {', '.join(quote_currencies)}")
|
||||
|
||||
def validate_pairs(self, pairs: List[str]) -> None:
|
||||
"""
|
||||
Checks if all given pairs are tradable on the current exchange.
|
||||
Raises OperationalException if one pair is not available.
|
||||
:param pairs: list of pairs
|
||||
:raise: OperationalException if one pair is not available
|
||||
:return: None
|
||||
"""
|
||||
|
||||
@@ -278,14 +306,22 @@ class Exchange:
|
||||
raise OperationalException(
|
||||
f'Pair {pair} is not available on {self.name}. '
|
||||
f'Please remove {pair} from your whitelist.')
|
||||
elif self.markets[pair].get('info', {}).get('IsRestricted', False):
|
||||
|
||||
# From ccxt Documentation:
|
||||
# markets.info: An associative array of non-common market properties,
|
||||
# including fees, rates, limits and other general market information.
|
||||
# The internal info array is different for each particular market,
|
||||
# its contents depend on the exchange.
|
||||
# It can also be a string or similar ... so we need to verify that first.
|
||||
elif (isinstance(self.markets[pair].get('info', None), dict)
|
||||
and self.markets[pair].get('info', {}).get('IsRestricted', False)):
|
||||
# Warn users about restricted pairs in whitelist.
|
||||
# We cannot determine reliably if Users are affected.
|
||||
logger.warning(f"Pair {pair} is restricted for some users on this exchange."
|
||||
f"Please check if you are impacted by this restriction "
|
||||
f"on the exchange and eventually remove {pair} from your whitelist.")
|
||||
|
||||
def get_valid_pair_combination(self, curr_1, curr_2) -> str:
|
||||
def get_valid_pair_combination(self, curr_1: str, curr_2: str) -> str:
|
||||
"""
|
||||
Get valid pair combination of curr_1 and curr_2 by trying both combinations.
|
||||
"""
|
||||
@@ -311,6 +347,10 @@ class Exchange:
|
||||
raise OperationalException(
|
||||
f"Invalid ticker interval '{timeframe}'. This exchange supports: {self.timeframes}")
|
||||
|
||||
if timeframe and timeframe_to_minutes(timeframe) < 1:
|
||||
raise OperationalException(
|
||||
f"Timeframes < 1m are currently not supported by Freqtrade.")
|
||||
|
||||
def validate_ordertypes(self, order_types: Dict) -> None:
|
||||
"""
|
||||
Checks if order-types configured in strategy/config are supported
|
||||
@@ -335,7 +375,7 @@ class Exchange:
|
||||
raise OperationalException(
|
||||
f'Time in force policies are not supported for {self.name} yet.')
|
||||
|
||||
def validate_required_startup_candles(self, startup_candles) -> None:
|
||||
def validate_required_startup_candles(self, startup_candles: int) -> None:
|
||||
"""
|
||||
Checks if required startup_candles is more than ohlcv_candle_limit.
|
||||
Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default.
|
||||
@@ -354,23 +394,40 @@ class Exchange:
|
||||
"""
|
||||
return endpoint in self._api.has and self._api.has[endpoint]
|
||||
|
||||
def symbol_amount_prec(self, pair, amount: float):
|
||||
def amount_to_precision(self, pair: str, amount: float) -> float:
|
||||
'''
|
||||
Returns the amount to buy or sell to a precision the Exchange accepts
|
||||
Rounded down
|
||||
Reimplementation of ccxt internal methods - ensuring we can test the result is correct
|
||||
based on our definitions.
|
||||
'''
|
||||
if self.markets[pair]['precision']['amount']:
|
||||
symbol_prec = self.markets[pair]['precision']['amount']
|
||||
big_amount = amount * pow(10, symbol_prec)
|
||||
amount = floor(big_amount) / pow(10, symbol_prec)
|
||||
amount = float(decimal_to_precision(amount, rounding_mode=TRUNCATE,
|
||||
precision=self.markets[pair]['precision']['amount'],
|
||||
counting_mode=self.precisionMode,
|
||||
))
|
||||
|
||||
return amount
|
||||
|
||||
def symbol_price_prec(self, pair, price: float):
|
||||
def price_to_precision(self, pair: str, price: float) -> float:
|
||||
'''
|
||||
Returns the price buying or selling with to the precision the Exchange accepts
|
||||
Returns the price rounded up to the precision the Exchange accepts.
|
||||
Partial Reimplementation of ccxt internal method decimal_to_precision(),
|
||||
which does not support rounding up
|
||||
TODO: If ccxt supports ROUND_UP for decimal_to_precision(), we could remove this and
|
||||
align with amount_to_precision().
|
||||
Rounds up
|
||||
'''
|
||||
if self.markets[pair]['precision']['price']:
|
||||
# price = float(decimal_to_precision(price, rounding_mode=ROUND,
|
||||
# precision=self.markets[pair]['precision']['price'],
|
||||
# counting_mode=self.precisionMode,
|
||||
# ))
|
||||
if self.precisionMode == TICK_SIZE:
|
||||
precision = self.markets[pair]['precision']['price']
|
||||
missing = price % precision
|
||||
if missing != 0:
|
||||
price = price - missing + precision
|
||||
else:
|
||||
symbol_prec = self.markets[pair]['precision']['price']
|
||||
big_price = price * pow(10, symbol_prec)
|
||||
price = ceil(big_price) / pow(10, symbol_prec)
|
||||
@@ -379,15 +436,16 @@ class Exchange:
|
||||
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
||||
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
||||
_amount = self.amount_to_precision(pair, amount)
|
||||
dry_order = {
|
||||
"id": order_id,
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
"cost": amount * rate,
|
||||
'amount': _amount,
|
||||
"cost": _amount * rate,
|
||||
'type': ordertype,
|
||||
'side': side,
|
||||
'remaining': amount,
|
||||
'remaining': _amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': "closed" if ordertype == "market" else "open",
|
||||
'fee': None,
|
||||
@@ -413,13 +471,13 @@ class Exchange:
|
||||
rate: float, params: Dict = {}) -> Dict:
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
amount = self.amount_to_precision(pair, amount)
|
||||
needs_price = (ordertype != 'market'
|
||||
or self._api.options.get("createMarketBuyOrderRequiresPrice", False))
|
||||
rate = self.symbol_price_prec(pair, rate) if needs_price else None
|
||||
rate_for_order = self.price_to_precision(pair, rate) if needs_price else None
|
||||
|
||||
return self._api.create_order(pair, ordertype, side,
|
||||
amount, rate, params)
|
||||
amount, rate_for_order, params)
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
@@ -438,7 +496,7 @@ class Exchange:
|
||||
raise OperationalException(e) from e
|
||||
|
||||
def buy(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force) -> Dict:
|
||||
rate: float, time_in_force: str) -> Dict:
|
||||
|
||||
if self._config['dry_run']:
|
||||
dry_order = self.dry_run_order(pair, ordertype, "buy", amount, rate)
|
||||
@@ -451,7 +509,7 @@ class Exchange:
|
||||
return self.create_order(pair, ordertype, 'buy', amount, rate, params)
|
||||
|
||||
def sell(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force='gtc') -> Dict:
|
||||
rate: float, time_in_force: str = 'gtc') -> Dict:
|
||||
|
||||
if self._config['dry_run']:
|
||||
dry_order = self.dry_run_order(pair, ordertype, "sell", amount, rate)
|
||||
@@ -463,9 +521,17 @@ class Exchange:
|
||||
|
||||
return self.create_order(pair, ordertype, 'sell', amount, rate, params)
|
||||
|
||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
||||
"""
|
||||
creates a stoploss limit order.
|
||||
Verify stop_loss against stoploss-order value (limit or price)
|
||||
Returns True if adjustment is necessary.
|
||||
"""
|
||||
raise OperationalException(f"stoploss is not implemented for {self.name}.")
|
||||
|
||||
def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict:
|
||||
"""
|
||||
creates a stoploss order.
|
||||
The precise ordertype is determined by the order_types dict or exchange default.
|
||||
Since ccxt does not unify stoploss-limit orders yet, this needs to be implemented in each
|
||||
exchange's subclass.
|
||||
The exception below should never raise, since we disallow
|
||||
@@ -473,12 +539,12 @@ class Exchange:
|
||||
Note: Changes to this interface need to be applied to all sub-classes too.
|
||||
"""
|
||||
|
||||
raise OperationalException(f"stoploss_limit is not implemented for {self.name}.")
|
||||
raise OperationalException(f"stoploss is not implemented for {self.name}.")
|
||||
|
||||
@retrier
|
||||
def get_balance(self, currency: str) -> float:
|
||||
if self._config['dry_run']:
|
||||
return constants.DRY_RUN_WALLET
|
||||
return self._config['dry_run_wallet']
|
||||
|
||||
# ccxt exception is already handled by get_balances
|
||||
balances = self.get_balances()
|
||||
@@ -523,28 +589,17 @@ class Exchange:
|
||||
raise OperationalException(e) from e
|
||||
|
||||
@retrier
|
||||
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
|
||||
if refresh or pair not in self._cached_ticker.keys():
|
||||
def fetch_ticker(self, pair: str) -> dict:
|
||||
try:
|
||||
if pair not in self._api.markets or not self._api.markets[pair].get('active'):
|
||||
raise DependencyException(f"Pair {pair} not available")
|
||||
data = self._api.fetch_ticker(pair)
|
||||
try:
|
||||
self._cached_ticker[pair] = {
|
||||
'bid': float(data['bid']),
|
||||
'ask': float(data['ask']),
|
||||
}
|
||||
except KeyError:
|
||||
logger.debug("Could not cache ticker data for %s", pair)
|
||||
return data
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not load ticker due to {e.__class__.__name__}. Message: {e}') from e
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e) from e
|
||||
else:
|
||||
logger.info("returning cached ticker-data for %s", pair)
|
||||
return self._cached_ticker[pair]
|
||||
|
||||
def get_historic_ohlcv(self, pair: str, timeframe: str,
|
||||
since_ms: int) -> List:
|
||||
@@ -672,10 +727,11 @@ class Exchange:
|
||||
f'Exchange {self._api.name} does not support fetching historical candlestick data.'
|
||||
f'Message: {e}') from e
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(f'Could not load ticker history due to {e.__class__.__name__}. '
|
||||
f'Message: {e}') from e
|
||||
raise TemporaryError(f'Could not load ticker history for pair {pair} due to '
|
||||
f'{e.__class__.__name__}. Message: {e}') from e
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(f'Could not fetch ticker data. Msg: {e}') from e
|
||||
raise OperationalException(f'Could not fetch ticker data for pair {pair}. '
|
||||
f'Msg: {e}') from e
|
||||
|
||||
@retrier_async
|
||||
async def _async_fetch_trades(self, pair: str,
|
||||
@@ -920,8 +976,8 @@ class Exchange:
|
||||
raise OperationalException(e) from e
|
||||
|
||||
@retrier
|
||||
def get_fee(self, symbol='ETH/BTC', type='', side='', amount=1,
|
||||
price=1, taker_or_maker='maker') -> float:
|
||||
def get_fee(self, symbol: str, type: str = '', side: str = '', amount: float = 1,
|
||||
price: float = 1, taker_or_maker: str = 'maker') -> float:
|
||||
try:
|
||||
# validate that markets are loaded before trying to get fee
|
||||
if self._api.markets is None or len(self._api.markets) == 0:
|
||||
@@ -944,7 +1000,7 @@ def get_exchange_bad_reason(exchange_name: str) -> str:
|
||||
return BAD_EXCHANGES.get(exchange_name, "")
|
||||
|
||||
|
||||
def is_exchange_known_ccxt(exchange_name: str, ccxt_module=None) -> bool:
|
||||
def is_exchange_known_ccxt(exchange_name: str, ccxt_module: CcxtModuleType = None) -> bool:
|
||||
return exchange_name in ccxt_exchanges(ccxt_module)
|
||||
|
||||
|
||||
@@ -952,14 +1008,14 @@ def is_exchange_officially_supported(exchange_name: str) -> bool:
|
||||
return exchange_name in ['bittrex', 'binance']
|
||||
|
||||
|
||||
def ccxt_exchanges(ccxt_module=None) -> List[str]:
|
||||
def ccxt_exchanges(ccxt_module: CcxtModuleType = None) -> List[str]:
|
||||
"""
|
||||
Return the list of all exchanges known to ccxt
|
||||
"""
|
||||
return ccxt_module.exchanges if ccxt_module is not None else ccxt.exchanges
|
||||
|
||||
|
||||
def available_exchanges(ccxt_module=None) -> List[str]:
|
||||
def available_exchanges(ccxt_module: CcxtModuleType = None) -> List[str]:
|
||||
"""
|
||||
Return exchanges available to the bot, i.e. non-bad exchanges in the ccxt list
|
||||
"""
|
||||
@@ -1019,7 +1075,8 @@ def timeframe_to_next_date(timeframe: str, date: datetime = None) -> datetime:
|
||||
return datetime.fromtimestamp(new_timestamp, tz=timezone.utc)
|
||||
|
||||
|
||||
def symbol_is_pair(market_symbol: str, base_currency: str = None, quote_currency: str = None):
|
||||
def symbol_is_pair(market_symbol: str, base_currency: str = None,
|
||||
quote_currency: str = None) -> bool:
|
||||
"""
|
||||
Check if the market symbol is a pair, i.e. that its symbol consists of the base currency and the
|
||||
quote currency separated by '/' character. If base_currency and/or quote_currency is passed,
|
||||
@@ -1032,7 +1089,7 @@ def symbol_is_pair(market_symbol: str, base_currency: str = None, quote_currency
|
||||
(symbol_parts[1] == quote_currency if quote_currency else len(symbol_parts[1]) > 0))
|
||||
|
||||
|
||||
def market_is_active(market):
|
||||
def market_is_active(market: Dict) -> bool:
|
||||
"""
|
||||
Return True if the market is active.
|
||||
"""
|
||||
|
14
freqtrade/exchange/ftx.py
Normal file
14
freqtrade/exchange/ftx.py
Normal file
@@ -0,0 +1,14 @@
|
||||
""" FTX exchange subclass """
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from freqtrade.exchange import Exchange
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Ftx(Exchange):
|
||||
|
||||
_ft_has: Dict = {
|
||||
"ohlcv_candle_limit": 1500,
|
||||
}
|
@@ -4,7 +4,8 @@ from typing import Dict
|
||||
|
||||
import ccxt
|
||||
|
||||
from freqtrade import OperationalException, TemporaryError
|
||||
from freqtrade.exceptions import (DependencyException, InvalidOrderException,
|
||||
OperationalException, TemporaryError)
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.exchange.exchange import retrier
|
||||
|
||||
@@ -15,6 +16,7 @@ class Kraken(Exchange):
|
||||
|
||||
_params: Dict = {"trading_agreement": "agree"}
|
||||
_ft_has: Dict = {
|
||||
"stoploss_on_exchange": True,
|
||||
"trades_pagination": "id",
|
||||
"trades_pagination_arg": "since",
|
||||
}
|
||||
@@ -48,3 +50,51 @@ class Kraken(Exchange):
|
||||
f'Could not get balance due to {e.__class__.__name__}. Message: {e}') from e
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e) from e
|
||||
|
||||
def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool:
|
||||
"""
|
||||
Verify stop_loss against stoploss-order value (limit or price)
|
||||
Returns True if adjustment is necessary.
|
||||
"""
|
||||
return order['type'] == 'stop-loss' and stop_loss > float(order['price'])
|
||||
|
||||
def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict:
|
||||
"""
|
||||
Creates a stoploss market order.
|
||||
Stoploss market orders is the only stoploss type supported by kraken.
|
||||
"""
|
||||
|
||||
ordertype = "stop-loss"
|
||||
|
||||
stop_price = self.price_to_precision(pair, stop_price)
|
||||
|
||||
if self._config['dry_run']:
|
||||
dry_order = self.dry_run_order(
|
||||
pair, ordertype, "sell", amount, stop_price)
|
||||
return dry_order
|
||||
|
||||
try:
|
||||
params = self._params.copy()
|
||||
|
||||
amount = self.amount_to_precision(pair, amount)
|
||||
|
||||
order = self._api.create_order(symbol=pair, type=ordertype, side='sell',
|
||||
amount=amount, price=stop_price, params=params)
|
||||
logger.info('stoploss order added for %s. '
|
||||
'stop price: %s.', pair, stop_price)
|
||||
return order
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create {ordertype} sell order on market {pair}.'
|
||||
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
||||
f'Message: {e}') from e
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise InvalidOrderException(
|
||||
f'Could not create {ordertype} sell order on market {pair}. '
|
||||
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
||||
f'Message: {e}') from e
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}') from e
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e) from e
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@ from logging import Formatter
|
||||
from logging.handlers import RotatingFileHandler, SysLogHandler
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
@@ -4,6 +4,7 @@ Main Freqtrade bot script.
|
||||
Read the documentation to know what cli arguments you need.
|
||||
"""
|
||||
|
||||
from freqtrade.exceptions import FreqtradeException, OperationalException
|
||||
import sys
|
||||
# check min. python version
|
||||
if sys.version_info < (3, 6):
|
||||
@@ -13,8 +14,7 @@ if sys.version_info < (3, 6):
|
||||
import logging
|
||||
from typing import Any, List
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.configuration import Arguments
|
||||
from freqtrade.commands import Arguments
|
||||
|
||||
|
||||
logger = logging.getLogger('freqtrade')
|
||||
@@ -38,8 +38,8 @@ def main(sysargv: List[str] = None) -> None:
|
||||
# No subcommand was issued.
|
||||
raise OperationalException(
|
||||
"Usage of Freqtrade requires a subcommand to be specified.\n"
|
||||
"To have the previous behavior (bot executing trades in live/dry-run modes, "
|
||||
"depending on the value of the `dry_run` setting in the config), run freqtrade "
|
||||
"To have the bot executing trades in live/dry-run modes, "
|
||||
"depending on the value of the `dry_run` setting in the config, run Freqtrade "
|
||||
"as `freqtrade trade [options...]`.\n"
|
||||
"To see the full list of options available, please use "
|
||||
"`freqtrade --help` or `freqtrade <command> --help`."
|
||||
@@ -50,7 +50,7 @@ def main(sysargv: List[str] = None) -> None:
|
||||
except KeyboardInterrupt:
|
||||
logger.info('SIGINT received, aborting ...')
|
||||
return_code = 0
|
||||
except OperationalException as e:
|
||||
except FreqtradeException as e:
|
||||
logger.error(str(e))
|
||||
return_code = 2
|
||||
except Exception:
|
||||
|
@@ -6,6 +6,7 @@ import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing.io import IO
|
||||
|
||||
import numpy as np
|
||||
@@ -40,28 +41,30 @@ def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
|
||||
return dates.dt.to_pydatetime()
|
||||
|
||||
|
||||
def file_dump_json(filename: Path, data, is_zip=False) -> None:
|
||||
def file_dump_json(filename: Path, data: Any, is_zip: bool = False) -> None:
|
||||
"""
|
||||
Dump JSON data into a file
|
||||
:param filename: file to create
|
||||
:param data: JSON Data to save
|
||||
:return:
|
||||
"""
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
|
||||
if is_zip:
|
||||
if filename.suffix != '.gz':
|
||||
filename = filename.with_suffix('.gz')
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
|
||||
with gzip.open(filename, 'w') as fp:
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
else:
|
||||
logger.info(f'dumping json to "{filename}"')
|
||||
with open(filename, 'w') as fp:
|
||||
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
|
||||
|
||||
logger.debug(f'done json to "{filename}"')
|
||||
|
||||
|
||||
def json_load(datafile: IO):
|
||||
def json_load(datafile: IO) -> Any:
|
||||
"""
|
||||
load data with rapidjson
|
||||
Use this to have a consistent experience,
|
||||
@@ -90,6 +93,12 @@ def file_load_json(file):
|
||||
return pairdata
|
||||
|
||||
|
||||
def pair_to_filename(pair: str) -> str:
|
||||
for ch in ['/', '-', ' ', '.', '@', '$', '+', ':']:
|
||||
pair = pair.replace(ch, '_')
|
||||
return pair
|
||||
|
||||
|
||||
def format_ms_time(date: int) -> str:
|
||||
"""
|
||||
convert MS date to readable format.
|
||||
@@ -125,11 +134,11 @@ def round_dict(d, n):
|
||||
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
||||
|
||||
|
||||
def plural(num, singular: str, plural: str = None) -> str:
|
||||
def plural(num: float, singular: str, plural: str = None) -> str:
|
||||
return singular if (num == 1 or num == -1) else plural or singular + 's'
|
||||
|
||||
|
||||
def render_template(templatefile: str, arguments: dict = {}):
|
||||
def render_template(templatefile: str, arguments: dict = {}) -> str:
|
||||
|
||||
from jinja2 import Environment, PackageLoader, select_autoescape
|
||||
|
||||
@@ -138,5 +147,4 @@ def render_template(templatefile: str, arguments: dict = {}):
|
||||
autoescape=select_autoescape(['html', 'xml'])
|
||||
)
|
||||
template = env.get_template(templatefile)
|
||||
|
||||
return template.render(**arguments)
|
||||
|
@@ -1,102 +0,0 @@
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from freqtrade import DependencyException, constants, OperationalException
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.utils import setup_utils_configuration
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:
|
||||
"""
|
||||
Prepare the configuration for the Hyperopt module
|
||||
:param args: Cli args from Arguments()
|
||||
:return: Configuration
|
||||
"""
|
||||
config = setup_utils_configuration(args, method)
|
||||
|
||||
if method == RunMode.BACKTEST:
|
||||
if config['stake_amount'] == constants.UNLIMITED_STAKE_AMOUNT:
|
||||
raise DependencyException('stake amount could not be "%s" for backtesting' %
|
||||
constants.UNLIMITED_STAKE_AMOUNT)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def start_backtesting(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Start Backtesting script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
# Import here to avoid loading backtesting module when it's not used
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
|
||||
# Initialize configuration
|
||||
config = setup_configuration(args, RunMode.BACKTEST)
|
||||
|
||||
logger.info('Starting freqtrade in Backtesting mode')
|
||||
|
||||
# Initialize backtesting object
|
||||
backtesting = Backtesting(config)
|
||||
backtesting.start()
|
||||
|
||||
|
||||
def start_hyperopt(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Start hyperopt script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
# Import here to avoid loading hyperopt module when it's not used
|
||||
try:
|
||||
from filelock import FileLock, Timeout
|
||||
from freqtrade.optimize.hyperopt import Hyperopt
|
||||
except ImportError as e:
|
||||
raise OperationalException(
|
||||
f"{e}. Please ensure that the hyperopt dependencies are installed.") from e
|
||||
# Initialize configuration
|
||||
config = setup_configuration(args, RunMode.HYPEROPT)
|
||||
|
||||
logger.info('Starting freqtrade in Hyperopt mode')
|
||||
|
||||
lock = FileLock(Hyperopt.get_lock_filename(config))
|
||||
|
||||
try:
|
||||
with lock.acquire(timeout=1):
|
||||
|
||||
# Remove noisy log messages
|
||||
logging.getLogger('hyperopt.tpe').setLevel(logging.WARNING)
|
||||
logging.getLogger('filelock').setLevel(logging.WARNING)
|
||||
|
||||
# Initialize backtesting object
|
||||
hyperopt = Hyperopt(config)
|
||||
hyperopt.start()
|
||||
|
||||
except Timeout:
|
||||
logger.info("Another running instance of freqtrade Hyperopt detected.")
|
||||
logger.info("Simultaneous execution of multiple Hyperopt commands is not supported. "
|
||||
"Hyperopt module is resource hungry. Please run your Hyperopt sequentially "
|
||||
"or on separate machines.")
|
||||
logger.info("Quitting now.")
|
||||
# TODO: return False here in order to help freqtrade to exit
|
||||
# with non-zero exit code...
|
||||
# Same in Edge and Backtesting start() functions.
|
||||
|
||||
|
||||
def start_edge(args: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Start Edge script
|
||||
:param args: Cli args from Arguments()
|
||||
:return: None
|
||||
"""
|
||||
from freqtrade.optimize.edge_cli import EdgeCli
|
||||
# Initialize configuration
|
||||
config = setup_configuration(args, RunMode.EDGE)
|
||||
logger.info('Starting freqtrade in Edge mode')
|
||||
|
||||
# Initialize Edge object
|
||||
edge_cli = EdgeCli(config)
|
||||
edge_cli.start()
|
||||
|
@@ -9,20 +9,24 @@ from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, NamedTuple, Optional
|
||||
|
||||
import arrow
|
||||
from pandas import DataFrame
|
||||
from tabulate import tabulate
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.configuration import (TimeRange, remove_credentials,
|
||||
validate_config_consistency)
|
||||
from freqtrade.data import history
|
||||
from freqtrade.data.converter import trim_dataframe
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
|
||||
from freqtrade.misc import file_dump_json
|
||||
from freqtrade.optimize.optimize_reports import (
|
||||
generate_text_table, generate_text_table_sell_reason,
|
||||
generate_text_table_strategy)
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.strategy.interface import IStrategy, SellType
|
||||
from freqtrade.strategy.interface import IStrategy, SellCheckTuple, SellType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -60,12 +64,12 @@ class Backtesting:
|
||||
# Reset keys for backtesting
|
||||
remove_credentials(self.config)
|
||||
self.strategylist: List[IStrategy] = []
|
||||
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
|
||||
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
|
||||
|
||||
if config.get('fee'):
|
||||
self.fee = config['fee']
|
||||
else:
|
||||
self.fee = self.exchange.get_fee()
|
||||
self.fee = self.exchange.get_fee(symbol=self.config['exchange']['pair_whitelist'][0])
|
||||
|
||||
if self.config.get('runmode') != RunMode.HYPEROPT:
|
||||
self.dataprovider = DataProvider(self.config, self.exchange)
|
||||
@@ -75,19 +79,19 @@ class Backtesting:
|
||||
for strat in list(self.config['strategy_list']):
|
||||
stratconf = deepcopy(self.config)
|
||||
stratconf['strategy'] = strat
|
||||
self.strategylist.append(StrategyResolver(stratconf).strategy)
|
||||
self.strategylist.append(StrategyResolver.load_strategy(stratconf))
|
||||
validate_config_consistency(stratconf)
|
||||
|
||||
else:
|
||||
# No strategy list specified, only one strategy
|
||||
self.strategylist.append(StrategyResolver(self.config).strategy)
|
||||
self.strategylist.append(StrategyResolver.load_strategy(self.config))
|
||||
validate_config_consistency(self.config)
|
||||
|
||||
if "ticker_interval" not in self.config:
|
||||
raise OperationalException("Ticker-interval needs to be set in either configuration "
|
||||
"or as cli argument `--ticker-interval 5m`")
|
||||
self.timeframe = str(self.config.get('ticker_interval'))
|
||||
self.timeframe_mins = timeframe_to_minutes(self.timeframe)
|
||||
self.timeframe_min = timeframe_to_minutes(self.timeframe)
|
||||
|
||||
# Get maximum required startup period
|
||||
self.required_startup = max([strat.startup_candle_count for strat in self.strategylist])
|
||||
@@ -109,15 +113,16 @@ class Backtesting:
|
||||
'timerange') is None else str(self.config.get('timerange')))
|
||||
|
||||
data = history.load_data(
|
||||
datadir=Path(self.config['datadir']),
|
||||
datadir=self.config['datadir'],
|
||||
pairs=self.config['exchange']['pair_whitelist'],
|
||||
timeframe=self.timeframe,
|
||||
timerange=timerange,
|
||||
startup_candles=self.required_startup,
|
||||
fail_without_data=True,
|
||||
data_format=self.config.get('dataformat_ohlcv', 'json'),
|
||||
)
|
||||
|
||||
min_date, max_date = history.get_timeframe(data)
|
||||
min_date, max_date = history.get_timerange(data)
|
||||
|
||||
logger.info(
|
||||
'Loading data from %s up to %s (%s days)..',
|
||||
@@ -129,94 +134,6 @@ class Backtesting:
|
||||
|
||||
return data, timerange
|
||||
|
||||
def _generate_text_table(self, data: Dict[str, Dict], results: DataFrame,
|
||||
skip_nan: bool = False) -> str:
|
||||
"""
|
||||
Generates and returns a text table for the given backtest data and the results dataframe
|
||||
:return: pretty printed table with tabulate as str
|
||||
"""
|
||||
stake_currency = str(self.config.get('stake_currency'))
|
||||
max_open_trades = self.config.get('max_open_trades')
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = ['pair', 'buy count', 'avg profit %', 'cum profit %',
|
||||
'tot profit ' + stake_currency, 'tot profit %', 'avg duration',
|
||||
'profit', 'loss']
|
||||
for pair in data:
|
||||
result = results[results.pair == pair]
|
||||
if skip_nan and result.profit_abs.isnull().all():
|
||||
continue
|
||||
|
||||
tabular_data.append([
|
||||
pair,
|
||||
len(result.index),
|
||||
result.profit_percent.mean() * 100.0,
|
||||
result.profit_percent.sum() * 100.0,
|
||||
result.profit_abs.sum(),
|
||||
result.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(result.trade_duration.mean()))) if not result.empty else '0:00',
|
||||
len(result[result.profit_abs > 0]),
|
||||
len(result[result.profit_abs < 0])
|
||||
])
|
||||
|
||||
# Append Total
|
||||
tabular_data.append([
|
||||
'TOTAL',
|
||||
len(results.index),
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_percent.sum() * 100.0,
|
||||
results.profit_abs.sum(),
|
||||
results.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(results.trade_duration.mean()))) if not results.empty else '0:00',
|
||||
len(results[results.profit_abs > 0]),
|
||||
len(results[results.profit_abs < 0])
|
||||
])
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers,
|
||||
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||
|
||||
def _generate_text_table_sell_reason(self, data: Dict[str, Dict], results: DataFrame) -> str:
|
||||
"""
|
||||
Generate small table outlining Backtest results
|
||||
"""
|
||||
tabular_data = []
|
||||
headers = ['Sell Reason', 'Count']
|
||||
for reason, count in results['sell_reason'].value_counts().iteritems():
|
||||
tabular_data.append([reason.value, count])
|
||||
return tabulate(tabular_data, headers=headers, tablefmt="pipe")
|
||||
|
||||
def _generate_text_table_strategy(self, all_results: dict) -> str:
|
||||
"""
|
||||
Generate summary table per strategy
|
||||
"""
|
||||
stake_currency = str(self.config.get('stake_currency'))
|
||||
max_open_trades = self.config.get('max_open_trades')
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = ['Strategy', 'buy count', 'avg profit %', 'cum profit %',
|
||||
'tot profit ' + stake_currency, 'tot profit %', 'avg duration',
|
||||
'profit', 'loss']
|
||||
for strategy, results in all_results.items():
|
||||
tabular_data.append([
|
||||
strategy,
|
||||
len(results.index),
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_percent.sum() * 100.0,
|
||||
results.profit_abs.sum(),
|
||||
results.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(results.trade_duration.mean()))) if not results.empty else '0:00',
|
||||
len(results[results.profit_abs > 0]),
|
||||
len(results[results.profit_abs < 0])
|
||||
])
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers,
|
||||
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||
|
||||
def _store_backtest_result(self, recordfilename: Path, results: DataFrame,
|
||||
strategyname: Optional[str] = None) -> None:
|
||||
|
||||
@@ -234,7 +151,7 @@ class Backtesting:
|
||||
logger.info(f'Dumping backtest results to {recordfilename}')
|
||||
file_dump_json(recordfilename, records)
|
||||
|
||||
def _get_ticker_list(self, processed) -> Dict[str, DataFrame]:
|
||||
def _get_ticker_list(self, processed: Dict) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Helper function to convert a processed tickerlist into a list for performance reasons.
|
||||
|
||||
@@ -261,6 +178,46 @@ class Backtesting:
|
||||
ticker[pair] = [x for x in ticker_data.itertuples()]
|
||||
return ticker
|
||||
|
||||
def _get_close_rate(self, sell_row, trade: Trade, sell: SellCheckTuple,
|
||||
trade_dur: int) -> float:
|
||||
"""
|
||||
Get close rate for backtesting result
|
||||
"""
|
||||
# Special handling if high or low hit STOP_LOSS or ROI
|
||||
if sell.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
|
||||
# Set close_rate to stoploss
|
||||
return trade.stop_loss
|
||||
elif sell.sell_type == (SellType.ROI):
|
||||
roi_entry, roi = self.strategy.min_roi_reached_entry(trade_dur)
|
||||
if roi is not None:
|
||||
if roi == -1 and roi_entry % self.timeframe_min == 0:
|
||||
# When forceselling with ROI=-1, the roi time will always be equal to trade_dur.
|
||||
# If that entry is a multiple of the timeframe (so on candle open)
|
||||
# - we'll use open instead of close
|
||||
return sell_row.open
|
||||
|
||||
# - (Expected abs profit + open_rate + open_fee) / (fee_close -1)
|
||||
close_rate = - (trade.open_rate * roi + trade.open_rate *
|
||||
(1 + trade.fee_open)) / (trade.fee_close - 1)
|
||||
|
||||
if (trade_dur > 0 and trade_dur == roi_entry
|
||||
and roi_entry % self.timeframe_min == 0
|
||||
and sell_row.open > close_rate):
|
||||
# new ROI entry came into effect.
|
||||
# use Open rate if open_rate > calculated sell rate
|
||||
return sell_row.open
|
||||
|
||||
# Use the maximum between close_rate and low as we
|
||||
# cannot sell outside of a candle.
|
||||
# Applies when a new ROI setting comes in place and the whole candle is above that.
|
||||
return max(close_rate, sell_row.low)
|
||||
|
||||
else:
|
||||
# This should not be reached...
|
||||
return sell_row.open
|
||||
else:
|
||||
return sell_row.open
|
||||
|
||||
def _get_sell_trade_entry(
|
||||
self, pair: str, buy_row: DataFrame,
|
||||
partial_ticker: List, trade_count_lock: Dict,
|
||||
@@ -287,29 +244,10 @@ class Backtesting:
|
||||
sell_row.sell, low=sell_row.low, high=sell_row.high)
|
||||
if sell.sell_flag:
|
||||
trade_dur = int((sell_row.date - buy_row.date).total_seconds() // 60)
|
||||
# Special handling if high or low hit STOP_LOSS or ROI
|
||||
if sell.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
|
||||
# Set close_rate to stoploss
|
||||
closerate = trade.stop_loss
|
||||
elif sell.sell_type == (SellType.ROI):
|
||||
roi = self.strategy.min_roi_reached_entry(trade_dur)
|
||||
if roi is not None:
|
||||
# - (Expected abs profit + open_rate + open_fee) / (fee_close -1)
|
||||
closerate = - (trade.open_rate * roi + trade.open_rate *
|
||||
(1 + trade.fee_open)) / (trade.fee_close - 1)
|
||||
|
||||
# Use the maximum between closerate and low as we
|
||||
# cannot sell outside of a candle.
|
||||
# Applies when using {"xx": -1} as roi to force sells after xx minutes
|
||||
closerate = max(closerate, sell_row.low)
|
||||
else:
|
||||
# This should not be reached...
|
||||
closerate = sell_row.open
|
||||
else:
|
||||
closerate = sell_row.open
|
||||
closerate = self._get_close_rate(sell_row, trade, sell, trade_dur)
|
||||
|
||||
return BacktestResult(pair=pair,
|
||||
profit_percent=trade.calc_profit_percent(rate=closerate),
|
||||
profit_percent=trade.calc_profit_ratio(rate=closerate),
|
||||
profit_abs=trade.calc_profit(rate=closerate),
|
||||
open_time=buy_row.date,
|
||||
close_time=sell_row.date,
|
||||
@@ -325,7 +263,7 @@ class Backtesting:
|
||||
# no sell condition found - trade stil open at end of backtest period
|
||||
sell_row = partial_ticker[-1]
|
||||
bt_res = BacktestResult(pair=pair,
|
||||
profit_percent=trade.calc_profit_percent(rate=sell_row.open),
|
||||
profit_percent=trade.calc_profit_ratio(rate=sell_row.open),
|
||||
profit_abs=trade.calc_profit(rate=sell_row.open),
|
||||
open_time=buy_row.date,
|
||||
close_time=sell_row.date,
|
||||
@@ -345,30 +283,28 @@ class Backtesting:
|
||||
return bt_res
|
||||
return None
|
||||
|
||||
def backtest(self, args: Dict) -> DataFrame:
|
||||
def backtest(self, processed: Dict, stake_amount: float,
|
||||
start_date: arrow.Arrow, end_date: arrow.Arrow,
|
||||
max_open_trades: int = 0, position_stacking: bool = False) -> DataFrame:
|
||||
"""
|
||||
Implements backtesting functionality
|
||||
Implement backtesting functionality
|
||||
|
||||
NOTE: This method is used by Hyperopt at each iteration. Please keep it optimized.
|
||||
Of course try to not have ugly code. By some accessor are sometime slower than functions.
|
||||
Avoid, logging on this method
|
||||
Avoid extensive logging in this method and functions it calls.
|
||||
|
||||
:param args: a dict containing:
|
||||
stake_amount: btc amount to use for each trade
|
||||
processed: a processed dictionary with format {pair, data}
|
||||
max_open_trades: maximum number of concurrent trades (default: 0, disabled)
|
||||
position_stacking: do we allow position stacking? (default: False)
|
||||
:return: DataFrame
|
||||
:param processed: a processed dictionary with format {pair, data}
|
||||
:param stake_amount: amount to use for each trade
|
||||
:param start_date: backtesting timerange start datetime
|
||||
:param end_date: backtesting timerange end datetime
|
||||
:param max_open_trades: maximum number of concurrent trades, <= 0 means unlimited
|
||||
:param position_stacking: do we allow position stacking?
|
||||
:return: DataFrame with trades (results of backtesting)
|
||||
"""
|
||||
# Arguments are long and noisy, so this is commented out.
|
||||
# Uncomment if you need to debug the backtest() method.
|
||||
# logger.debug(f"Start backtest, args: {args}")
|
||||
processed = args['processed']
|
||||
stake_amount = args['stake_amount']
|
||||
max_open_trades = args.get('max_open_trades', 0)
|
||||
position_stacking = args.get('position_stacking', False)
|
||||
start_date = args['start_date']
|
||||
end_date = args['end_date']
|
||||
logger.debug(f"Run backtest, stake_amount: {stake_amount}, "
|
||||
f"start_date: {start_date}, end_date: {end_date}, "
|
||||
f"max_open_trades: {max_open_trades}, position_stacking: {position_stacking}"
|
||||
)
|
||||
trades = []
|
||||
trade_count_lock: Dict = {}
|
||||
|
||||
@@ -378,7 +314,7 @@ class Backtesting:
|
||||
lock_pair_until: Dict = {}
|
||||
# Indexes per pair, so some pairs are allowed to have a missing start.
|
||||
indexes: Dict = {}
|
||||
tmp = start_date + timedelta(minutes=self.timeframe_mins)
|
||||
tmp = start_date + timedelta(minutes=self.timeframe_min)
|
||||
|
||||
# Loop timerange and get candle for each pair at that point in time
|
||||
while tmp < end_date:
|
||||
@@ -430,23 +366,26 @@ class Backtesting:
|
||||
lock_pair_until[pair] = end_date.datetime
|
||||
|
||||
# Move time one configured time_interval ahead.
|
||||
tmp += timedelta(minutes=self.timeframe_mins)
|
||||
tmp += timedelta(minutes=self.timeframe_min)
|
||||
return DataFrame.from_records(trades, columns=BacktestResult._fields)
|
||||
|
||||
def start(self) -> None:
|
||||
"""
|
||||
Run a backtesting end-to-end
|
||||
Run backtesting end-to-end
|
||||
:return: None
|
||||
"""
|
||||
data: Dict[str, Any] = {}
|
||||
|
||||
logger.info('Using stake_currency: %s ...', self.config['stake_currency'])
|
||||
logger.info('Using stake_amount: %s ...', self.config['stake_amount'])
|
||||
|
||||
# Use max_open_trades in backtesting, except --disable-max-market-positions is set
|
||||
if self.config.get('use_max_market_positions', True):
|
||||
max_open_trades = self.config['max_open_trades']
|
||||
else:
|
||||
logger.info('Ignoring max_open_trades (--disable-max-market-positions was used) ...')
|
||||
max_open_trades = 0
|
||||
position_stacking = self.config.get('position_stacking', False)
|
||||
|
||||
data, timerange = self.load_bt_data()
|
||||
|
||||
@@ -460,8 +399,8 @@ class Backtesting:
|
||||
|
||||
# Trim startup period from analyzed dataframe
|
||||
for pair, df in preprocessed.items():
|
||||
preprocessed[pair] = history.trim_dataframe(df, timerange)
|
||||
min_date, max_date = history.get_timeframe(preprocessed)
|
||||
preprocessed[pair] = trim_dataframe(df, timerange)
|
||||
min_date, max_date = history.get_timerange(preprocessed)
|
||||
|
||||
logger.info(
|
||||
'Backtesting with data from %s up to %s (%s days)..',
|
||||
@@ -469,14 +408,12 @@ class Backtesting:
|
||||
)
|
||||
# Execute backtest and print results
|
||||
all_results[self.strategy.get_strategy_name()] = self.backtest(
|
||||
{
|
||||
'stake_amount': self.config.get('stake_amount'),
|
||||
'processed': preprocessed,
|
||||
'max_open_trades': max_open_trades,
|
||||
'position_stacking': self.config.get('position_stacking', False),
|
||||
'start_date': min_date,
|
||||
'end_date': max_date,
|
||||
}
|
||||
processed=preprocessed,
|
||||
stake_amount=self.config['stake_amount'],
|
||||
start_date=min_date,
|
||||
end_date=max_date,
|
||||
max_open_trades=max_open_trades,
|
||||
position_stacking=position_stacking,
|
||||
)
|
||||
|
||||
for strategy, results in all_results.items():
|
||||
@@ -487,16 +424,27 @@ class Backtesting:
|
||||
|
||||
print(f"Result for strategy {strategy}")
|
||||
print(' BACKTESTING REPORT '.center(133, '='))
|
||||
print(self._generate_text_table(data, results))
|
||||
print(generate_text_table(data,
|
||||
stake_currency=self.config['stake_currency'],
|
||||
max_open_trades=self.config['max_open_trades'],
|
||||
results=results))
|
||||
|
||||
print(' SELL REASON STATS '.center(133, '='))
|
||||
print(self._generate_text_table_sell_reason(data, results))
|
||||
print(generate_text_table_sell_reason(data,
|
||||
stake_currency=self.config['stake_currency'],
|
||||
max_open_trades=self.config['max_open_trades'],
|
||||
results=results))
|
||||
|
||||
print(' LEFT OPEN TRADES REPORT '.center(133, '='))
|
||||
print(self._generate_text_table(data, results.loc[results.open_at_end], True))
|
||||
print(generate_text_table(data,
|
||||
stake_currency=self.config['stake_currency'],
|
||||
max_open_trades=self.config['max_open_trades'],
|
||||
results=results.loc[results.open_at_end], skip_nan=True))
|
||||
print()
|
||||
if len(all_results) > 1:
|
||||
# Print Strategy summary table
|
||||
print(' Strategy Summary '.center(133, '='))
|
||||
print(self._generate_text_table_strategy(all_results))
|
||||
print(' STRATEGY SUMMARY '.center(133, '='))
|
||||
print(generate_text_table_strategy(self.config['stake_currency'],
|
||||
self.config['max_open_trades'],
|
||||
all_results=all_results))
|
||||
print('\nFor more details, please look at the detail tables above')
|
||||
|
@@ -6,14 +6,12 @@ This module contains the edge backtesting interface
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
from freqtrade import constants
|
||||
from freqtrade.configuration import (TimeRange, remove_credentials,
|
||||
validate_config_consistency)
|
||||
from freqtrade.edge import Edge
|
||||
from freqtrade.exchange import Exchange
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
from freqtrade.optimize.optimize_reports import generate_edge_table
|
||||
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -33,8 +31,8 @@ class EdgeCli:
|
||||
# Reset keys for edge
|
||||
remove_credentials(self.config)
|
||||
self.config['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
||||
self.exchange = Exchange(self.config)
|
||||
self.strategy = StrategyResolver(self.config).strategy
|
||||
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
|
||||
self.strategy = StrategyResolver.load_strategy(self.config)
|
||||
|
||||
validate_config_consistency(self.config)
|
||||
|
||||
@@ -42,38 +40,11 @@ class EdgeCli:
|
||||
# Set refresh_pairs to false for edge-cli (it must be true for edge)
|
||||
self.edge._refresh_pairs = False
|
||||
|
||||
self.timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||
self.edge._timerange = TimeRange.parse_timerange(None if self.config.get(
|
||||
'timerange') is None else str(self.config.get('timerange')))
|
||||
|
||||
self.edge._timerange = self.timerange
|
||||
|
||||
def _generate_edge_table(self, results: dict) -> str:
|
||||
|
||||
floatfmt = ('s', '.10g', '.2f', '.2f', '.2f', '.2f', 'd', '.d')
|
||||
tabular_data = []
|
||||
headers = ['pair', 'stoploss', 'win rate', 'risk reward ratio',
|
||||
'required risk reward', 'expectancy', 'total number of trades',
|
||||
'average duration (min)']
|
||||
|
||||
for result in results.items():
|
||||
if result[1].nb_trades > 0:
|
||||
tabular_data.append([
|
||||
result[0],
|
||||
result[1].stoploss,
|
||||
result[1].winrate,
|
||||
result[1].risk_reward_ratio,
|
||||
result[1].required_risk_reward,
|
||||
result[1].expectancy,
|
||||
result[1].nb_trades,
|
||||
round(result[1].avg_trade_duration)
|
||||
])
|
||||
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers,
|
||||
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||
|
||||
def start(self) -> None:
|
||||
result = self.edge.calculate()
|
||||
if result:
|
||||
print('') # blank line for readability
|
||||
print(self._generate_edge_table(self.edge._cached_pairs))
|
||||
print(generate_edge_table(self.edge._cached_pairs))
|
||||
|
@@ -6,7 +6,9 @@ This module contains the hyperopt logic
|
||||
|
||||
import locale
|
||||
import logging
|
||||
import random
|
||||
import sys
|
||||
import warnings
|
||||
from collections import OrderedDict
|
||||
from operator import itemgetter
|
||||
from pathlib import Path
|
||||
@@ -19,19 +21,25 @@ from colorama import init as colorama_init
|
||||
from joblib import (Parallel, cpu_count, delayed, dump, load,
|
||||
wrap_non_picklable_objects)
|
||||
from pandas import DataFrame
|
||||
from skopt import Optimizer
|
||||
from skopt.space import Dimension
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.data.history import get_timeframe, trim_dataframe
|
||||
from freqtrade.data.converter import trim_dataframe
|
||||
from freqtrade.data.history import get_timerange
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.misc import plural, round_dict
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
|
||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F4
|
||||
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F4
|
||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt # noqa: F401
|
||||
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss # noqa: F401
|
||||
from freqtrade.resolvers.hyperopt_resolver import (HyperOptLossResolver,
|
||||
HyperOptResolver)
|
||||
|
||||
# Suppress scikit-learn FutureWarnings from skopt
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning)
|
||||
from skopt import Optimizer
|
||||
from skopt.space import Dimension
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -52,14 +60,15 @@ class Hyperopt:
|
||||
hyperopt = Hyperopt(config)
|
||||
hyperopt.start()
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict[str, Any]) -> None:
|
||||
self.config = config
|
||||
|
||||
self.backtesting = Backtesting(self.config)
|
||||
|
||||
self.custom_hyperopt = HyperOptResolver(self.config).hyperopt
|
||||
self.custom_hyperopt = HyperOptResolver.load_hyperopt(self.config)
|
||||
|
||||
self.custom_hyperoptloss = HyperOptLossResolver(self.config).hyperoptloss
|
||||
self.custom_hyperoptloss = HyperOptLossResolver.load_hyperoptloss(self.config)
|
||||
self.calculate_loss = self.custom_hyperoptloss.hyperopt_loss_function
|
||||
|
||||
self.trials_file = (self.config['user_data_dir'] /
|
||||
@@ -110,11 +119,11 @@ class Hyperopt:
|
||||
self.print_json = self.config.get('print_json', False)
|
||||
|
||||
@staticmethod
|
||||
def get_lock_filename(config) -> str:
|
||||
def get_lock_filename(config: Dict[str, Any]) -> str:
|
||||
|
||||
return str(config['user_data_dir'] / 'hyperopt.lock')
|
||||
|
||||
def clean_hyperopt(self):
|
||||
def clean_hyperopt(self) -> None:
|
||||
"""
|
||||
Remove hyperopt pickle files to restart hyperopt.
|
||||
"""
|
||||
@@ -151,7 +160,7 @@ class Hyperopt:
|
||||
f"saved to '{self.trials_file}'.")
|
||||
|
||||
@staticmethod
|
||||
def _read_trials(trials_file) -> List:
|
||||
def _read_trials(trials_file: Path) -> List:
|
||||
"""
|
||||
Read hyperopt trials file
|
||||
"""
|
||||
@@ -177,13 +186,12 @@ class Hyperopt:
|
||||
result['stoploss'] = {p.name: params.get(p.name)
|
||||
for p in self.hyperopt_space('stoploss')}
|
||||
if self.has_space('trailing'):
|
||||
result['trailing'] = {p.name: params.get(p.name)
|
||||
for p in self.hyperopt_space('trailing')}
|
||||
result['trailing'] = self.custom_hyperopt.generate_trailing_params(params)
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def print_epoch_details(results, total_epochs, print_json: bool,
|
||||
def print_epoch_details(results, total_epochs: int, print_json: bool,
|
||||
no_header: bool = False, header_str: str = None) -> None:
|
||||
"""
|
||||
Display details of the hyperopt result
|
||||
@@ -212,7 +220,7 @@ class Hyperopt:
|
||||
Hyperopt._params_pretty_print(params, 'trailing', "Trailing stop:")
|
||||
|
||||
@staticmethod
|
||||
def _params_update_for_json(result_dict, params, space: str):
|
||||
def _params_update_for_json(result_dict, params, space: str) -> None:
|
||||
if space in params:
|
||||
space_params = Hyperopt._space_params(params, space)
|
||||
if space in ['buy', 'sell']:
|
||||
@@ -229,7 +237,7 @@ class Hyperopt:
|
||||
result_dict.update(space_params)
|
||||
|
||||
@staticmethod
|
||||
def _params_pretty_print(params, space: str, header: str):
|
||||
def _params_pretty_print(params, space: str, header: str) -> None:
|
||||
if space in params:
|
||||
space_params = Hyperopt._space_params(params, space, 5)
|
||||
if space == 'stoploss':
|
||||
@@ -245,7 +253,7 @@ class Hyperopt:
|
||||
return round_dict(d, r) if r else d
|
||||
|
||||
@staticmethod
|
||||
def is_best_loss(results, current_best_loss) -> bool:
|
||||
def is_best_loss(results, current_best_loss: float) -> bool:
|
||||
return results['loss'] < current_best_loss
|
||||
|
||||
def print_results(self, results) -> None:
|
||||
@@ -353,27 +361,25 @@ class Hyperopt:
|
||||
self.backtesting.strategy.stoploss = params_dict['stoploss']
|
||||
|
||||
if self.has_space('trailing'):
|
||||
self.backtesting.strategy.trailing_stop = params_dict['trailing_stop']
|
||||
self.backtesting.strategy.trailing_stop_positive = \
|
||||
params_dict['trailing_stop_positive']
|
||||
d = self.custom_hyperopt.generate_trailing_params(params_dict)
|
||||
self.backtesting.strategy.trailing_stop = d['trailing_stop']
|
||||
self.backtesting.strategy.trailing_stop_positive = d['trailing_stop_positive']
|
||||
self.backtesting.strategy.trailing_stop_positive_offset = \
|
||||
params_dict['trailing_stop_positive_offset']
|
||||
d['trailing_stop_positive_offset']
|
||||
self.backtesting.strategy.trailing_only_offset_is_reached = \
|
||||
params_dict['trailing_only_offset_is_reached']
|
||||
d['trailing_only_offset_is_reached']
|
||||
|
||||
processed = load(self.tickerdata_pickle)
|
||||
|
||||
min_date, max_date = get_timeframe(processed)
|
||||
min_date, max_date = get_timerange(processed)
|
||||
|
||||
backtesting_results = self.backtesting.backtest(
|
||||
{
|
||||
'stake_amount': self.config['stake_amount'],
|
||||
'processed': processed,
|
||||
'max_open_trades': self.max_open_trades,
|
||||
'position_stacking': self.position_stacking,
|
||||
'start_date': min_date,
|
||||
'end_date': max_date,
|
||||
}
|
||||
processed=processed,
|
||||
stake_amount=self.config['stake_amount'],
|
||||
start_date=min_date,
|
||||
end_date=max_date,
|
||||
max_open_trades=self.max_open_trades,
|
||||
position_stacking=self.position_stacking,
|
||||
)
|
||||
return self._get_results_dict(backtesting_results, min_date, max_date,
|
||||
params_dict, params_details)
|
||||
@@ -421,7 +427,7 @@ class Hyperopt:
|
||||
f"Avg profit {results_metrics['avg_profit']: 6.2f}%. "
|
||||
f"Total profit {results_metrics['total_profit']: 11.8f} {stake_cur} "
|
||||
f"({results_metrics['profit']: 7.2f}\N{GREEK CAPITAL LETTER SIGMA}%). "
|
||||
f"Avg duration {results_metrics['duration']:5.1f} mins."
|
||||
f"Avg duration {results_metrics['duration']:5.1f} min."
|
||||
).encode(locale.getpreferredencoding(), 'replace').decode('utf-8')
|
||||
|
||||
def get_optimizer(self, dimensions: List[Dimension], cpu_count) -> Optimizer:
|
||||
@@ -431,10 +437,10 @@ class Hyperopt:
|
||||
acq_optimizer="auto",
|
||||
n_initial_points=INITIAL_POINTS,
|
||||
acq_optimizer_kwargs={'n_jobs': cpu_count},
|
||||
random_state=self.config.get('hyperopt_random_state', None),
|
||||
random_state=self.random_state,
|
||||
)
|
||||
|
||||
def fix_optimizer_models_list(self):
|
||||
def fix_optimizer_models_list(self) -> None:
|
||||
"""
|
||||
WORKAROUND: Since skopt is not actively supported, this resolves problems with skopt
|
||||
memory usage, see also: https://github.com/scikit-optimize/scikit-optimize/pull/746
|
||||
@@ -456,7 +462,7 @@ class Hyperopt:
|
||||
wrap_non_picklable_objects(self.generate_optimizer))(v, i) for v in asked)
|
||||
|
||||
@staticmethod
|
||||
def load_previous_results(trials_file) -> List:
|
||||
def load_previous_results(trials_file: Path) -> List:
|
||||
"""
|
||||
Load data for epochs from the file if we have one
|
||||
"""
|
||||
@@ -470,7 +476,13 @@ class Hyperopt:
|
||||
logger.info(f"Loaded {len(trials)} previous evaluations from disk.")
|
||||
return trials
|
||||
|
||||
def _set_random_state(self, random_state: Optional[int]) -> int:
|
||||
return random_state or random.randint(1, 2**16 - 1)
|
||||
|
||||
def start(self) -> None:
|
||||
self.random_state = self._set_random_state(self.config.get('hyperopt_random_state', None))
|
||||
logger.info(f"Using optimizer random state: {self.random_state}")
|
||||
|
||||
data, timerange = self.backtesting.load_bt_data()
|
||||
|
||||
preprocessed = self.backtesting.strategy.tickerdata_to_dataframe(data)
|
||||
@@ -478,7 +490,7 @@ class Hyperopt:
|
||||
# Trim startup period from analyzed dataframe
|
||||
for pair, df in preprocessed.items():
|
||||
preprocessed[pair] = trim_dataframe(df, timerange)
|
||||
min_date, max_date = get_timeframe(data)
|
||||
min_date, max_date = get_timerange(data)
|
||||
|
||||
logger.info(
|
||||
'Hyperopting with data from %s up to %s (%s days)..',
|
||||
|
@@ -4,17 +4,15 @@ This module defines the interface to apply for hyperopt
|
||||
"""
|
||||
import logging
|
||||
import math
|
||||
|
||||
from abc import ABC
|
||||
from typing import Dict, Any, Callable, List
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from skopt.space import Categorical, Dimension, Integer, Real
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import timeframe_to_minutes
|
||||
from freqtrade.misc import round_dict
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -106,7 +104,7 @@ class IHyperOpt(ABC):
|
||||
roi_t_alpha = 1.0
|
||||
roi_p_alpha = 1.0
|
||||
|
||||
timeframe_mins = timeframe_to_minutes(IHyperOpt.ticker_interval)
|
||||
timeframe_min = timeframe_to_minutes(IHyperOpt.ticker_interval)
|
||||
|
||||
# We define here limits for the ROI space parameters automagically adapted to the
|
||||
# timeframe used by the bot:
|
||||
@@ -117,8 +115,8 @@ class IHyperOpt(ABC):
|
||||
#
|
||||
# The scaling is designed so that it maps exactly to the legacy Freqtrade roi_space()
|
||||
# method for the 5m ticker interval.
|
||||
roi_t_scale = timeframe_mins / 5
|
||||
roi_p_scale = math.log1p(timeframe_mins) / math.log1p(5)
|
||||
roi_t_scale = timeframe_min / 5
|
||||
roi_p_scale = math.log1p(timeframe_min) / math.log1p(5)
|
||||
roi_limits = {
|
||||
'roi_t1_min': int(10 * roi_t_scale * roi_t_alpha),
|
||||
'roi_t1_max': int(120 * roi_t_scale * roi_t_alpha),
|
||||
@@ -174,6 +172,19 @@ class IHyperOpt(ABC):
|
||||
Real(-0.35, -0.02, name='stoploss'),
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def generate_trailing_params(params: Dict) -> Dict:
|
||||
"""
|
||||
Create dict with trailing stop parameters.
|
||||
"""
|
||||
return {
|
||||
'trailing_stop': params['trailing_stop'],
|
||||
'trailing_stop_positive': params['trailing_stop_positive'],
|
||||
'trailing_stop_positive_offset': (params['trailing_stop_positive'] +
|
||||
params['trailing_stop_positive_offset_p1']),
|
||||
'trailing_only_offset_is_reached': params['trailing_only_offset_is_reached'],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def trailing_space() -> List[Dimension]:
|
||||
"""
|
||||
@@ -190,8 +201,15 @@ class IHyperOpt(ABC):
|
||||
# other 'trailing' hyperspace parameters.
|
||||
Categorical([True], name='trailing_stop'),
|
||||
|
||||
Real(0.02, 0.35, name='trailing_stop_positive'),
|
||||
Real(0.01, 0.1, name='trailing_stop_positive_offset'),
|
||||
Real(0.01, 0.35, name='trailing_stop_positive'),
|
||||
|
||||
# 'trailing_stop_positive_offset' should be greater than 'trailing_stop_positive',
|
||||
# so this intermediate parameter is used as the value of the difference between
|
||||
# them. The value of the 'trailing_stop_positive_offset' is constructed in the
|
||||
# generate_trailing_params() method.
|
||||
# This is similar to the hyperspace dimensions used for constructing the ROI tables.
|
||||
Real(0.001, 0.1, name='trailing_stop_positive_offset_p1'),
|
||||
|
||||
Categorical([True, False], name='trailing_only_offset_is_reached'),
|
||||
]
|
||||
|
||||
|
@@ -28,18 +28,19 @@ class SharpeHyperOptLoss(IHyperOptLoss):
|
||||
|
||||
Uses Sharpe Ratio calculation.
|
||||
"""
|
||||
total_profit = results.profit_percent
|
||||
total_profit = results["profit_percent"]
|
||||
days_period = (max_date - min_date).days
|
||||
|
||||
# adding slippage of 0.1% per trade
|
||||
total_profit = total_profit - 0.0005
|
||||
expected_yearly_return = total_profit.sum() / days_period
|
||||
expected_returns_mean = total_profit.sum() / days_period
|
||||
up_stdev = np.std(total_profit)
|
||||
|
||||
if (np.std(total_profit) != 0.):
|
||||
sharp_ratio = expected_yearly_return / np.std(total_profit) * np.sqrt(365)
|
||||
sharp_ratio = expected_returns_mean / up_stdev * np.sqrt(365)
|
||||
else:
|
||||
# Define high (negative) sharpe ratio to be clear that this is NOT optimal.
|
||||
sharp_ratio = -20.
|
||||
|
||||
# print(expected_yearly_return, np.std(total_profit), sharp_ratio)
|
||||
# print(expected_returns_mean, up_stdev, sharp_ratio)
|
||||
return -sharp_ratio
|
||||
|
62
freqtrade/optimize/hyperopt_loss_sharpe_daily.py
Normal file
62
freqtrade/optimize/hyperopt_loss_sharpe_daily.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
SharpeHyperOptLossDaily
|
||||
|
||||
This module defines the alternative HyperOptLoss class which can be used for
|
||||
Hyperoptimization.
|
||||
"""
|
||||
import math
|
||||
from datetime import datetime
|
||||
|
||||
from pandas import DataFrame, date_range
|
||||
|
||||
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
||||
|
||||
|
||||
class SharpeHyperOptLossDaily(IHyperOptLoss):
|
||||
"""
|
||||
Defines the loss function for hyperopt.
|
||||
|
||||
This implementation uses the Sharpe Ratio calculation.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
||||
min_date: datetime, max_date: datetime,
|
||||
*args, **kwargs) -> float:
|
||||
"""
|
||||
Objective function, returns smaller number for more optimal results.
|
||||
|
||||
Uses Sharpe Ratio calculation.
|
||||
"""
|
||||
resample_freq = '1D'
|
||||
slippage_per_trade_ratio = 0.0005
|
||||
days_in_year = 365
|
||||
annual_risk_free_rate = 0.0
|
||||
risk_free_rate = annual_risk_free_rate / days_in_year
|
||||
|
||||
# apply slippage per trade to profit_percent
|
||||
results.loc[:, 'profit_percent_after_slippage'] = \
|
||||
results['profit_percent'] - slippage_per_trade_ratio
|
||||
|
||||
# create the index within the min_date and end max_date
|
||||
t_index = date_range(start=min_date, end=max_date, freq=resample_freq,
|
||||
normalize=True)
|
||||
|
||||
sum_daily = (
|
||||
results.resample(resample_freq, on='close_time').agg(
|
||||
{"profit_percent_after_slippage": sum}).reindex(t_index).fillna(0)
|
||||
)
|
||||
|
||||
total_profit = sum_daily["profit_percent_after_slippage"] - risk_free_rate
|
||||
expected_returns_mean = total_profit.mean()
|
||||
up_stdev = total_profit.std()
|
||||
|
||||
if (up_stdev != 0.):
|
||||
sharp_ratio = expected_returns_mean / up_stdev * math.sqrt(days_in_year)
|
||||
else:
|
||||
# Define high (negative) sharpe ratio to be clear that this is NOT optimal.
|
||||
sharp_ratio = -20.
|
||||
|
||||
# print(t_index, sum_daily, total_profit)
|
||||
# print(risk_free_rate, expected_returns_mean, up_stdev, sharp_ratio)
|
||||
return -sharp_ratio
|
175
freqtrade/optimize/optimize_reports.py
Normal file
175
freqtrade/optimize/optimize_reports.py
Normal file
@@ -0,0 +1,175 @@
|
||||
from datetime import timedelta
|
||||
from typing import Dict
|
||||
|
||||
from pandas import DataFrame
|
||||
from tabulate import tabulate
|
||||
|
||||
|
||||
def generate_text_table(data: Dict[str, Dict], stake_currency: str, max_open_trades: int,
|
||||
results: DataFrame, skip_nan: bool = False) -> str:
|
||||
"""
|
||||
Generates and returns a text table for the given backtest data and the results dataframe
|
||||
:param data: Dict of <pair: dataframe> containing data that was used during backtesting.
|
||||
:param stake_currency: stake-currency - used to correctly name headers
|
||||
:param max_open_trades: Maximum allowed open trades
|
||||
:param results: Dataframe containing the backtest results
|
||||
:param skip_nan: Print "left open" open trades
|
||||
:return: pretty printed table with tabulate as string
|
||||
"""
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = [
|
||||
'Pair',
|
||||
'Buys',
|
||||
'Avg Profit %',
|
||||
'Cum Profit %',
|
||||
f'Tot Profit {stake_currency}',
|
||||
'Tot Profit %',
|
||||
'Avg Duration',
|
||||
'Wins',
|
||||
'Draws',
|
||||
'Losses'
|
||||
]
|
||||
for pair in data:
|
||||
result = results[results.pair == pair]
|
||||
if skip_nan and result.profit_abs.isnull().all():
|
||||
continue
|
||||
|
||||
tabular_data.append([
|
||||
pair,
|
||||
len(result.index),
|
||||
result.profit_percent.mean() * 100.0,
|
||||
result.profit_percent.sum() * 100.0,
|
||||
result.profit_abs.sum(),
|
||||
result.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(result.trade_duration.mean()))) if not result.empty else '0:00',
|
||||
len(result[result.profit_abs > 0]),
|
||||
len(result[result.profit_abs == 0]),
|
||||
len(result[result.profit_abs < 0])
|
||||
])
|
||||
|
||||
# Append Total
|
||||
tabular_data.append([
|
||||
'TOTAL',
|
||||
len(results.index),
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_percent.sum() * 100.0,
|
||||
results.profit_abs.sum(),
|
||||
results.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(results.trade_duration.mean()))) if not results.empty else '0:00',
|
||||
len(results[results.profit_abs > 0]),
|
||||
len(results[results.profit_abs == 0]),
|
||||
len(results[results.profit_abs < 0])
|
||||
])
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers,
|
||||
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||
|
||||
|
||||
def generate_text_table_sell_reason(
|
||||
data: Dict[str, Dict], stake_currency: str, max_open_trades: int, results: DataFrame
|
||||
) -> str:
|
||||
"""
|
||||
Generate small table outlining Backtest results
|
||||
:param data: Dict of <pair: dataframe> containing data that was used during backtesting.
|
||||
:param results: Dataframe containing the backtest results
|
||||
:return: pretty printed table with tabulate as string
|
||||
"""
|
||||
tabular_data = []
|
||||
headers = [
|
||||
"Sell Reason",
|
||||
"Sells",
|
||||
"Wins",
|
||||
"Draws",
|
||||
"Losses",
|
||||
"Avg Profit %",
|
||||
"Cum Profit %",
|
||||
f"Tot Profit {stake_currency}",
|
||||
"Tot Profit %",
|
||||
]
|
||||
for reason, count in results['sell_reason'].value_counts().iteritems():
|
||||
result = results.loc[results['sell_reason'] == reason]
|
||||
wins = len(result[result['profit_abs'] > 0])
|
||||
draws = len(result[result['profit_abs'] == 0])
|
||||
loss = len(result[result['profit_abs'] < 0])
|
||||
profit_mean = round(result['profit_percent'].mean() * 100.0, 2)
|
||||
profit_sum = round(result["profit_percent"].sum() * 100.0, 2)
|
||||
profit_tot = result['profit_abs'].sum()
|
||||
profit_percent_tot = round(result['profit_percent'].sum() * 100.0 / max_open_trades, 2)
|
||||
tabular_data.append(
|
||||
[
|
||||
reason.value,
|
||||
count,
|
||||
wins,
|
||||
draws,
|
||||
loss,
|
||||
profit_mean,
|
||||
profit_sum,
|
||||
profit_tot,
|
||||
profit_percent_tot,
|
||||
]
|
||||
)
|
||||
return tabulate(tabular_data, headers=headers, tablefmt="pipe")
|
||||
|
||||
|
||||
def generate_text_table_strategy(stake_currency: str, max_open_trades: str,
|
||||
all_results: Dict) -> str:
|
||||
"""
|
||||
Generate summary table per strategy
|
||||
:param stake_currency: stake-currency - used to correctly name headers
|
||||
:param max_open_trades: Maximum allowed open trades used for backtest
|
||||
:param all_results: Dict of <Strategyname: BacktestResult> containing results for all strategies
|
||||
:return: pretty printed table with tabulate as string
|
||||
"""
|
||||
|
||||
floatfmt = ('s', 'd', '.2f', '.2f', '.8f', '.2f', 'd', '.1f', '.1f')
|
||||
tabular_data = []
|
||||
headers = ['Strategy', 'Buys', 'Avg Profit %', 'Cum Profit %',
|
||||
f'Tot Profit {stake_currency}', 'Tot Profit %', 'Avg Duration',
|
||||
'Wins', 'Draws', 'Losses']
|
||||
for strategy, results in all_results.items():
|
||||
tabular_data.append([
|
||||
strategy,
|
||||
len(results.index),
|
||||
results.profit_percent.mean() * 100.0,
|
||||
results.profit_percent.sum() * 100.0,
|
||||
results.profit_abs.sum(),
|
||||
results.profit_percent.sum() * 100.0 / max_open_trades,
|
||||
str(timedelta(
|
||||
minutes=round(results.trade_duration.mean()))) if not results.empty else '0:00',
|
||||
len(results[results.profit_abs > 0]),
|
||||
len(results[results.profit_abs == 0]),
|
||||
len(results[results.profit_abs < 0])
|
||||
])
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers,
|
||||
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
||||
|
||||
|
||||
def generate_edge_table(results: dict) -> str:
|
||||
|
||||
floatfmt = ('s', '.10g', '.2f', '.2f', '.2f', '.2f', 'd', '.d')
|
||||
tabular_data = []
|
||||
headers = ['Pair', 'Stoploss', 'Win Rate', 'Risk Reward Ratio',
|
||||
'Required Risk Reward', 'Expectancy', 'Total Number of Trades',
|
||||
'Average Duration (min)']
|
||||
|
||||
for result in results.items():
|
||||
if result[1].nb_trades > 0:
|
||||
tabular_data.append([
|
||||
result[0],
|
||||
result[1].stoploss,
|
||||
result[1].winrate,
|
||||
result[1].risk_reward_ratio,
|
||||
result[1].required_risk_reward,
|
||||
result[1].expectancy,
|
||||
result[1].nb_trades,
|
||||
round(result[1].avg_trade_duration)
|
||||
])
|
||||
|
||||
# Ignore type as floatfmt does allow tuples but mypy does not know that
|
||||
return tabulate(tabular_data, headers=headers,
|
||||
floatfmt=floatfmt, tablefmt="pipe") # type: ignore
|
@@ -7,7 +7,7 @@ Provides lists as configured in config.json
|
||||
import logging
|
||||
from abc import ABC, abstractmethod, abstractproperty
|
||||
from copy import deepcopy
|
||||
from typing import Dict, List
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from freqtrade.exchange import market_is_active
|
||||
|
||||
@@ -16,7 +16,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
class IPairList(ABC):
|
||||
|
||||
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||
def __init__(self, exchange, pairlistmanager,
|
||||
config: Dict[str, Any], pairlistconfig: Dict[str, Any],
|
||||
pairlist_pos: int) -> None:
|
||||
"""
|
||||
:param exchange: Exchange instance
|
||||
|
@@ -35,8 +35,8 @@ class PrecisionFilter(IPairList):
|
||||
"""
|
||||
stop_price = ticker['ask'] * stoploss
|
||||
# Adjust stop-prices to precision
|
||||
sp = self._exchange.symbol_price_prec(ticker["symbol"], stop_price)
|
||||
stop_gap_price = self._exchange.symbol_price_prec(ticker["symbol"], stop_price * 0.99)
|
||||
sp = self._exchange.price_to_precision(ticker["symbol"], stop_price)
|
||||
stop_gap_price = self._exchange.price_to_precision(ticker["symbol"], stop_price * 0.99)
|
||||
logger.debug(f"{ticker['symbol']} - {sp} : {stop_gap_price}")
|
||||
if sp <= stop_gap_price:
|
||||
logger.info(f"Removed {ticker['symbol']} from whitelist, "
|
||||
@@ -48,10 +48,10 @@ class PrecisionFilter(IPairList):
|
||||
"""
|
||||
Filters and sorts pairlists and assigns and returns them again.
|
||||
"""
|
||||
stoploss = None
|
||||
if self._config.get('stoploss') is not None:
|
||||
stoploss = self._config.get('stoploss')
|
||||
if stoploss is not None:
|
||||
# Precalculate sanitized stoploss value to avoid recalculation for every pair
|
||||
stoploss = 1 - abs(self._config.get('stoploss'))
|
||||
stoploss = 1 - abs(stoploss)
|
||||
# Copy list since we're modifying this list
|
||||
for p in deepcopy(pairlist):
|
||||
ticker = tickers.get(p)
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Dict, List
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
|
||||
@@ -9,7 +9,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
class PriceFilter(IPairList):
|
||||
|
||||
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||
def __init__(self, exchange, pairlistmanager,
|
||||
config: Dict[str, Any], pairlistconfig: Dict[str, Any],
|
||||
pairlist_pos: int) -> None:
|
||||
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||
|
||||
|
59
freqtrade/pairlist/SpreadFilter.py
Normal file
59
freqtrade/pairlist/SpreadFilter.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Dict, List
|
||||
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SpreadFilter(IPairList):
|
||||
|
||||
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||
pairlist_pos: int) -> None:
|
||||
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||
|
||||
self._max_spread_ratio = pairlistconfig.get('max_spread_ratio', 0.005)
|
||||
|
||||
@property
|
||||
def needstickers(self) -> bool:
|
||||
"""
|
||||
Boolean property defining if tickers are necessary.
|
||||
If no Pairlist requries tickers, an empty List is passed
|
||||
as tickers argument to filter_pairlist
|
||||
"""
|
||||
return True
|
||||
|
||||
def short_desc(self) -> str:
|
||||
"""
|
||||
Short whitelist method description - used for startup-messages
|
||||
"""
|
||||
return (f"{self.name} - Filtering pairs with ask/bid diff above "
|
||||
f"{self._max_spread_ratio * 100}%.")
|
||||
|
||||
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||
|
||||
"""
|
||||
Filters and sorts pairlist and returns the whitelist 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 whitelist
|
||||
"""
|
||||
# Copy list since we're modifying this list
|
||||
|
||||
spread = None
|
||||
for p in deepcopy(pairlist):
|
||||
ticker = tickers.get(p)
|
||||
assert ticker is not None
|
||||
if 'bid' in ticker and 'ask' in ticker:
|
||||
spread = 1 - ticker['bid'] / ticker['ask']
|
||||
if not ticker or spread > self._max_spread_ratio:
|
||||
logger.info(f"Removed {ticker['symbol']} from whitelist, "
|
||||
f"because spread {spread * 100:.3f}% >"
|
||||
f"{self._max_spread_ratio * 100}%")
|
||||
pairlist.remove(p)
|
||||
else:
|
||||
pairlist.remove(p)
|
||||
|
||||
return pairlist
|
@@ -6,9 +6,9 @@ Provides lists as configured in config.json
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Dict, List
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -18,7 +18,7 @@ SORT_VALUES = ['askVolume', 'bidVolume', 'quoteVolume']
|
||||
|
||||
class VolumePairList(IPairList):
|
||||
|
||||
def __init__(self, exchange, pairlistmanager, config, pairlistconfig: dict,
|
||||
def __init__(self, exchange, pairlistmanager, config: Dict[str, Any], pairlistconfig: dict,
|
||||
pairlist_pos: int) -> None:
|
||||
super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos)
|
||||
|
||||
@@ -28,6 +28,7 @@ class VolumePairList(IPairList):
|
||||
'for "pairlist.config.number_assets"')
|
||||
self._number_pairs = self._pairlistconfig['number_assets']
|
||||
self._sort_key = self._pairlistconfig.get('sort_key', 'quoteVolume')
|
||||
self._min_value = self._pairlistconfig.get('min_value', 0)
|
||||
self.refresh_period = self._pairlistconfig.get('refresh_period', 1800)
|
||||
|
||||
if not self._exchange.exchange_has('fetchTickers'):
|
||||
@@ -73,11 +74,13 @@ class VolumePairList(IPairList):
|
||||
tickers,
|
||||
self._config['stake_currency'],
|
||||
self._sort_key,
|
||||
self._min_value
|
||||
)
|
||||
else:
|
||||
return pairlist
|
||||
|
||||
def _gen_pair_whitelist(self, pairlist, tickers, base_currency: str, key: str) -> List[str]:
|
||||
def _gen_pair_whitelist(self, pairlist: List[str], tickers: Dict,
|
||||
base_currency: str, key: str, min_val: int) -> List[str]:
|
||||
"""
|
||||
Updates the whitelist with with a dynamically generated list
|
||||
:param base_currency: base currency as str
|
||||
@@ -96,6 +99,9 @@ class VolumePairList(IPairList):
|
||||
# If other pairlist is in front, use the incomming pairlist.
|
||||
filtered_tickers = [v for k, v in tickers.items() if k in pairlist]
|
||||
|
||||
if min_val > 0:
|
||||
filtered_tickers = list(filter(lambda t: t[key] > min_val, filtered_tickers))
|
||||
|
||||
sorted_tickers = sorted(filtered_tickers, reverse=True, key=lambda t: t[key])
|
||||
|
||||
# Validate whitelist to only have active market pairs
|
||||
|
@@ -4,11 +4,12 @@ Static List provider
|
||||
Provides lists as configured in config.json
|
||||
|
||||
"""
|
||||
from cachetools import TTLCache, cached
|
||||
import logging
|
||||
from typing import Dict, List
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from cachetools import TTLCache, cached
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.pairlist.IPairList import IPairList
|
||||
from freqtrade.resolvers import PairListResolver
|
||||
|
||||
@@ -28,13 +29,13 @@ class PairListManager():
|
||||
if 'method' not in pl:
|
||||
logger.warning(f"No method in {pl}")
|
||||
continue
|
||||
pairl = PairListResolver(pl.get('method'),
|
||||
pairl = PairListResolver.load_pairlist(pl.get('method'),
|
||||
exchange=exchange,
|
||||
pairlistmanager=self,
|
||||
config=config,
|
||||
pairlistconfig=pl,
|
||||
pairlist_pos=len(self._pairlists)
|
||||
).pairlist
|
||||
)
|
||||
self._tickers_needed = pairl.needstickers or self._tickers_needed
|
||||
self._pairlists.append(pairl)
|
||||
|
||||
|
@@ -16,7 +16,7 @@ from sqlalchemy.orm.scoping import scoped_session
|
||||
from sqlalchemy.orm.session import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -64,11 +64,11 @@ def init(db_url: str, clean_open_orders: bool = False) -> None:
|
||||
clean_dry_run_db()
|
||||
|
||||
|
||||
def has_column(columns, searchname: str) -> bool:
|
||||
def has_column(columns: List, searchname: str) -> bool:
|
||||
return len(list(filter(lambda x: x["name"] == searchname, columns))) == 1
|
||||
|
||||
|
||||
def get_column_def(columns, column: str, default: str) -> str:
|
||||
def get_column_def(columns: List, column: str, default: str) -> str:
|
||||
return default if not has_column(columns, column) else column
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ def check_migrate(engine) -> None:
|
||||
logger.debug(f'trying {table_back_name}')
|
||||
|
||||
# Check for latest column
|
||||
if not has_column(cols, 'stop_loss_pct'):
|
||||
if not has_column(cols, 'open_trade_price'):
|
||||
logger.info(f'Running database migration - backup available as {table_back_name}')
|
||||
|
||||
fee_open = get_column_def(cols, 'fee_open', 'fee')
|
||||
@@ -104,6 +104,8 @@ def check_migrate(engine) -> None:
|
||||
sell_reason = get_column_def(cols, 'sell_reason', 'null')
|
||||
strategy = get_column_def(cols, 'strategy', 'null')
|
||||
ticker_interval = get_column_def(cols, 'ticker_interval', 'null')
|
||||
open_trade_price = get_column_def(cols, 'open_trade_price',
|
||||
f'amount * open_rate * (1 + {fee_open})')
|
||||
|
||||
# Schema migration necessary
|
||||
engine.execute(f"alter table trades rename to {table_back_name}")
|
||||
@@ -121,7 +123,7 @@ def check_migrate(engine) -> None:
|
||||
stop_loss, stop_loss_pct, initial_stop_loss, initial_stop_loss_pct,
|
||||
stoploss_order_id, stoploss_last_update,
|
||||
max_rate, min_rate, sell_reason, strategy,
|
||||
ticker_interval
|
||||
ticker_interval, open_trade_price
|
||||
)
|
||||
select id, lower(exchange),
|
||||
case
|
||||
@@ -140,7 +142,8 @@ def check_migrate(engine) -> None:
|
||||
{initial_stop_loss_pct} initial_stop_loss_pct,
|
||||
{stoploss_order_id} stoploss_order_id, {stoploss_last_update} stoploss_last_update,
|
||||
{max_rate} max_rate, {min_rate} min_rate, {sell_reason} sell_reason,
|
||||
{strategy} strategy, {ticker_interval} ticker_interval
|
||||
{strategy} strategy, {ticker_interval} ticker_interval,
|
||||
{open_trade_price} open_trade_price
|
||||
from {table_back_name}
|
||||
""")
|
||||
|
||||
@@ -182,6 +185,8 @@ class Trade(_DECL_BASE):
|
||||
fee_close = Column(Float, nullable=False, default=0.0)
|
||||
open_rate = Column(Float)
|
||||
open_rate_requested = Column(Float)
|
||||
# open_trade_price - calcuated via _calc_open_trade_price
|
||||
open_trade_price = Column(Float)
|
||||
close_rate = Column(Float)
|
||||
close_rate_requested = Column(Float)
|
||||
close_profit = Column(Float)
|
||||
@@ -210,6 +215,10 @@ class Trade(_DECL_BASE):
|
||||
strategy = Column(String, nullable=True)
|
||||
ticker_interval = Column(Integer, nullable=True)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.recalc_open_trade_price()
|
||||
|
||||
def __repr__(self):
|
||||
open_since = self.open_date.strftime('%Y-%m-%d %H:%M:%S') if self.is_open else 'closed'
|
||||
|
||||
@@ -237,14 +246,15 @@ class Trade(_DECL_BASE):
|
||||
if self.initial_stop_loss_pct else None),
|
||||
}
|
||||
|
||||
def adjust_min_max_rates(self, current_price: float):
|
||||
def adjust_min_max_rates(self, current_price: float) -> None:
|
||||
"""
|
||||
Adjust the max_rate and min_rate.
|
||||
"""
|
||||
self.max_rate = max(current_price, self.max_rate or self.open_rate)
|
||||
self.min_rate = min(current_price, self.min_rate or self.open_rate)
|
||||
|
||||
def adjust_stop_loss(self, current_price: float, stoploss: float, initial: bool = False):
|
||||
def adjust_stop_loss(self, current_price: float, stoploss: float,
|
||||
initial: bool = False) -> None:
|
||||
"""
|
||||
This adjusts the stop loss to it's most recently observed setting
|
||||
:param current_price: Current rate the asset is traded
|
||||
@@ -302,15 +312,16 @@ class Trade(_DECL_BASE):
|
||||
# Update open rate and actual amount
|
||||
self.open_rate = Decimal(order['price'])
|
||||
self.amount = Decimal(order['amount'])
|
||||
self.recalc_open_trade_price()
|
||||
logger.info('%s_BUY has been fulfilled for %s.', order_type.upper(), self)
|
||||
self.open_order_id = None
|
||||
elif order_type in ('market', 'limit') and order['side'] == 'sell':
|
||||
self.close(order['price'])
|
||||
logger.info('%s_SELL has been fulfilled for %s.', order_type.upper(), self)
|
||||
elif order_type == 'stop_loss_limit':
|
||||
elif order_type in ('stop_loss_limit', 'stop-loss'):
|
||||
self.stoploss_order_id = None
|
||||
self.close_rate_requested = self.stop_loss
|
||||
logger.info('STOP_LOSS_LIMIT is hit for %s.', self)
|
||||
logger.info('%s is hit for %s.', order_type.upper(), self)
|
||||
self.close(order['average'])
|
||||
else:
|
||||
raise ValueError(f'Unknown order type: {order_type}')
|
||||
@@ -322,7 +333,7 @@ class Trade(_DECL_BASE):
|
||||
and marks trade as closed
|
||||
"""
|
||||
self.close_rate = Decimal(rate)
|
||||
self.close_profit = self.calc_profit_percent()
|
||||
self.close_profit = self.calc_profit_ratio()
|
||||
self.close_date = datetime.utcnow()
|
||||
self.is_open = False
|
||||
self.open_order_id = None
|
||||
@@ -331,17 +342,22 @@ class Trade(_DECL_BASE):
|
||||
self
|
||||
)
|
||||
|
||||
def calc_open_trade_price(self, fee: Optional[float] = None) -> float:
|
||||
def _calc_open_trade_price(self) -> float:
|
||||
"""
|
||||
Calculate the open_rate including fee.
|
||||
:param fee: fee to use on the open rate (optional).
|
||||
If rate is not set self.fee will be used
|
||||
Calculate the open_rate including open_fee.
|
||||
:return: Price in of the open trade incl. Fees
|
||||
"""
|
||||
buy_trade = (Decimal(self.amount) * Decimal(self.open_rate))
|
||||
fees = buy_trade * Decimal(fee or self.fee_open)
|
||||
buy_trade = Decimal(self.amount) * Decimal(self.open_rate)
|
||||
fees = buy_trade * Decimal(self.fee_open)
|
||||
return float(buy_trade + fees)
|
||||
|
||||
def recalc_open_trade_price(self) -> None:
|
||||
"""
|
||||
Recalculate open_trade_price.
|
||||
Must be called whenever open_rate or fee_open is changed.
|
||||
"""
|
||||
self.open_trade_price = self._calc_open_trade_price()
|
||||
|
||||
def calc_close_trade_price(self, rate: Optional[float] = None,
|
||||
fee: Optional[float] = None) -> float:
|
||||
"""
|
||||
@@ -355,7 +371,7 @@ class Trade(_DECL_BASE):
|
||||
if rate is None and not self.close_rate:
|
||||
return 0.0
|
||||
|
||||
sell_trade = (Decimal(self.amount) * Decimal(rate or self.close_rate))
|
||||
sell_trade = Decimal(self.amount) * Decimal(rate or self.close_rate)
|
||||
fees = sell_trade * Decimal(fee or self.fee_close)
|
||||
return float(sell_trade - fees)
|
||||
|
||||
@@ -369,29 +385,27 @@ class Trade(_DECL_BASE):
|
||||
If rate is not set self.close_rate will be used
|
||||
:return: profit in stake currency as float
|
||||
"""
|
||||
open_trade_price = self.calc_open_trade_price()
|
||||
close_trade_price = self.calc_close_trade_price(
|
||||
rate=(rate or self.close_rate),
|
||||
fee=(fee or self.fee_close)
|
||||
)
|
||||
profit = close_trade_price - open_trade_price
|
||||
profit = close_trade_price - self.open_trade_price
|
||||
return float(f"{profit:.8f}")
|
||||
|
||||
def calc_profit_percent(self, rate: Optional[float] = None,
|
||||
def calc_profit_ratio(self, rate: Optional[float] = None,
|
||||
fee: Optional[float] = None) -> float:
|
||||
"""
|
||||
Calculates the profit in percentage (including fee).
|
||||
Calculates the profit as ratio (including fee).
|
||||
:param rate: rate to compare with (optional).
|
||||
If rate is not set self.close_rate will be used
|
||||
:param fee: fee to use on the close rate (optional).
|
||||
:return: profit in percentage as float
|
||||
:return: profit ratio as float
|
||||
"""
|
||||
open_trade_price = self.calc_open_trade_price()
|
||||
close_trade_price = self.calc_close_trade_price(
|
||||
rate=(rate or self.close_rate),
|
||||
fee=(fee or self.fee_close)
|
||||
)
|
||||
profit_percent = (close_trade_price / open_trade_price) - 1
|
||||
profit_percent = (close_trade_price / self.open_trade_price) - 1
|
||||
return float(f"{profit_percent:.8f}")
|
||||
|
||||
@staticmethod
|
||||
|
@@ -3,11 +3,14 @@ from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from freqtrade.configuration import TimeRange
|
||||
from freqtrade.data import history
|
||||
from freqtrade.data.btanalysis import (combine_tickers_with_mean,
|
||||
create_cum_profit,
|
||||
extract_trades_of_period, load_trades)
|
||||
from freqtrade.data.converter import trim_dataframe
|
||||
from freqtrade.data.history import load_data
|
||||
from freqtrade.misc import pair_to_filename
|
||||
from freqtrade.resolvers import StrategyResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -36,39 +39,46 @@ def init_plotscript(config):
|
||||
# Set timerange to use
|
||||
timerange = TimeRange.parse_timerange(config.get("timerange"))
|
||||
|
||||
tickers = history.load_data(
|
||||
datadir=Path(str(config.get("datadir"))),
|
||||
tickers = load_data(
|
||||
datadir=config.get("datadir"),
|
||||
pairs=pairs,
|
||||
timeframe=config.get('ticker_interval', '5m'),
|
||||
timerange=timerange,
|
||||
data_format=config.get('dataformat_ohlcv', 'json'),
|
||||
)
|
||||
|
||||
trades = load_trades(config['trade_source'],
|
||||
db_url=config.get('db_url'),
|
||||
exportfilename=config.get('exportfilename'),
|
||||
)
|
||||
trades = history.trim_dataframe(trades, timerange, 'open_time')
|
||||
trades = trim_dataframe(trades, timerange, 'open_time')
|
||||
return {"tickers": tickers,
|
||||
"trades": trades,
|
||||
"pairs": pairs,
|
||||
}
|
||||
|
||||
|
||||
def add_indicators(fig, row, indicators: List[str], data: pd.DataFrame) -> make_subplots:
|
||||
def add_indicators(fig, row, indicators: Dict[str, Dict], data: pd.DataFrame) -> make_subplots:
|
||||
"""
|
||||
Generator all the indicator selected by the user for a specific row
|
||||
Generate all the indicators selected by the user for a specific row, based on the configuration
|
||||
:param fig: Plot figure to append to
|
||||
:param row: row number for this plot
|
||||
:param indicators: List of indicators present in the dataframe
|
||||
:param indicators: Dict of Indicators with configuration options.
|
||||
Dict key must correspond to dataframe column.
|
||||
:param data: candlestick DataFrame
|
||||
"""
|
||||
for indicator in indicators:
|
||||
for indicator, conf in indicators.items():
|
||||
logger.debug(f"indicator {indicator} with config {conf}")
|
||||
if indicator in data:
|
||||
kwargs = {'x': data['date'],
|
||||
'y': data[indicator].values,
|
||||
'mode': 'lines',
|
||||
'name': indicator
|
||||
}
|
||||
if 'color' in conf:
|
||||
kwargs.update({'line': {'color': conf['color']}})
|
||||
scatter = go.Scatter(
|
||||
x=data['date'],
|
||||
y=data[indicator].values,
|
||||
mode='lines',
|
||||
name=indicator
|
||||
**kwargs
|
||||
)
|
||||
fig.add_trace(scatter, row, 1)
|
||||
else:
|
||||
@@ -107,11 +117,31 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
|
||||
"""
|
||||
# Trades can be empty
|
||||
if trades is not None and len(trades) > 0:
|
||||
# Create description for sell summarizing the trade
|
||||
trades['desc'] = trades.apply(lambda row: f"{round(row['profitperc'] * 100, 1)}%, "
|
||||
f"{row['sell_reason']}, {row['duration']} min",
|
||||
axis=1)
|
||||
trade_buys = go.Scatter(
|
||||
x=trades["open_time"],
|
||||
y=trades["open_rate"],
|
||||
mode='markers',
|
||||
name='trade_buy',
|
||||
name='Trade buy',
|
||||
text=trades["desc"],
|
||||
marker=dict(
|
||||
symbol='circle-open',
|
||||
size=11,
|
||||
line=dict(width=2),
|
||||
color='cyan'
|
||||
|
||||
)
|
||||
)
|
||||
|
||||
trade_sells = go.Scatter(
|
||||
x=trades.loc[trades['profitperc'] > 0, "close_time"],
|
||||
y=trades.loc[trades['profitperc'] > 0, "close_rate"],
|
||||
text=trades.loc[trades['profitperc'] > 0, "desc"],
|
||||
mode='markers',
|
||||
name='Sell - Profit',
|
||||
marker=dict(
|
||||
symbol='square-open',
|
||||
size=11,
|
||||
@@ -119,16 +149,12 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
|
||||
color='green'
|
||||
)
|
||||
)
|
||||
# Create description for sell summarizing the trade
|
||||
desc = trades.apply(lambda row: f"{round(row['profitperc'], 3)}%, {row['sell_reason']}, "
|
||||
f"{row['duration']}min",
|
||||
axis=1)
|
||||
trade_sells = go.Scatter(
|
||||
x=trades["close_time"],
|
||||
y=trades["close_rate"],
|
||||
text=desc,
|
||||
trade_sells_loss = go.Scatter(
|
||||
x=trades.loc[trades['profitperc'] <= 0, "close_time"],
|
||||
y=trades.loc[trades['profitperc'] <= 0, "close_rate"],
|
||||
text=trades.loc[trades['profitperc'] <= 0, "desc"],
|
||||
mode='markers',
|
||||
name='trade_sell',
|
||||
name='Sell - Loss',
|
||||
marker=dict(
|
||||
symbol='square-open',
|
||||
size=11,
|
||||
@@ -138,14 +164,53 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
|
||||
)
|
||||
fig.add_trace(trade_buys, 1, 1)
|
||||
fig.add_trace(trade_sells, 1, 1)
|
||||
fig.add_trace(trade_sells_loss, 1, 1)
|
||||
else:
|
||||
logger.warning("No trades found.")
|
||||
return fig
|
||||
|
||||
|
||||
def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFrame = None,
|
||||
def create_plotconfig(indicators1: List[str], indicators2: List[str],
|
||||
plot_config: Dict[str, Dict]) -> Dict[str, Dict]:
|
||||
"""
|
||||
Combines indicators 1 and indicators 2 into plot_config if necessary
|
||||
:param indicators1: List containing Main plot indicators
|
||||
:param indicators2: List containing Sub plot indicators
|
||||
:param plot_config: Dict of Dicts containing advanced plot configuration
|
||||
:return: plot_config - eventually with indicators 1 and 2
|
||||
"""
|
||||
|
||||
if plot_config:
|
||||
if indicators1:
|
||||
plot_config['main_plot'] = {ind: {} for ind in indicators1}
|
||||
if indicators2:
|
||||
plot_config['subplots'] = {'Other': {ind: {} for ind in indicators2}}
|
||||
|
||||
if not plot_config:
|
||||
# If no indicators and no plot-config given, use defaults.
|
||||
if not indicators1:
|
||||
indicators1 = ['sma', 'ema3', 'ema5']
|
||||
if not indicators2:
|
||||
indicators2 = ['macd', 'macdsignal']
|
||||
|
||||
# Create subplot configuration if plot_config is not available.
|
||||
plot_config = {
|
||||
'main_plot': {ind: {} for ind in indicators1},
|
||||
'subplots': {'Other': {ind: {} for ind in indicators2}},
|
||||
}
|
||||
if 'main_plot' not in plot_config:
|
||||
plot_config['main_plot'] = {}
|
||||
|
||||
if 'subplots' not in plot_config:
|
||||
plot_config['subplots'] = {}
|
||||
return plot_config
|
||||
|
||||
|
||||
def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFrame = None, *,
|
||||
indicators1: List[str] = [],
|
||||
indicators2: List[str] = [],) -> go.Figure:
|
||||
indicators2: List[str] = [],
|
||||
plot_config: Dict[str, Dict] = {},
|
||||
) -> go.Figure:
|
||||
"""
|
||||
Generate the graph from the data generated by Backtesting or from DB
|
||||
Volume will always be ploted in row2, so Row 1 and 3 are to our disposal for custom indicators
|
||||
@@ -154,21 +219,26 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra
|
||||
:param trades: All trades created
|
||||
:param indicators1: List containing Main plot indicators
|
||||
:param indicators2: List containing Sub plot indicators
|
||||
:return: None
|
||||
:param plot_config: Dict of Dicts containing advanced plot configuration
|
||||
:return: Plotly figure
|
||||
"""
|
||||
plot_config = create_plotconfig(indicators1, indicators2, plot_config)
|
||||
|
||||
rows = 2 + len(plot_config['subplots'])
|
||||
row_widths = [1 for _ in plot_config['subplots']]
|
||||
# Define the graph
|
||||
fig = make_subplots(
|
||||
rows=3,
|
||||
rows=rows,
|
||||
cols=1,
|
||||
shared_xaxes=True,
|
||||
row_width=[1, 1, 4],
|
||||
row_width=row_widths + [1, 4],
|
||||
vertical_spacing=0.0001,
|
||||
)
|
||||
fig['layout'].update(title=pair)
|
||||
fig['layout']['yaxis1'].update(title='Price')
|
||||
fig['layout']['yaxis2'].update(title='Volume')
|
||||
fig['layout']['yaxis3'].update(title='Other')
|
||||
for i, name in enumerate(plot_config['subplots']):
|
||||
fig['layout'][f'yaxis{3 + i}'].update(title=name)
|
||||
fig['layout']['xaxis']['rangeslider'].update(visible=False)
|
||||
|
||||
# Common information
|
||||
@@ -238,12 +308,13 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra
|
||||
)
|
||||
fig.add_trace(bb_lower, 1, 1)
|
||||
fig.add_trace(bb_upper, 1, 1)
|
||||
if 'bb_upperband' in indicators1 and 'bb_lowerband' in indicators1:
|
||||
indicators1.remove('bb_upperband')
|
||||
indicators1.remove('bb_lowerband')
|
||||
if ('bb_upperband' in plot_config['main_plot']
|
||||
and 'bb_lowerband' in plot_config['main_plot']):
|
||||
del plot_config['main_plot']['bb_upperband']
|
||||
del plot_config['main_plot']['bb_lowerband']
|
||||
|
||||
# Add indicators to main plot
|
||||
fig = add_indicators(fig=fig, row=1, indicators=indicators1, data=data)
|
||||
fig = add_indicators(fig=fig, row=1, indicators=plot_config['main_plot'], data=data)
|
||||
|
||||
fig = plot_trades(fig, trades)
|
||||
|
||||
@@ -258,7 +329,10 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra
|
||||
fig.add_trace(volume, 2, 1)
|
||||
|
||||
# Add indicators to separate row
|
||||
fig = add_indicators(fig=fig, row=3, indicators=indicators2, data=data)
|
||||
for i, name in enumerate(plot_config['subplots']):
|
||||
fig = add_indicators(fig=fig, row=3 + i,
|
||||
indicators=plot_config['subplots'][name],
|
||||
data=data)
|
||||
|
||||
return fig
|
||||
|
||||
@@ -300,12 +374,12 @@ def generate_profit_graph(pairs: str, tickers: Dict[str, pd.DataFrame],
|
||||
return fig
|
||||
|
||||
|
||||
def generate_plot_filename(pair, timeframe) -> str:
|
||||
def generate_plot_filename(pair: str, timeframe: str) -> str:
|
||||
"""
|
||||
Generate filenames per pair/timeframe to be used for storing plots
|
||||
"""
|
||||
pair_name = pair.replace("/", "_")
|
||||
file_name = 'freqtrade-plot-' + pair_name + '-' + timeframe + '.html'
|
||||
pair_s = pair_to_filename(pair)
|
||||
file_name = 'freqtrade-plot-' + pair_s + '-' + timeframe + '.html'
|
||||
|
||||
logger.info('Generate plot file for %s', pair)
|
||||
|
||||
@@ -340,7 +414,7 @@ def load_and_plot_trades(config: Dict[str, Any]):
|
||||
- Generate plot files
|
||||
:return: None
|
||||
"""
|
||||
strategy = StrategyResolver(config).strategy
|
||||
strategy = StrategyResolver.load_strategy(config)
|
||||
|
||||
plot_elements = init_plotscript(config)
|
||||
trades = plot_elements['trades']
|
||||
@@ -359,8 +433,9 @@ def load_and_plot_trades(config: Dict[str, Any]):
|
||||
pair=pair,
|
||||
data=dataframe,
|
||||
trades=trades_pair,
|
||||
indicators1=config["indicators1"],
|
||||
indicators2=config["indicators2"],
|
||||
indicators1=config.get("indicators1", []),
|
||||
indicators2=config.get("indicators2", []),
|
||||
plot_config=strategy.plot_config if hasattr(strategy, 'plot_config') else {}
|
||||
)
|
||||
|
||||
store_plot_file(fig, filename=generate_plot_filename(pair, config['ticker_interval']),
|
||||
|
@@ -14,10 +14,10 @@ class ExchangeResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load a custom exchange class
|
||||
"""
|
||||
object_type = Exchange
|
||||
|
||||
__slots__ = ['exchange']
|
||||
|
||||
def __init__(self, exchange_name: str, config: dict, validate: bool = True) -> None:
|
||||
@staticmethod
|
||||
def load_exchange(exchange_name: str, config: dict, validate: bool = True) -> Exchange:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary
|
||||
@@ -25,17 +25,20 @@ class ExchangeResolver(IResolver):
|
||||
# Map exchange name to avoid duplicate classes for identical exchanges
|
||||
exchange_name = MAP_EXCHANGE_CHILDCLASS.get(exchange_name, exchange_name)
|
||||
exchange_name = exchange_name.title()
|
||||
exchange = None
|
||||
try:
|
||||
self.exchange = self._load_exchange(exchange_name, kwargs={'config': config,
|
||||
exchange = ExchangeResolver._load_exchange(exchange_name,
|
||||
kwargs={'config': config,
|
||||
'validate': validate})
|
||||
except ImportError:
|
||||
logger.info(
|
||||
f"No {exchange_name} specific subclass found. Using the generic class instead.")
|
||||
if not hasattr(self, "exchange"):
|
||||
self.exchange = Exchange(config, validate=validate)
|
||||
if not exchange:
|
||||
exchange = Exchange(config, validate=validate)
|
||||
return exchange
|
||||
|
||||
def _load_exchange(
|
||||
self, exchange_name: str, kwargs: dict) -> Exchange:
|
||||
@staticmethod
|
||||
def _load_exchange(exchange_name: str, kwargs: dict) -> Exchange:
|
||||
"""
|
||||
Loads the specified exchange.
|
||||
Only checks for exchanges exported in freqtrade.exchanges
|
||||
|
@@ -5,10 +5,10 @@ This module load custom hyperopt
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict
|
||||
from typing import Dict
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.constants import DEFAULT_HYPEROPT_LOSS, USERPATH_HYPEROPTS
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss
|
||||
from freqtrade.resolvers import IResolver
|
||||
@@ -20,11 +20,15 @@ class HyperOptResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load custom hyperopt class
|
||||
"""
|
||||
__slots__ = ['hyperopt']
|
||||
object_type = IHyperOpt
|
||||
object_type_str = "Hyperopt"
|
||||
user_subdir = USERPATH_HYPEROPTS
|
||||
initial_search_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||
|
||||
def __init__(self, config: Dict) -> None:
|
||||
@staticmethod
|
||||
def load_hyperopt(config: Dict) -> IHyperOpt:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
Load the custom hyperopt class from config parameter
|
||||
:param config: configuration dictionary
|
||||
"""
|
||||
if not config.get('hyperopt'):
|
||||
@@ -33,50 +37,33 @@ class HyperOptResolver(IResolver):
|
||||
|
||||
hyperopt_name = config['hyperopt']
|
||||
|
||||
self.hyperopt = self._load_hyperopt(hyperopt_name, config,
|
||||
hyperopt = HyperOptResolver.load_object(hyperopt_name, config,
|
||||
kwargs={'config': config},
|
||||
extra_dir=config.get('hyperopt_path'))
|
||||
|
||||
if not hasattr(self.hyperopt, 'populate_indicators'):
|
||||
if not hasattr(hyperopt, 'populate_indicators'):
|
||||
logger.warning("Hyperopt class does not provide populate_indicators() method. "
|
||||
"Using populate_indicators from the strategy.")
|
||||
if not hasattr(self.hyperopt, 'populate_buy_trend'):
|
||||
if not hasattr(hyperopt, 'populate_buy_trend'):
|
||||
logger.warning("Hyperopt class does not provide populate_buy_trend() method. "
|
||||
"Using populate_buy_trend from the strategy.")
|
||||
if not hasattr(self.hyperopt, 'populate_sell_trend'):
|
||||
if not hasattr(hyperopt, 'populate_sell_trend'):
|
||||
logger.warning("Hyperopt class does not provide populate_sell_trend() method. "
|
||||
"Using populate_sell_trend from the strategy.")
|
||||
|
||||
def _load_hyperopt(
|
||||
self, hyperopt_name: str, config: Dict, extra_dir: Optional[str] = None) -> IHyperOpt:
|
||||
"""
|
||||
Search and loads the specified hyperopt.
|
||||
:param hyperopt_name: name of the module to import
|
||||
:param config: configuration dictionary
|
||||
:param extra_dir: additional directory to search for the given hyperopt
|
||||
:return: HyperOpt instance or None
|
||||
"""
|
||||
current_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||
|
||||
abs_paths = self.build_search_paths(config, current_path=current_path,
|
||||
user_subdir=USERPATH_HYPEROPTS, extra_dir=extra_dir)
|
||||
|
||||
hyperopt = self._load_object(paths=abs_paths, object_type=IHyperOpt,
|
||||
object_name=hyperopt_name, kwargs={'config': config})
|
||||
if hyperopt:
|
||||
return hyperopt
|
||||
raise OperationalException(
|
||||
f"Impossible to load Hyperopt '{hyperopt_name}'. This class does not exist "
|
||||
"or contains Python code errors."
|
||||
)
|
||||
|
||||
|
||||
class HyperOptLossResolver(IResolver):
|
||||
"""
|
||||
This class contains all the logic to load custom hyperopt loss class
|
||||
"""
|
||||
__slots__ = ['hyperoptloss']
|
||||
object_type = IHyperOptLoss
|
||||
object_type_str = "HyperoptLoss"
|
||||
user_subdir = USERPATH_HYPEROPTS
|
||||
initial_search_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||
|
||||
def __init__(self, config: Dict) -> None:
|
||||
@staticmethod
|
||||
def load_hyperoptloss(config: Dict) -> IHyperOptLoss:
|
||||
"""
|
||||
Load the custom class from config parameter
|
||||
:param config: configuration dictionary
|
||||
@@ -86,38 +73,15 @@ class HyperOptLossResolver(IResolver):
|
||||
# default hyperopt loss
|
||||
hyperoptloss_name = config.get('hyperopt_loss') or DEFAULT_HYPEROPT_LOSS
|
||||
|
||||
self.hyperoptloss = self._load_hyperoptloss(
|
||||
hyperoptloss_name, config, extra_dir=config.get('hyperopt_path'))
|
||||
hyperoptloss = HyperOptLossResolver.load_object(hyperoptloss_name,
|
||||
config, kwargs={},
|
||||
extra_dir=config.get('hyperopt_path'))
|
||||
|
||||
# Assign ticker_interval to be used in hyperopt
|
||||
self.hyperoptloss.__class__.ticker_interval = str(config['ticker_interval'])
|
||||
hyperoptloss.__class__.ticker_interval = str(config['ticker_interval'])
|
||||
|
||||
if not hasattr(self.hyperoptloss, 'hyperopt_loss_function'):
|
||||
if not hasattr(hyperoptloss, 'hyperopt_loss_function'):
|
||||
raise OperationalException(
|
||||
f"Found HyperoptLoss class {hyperoptloss_name} does not "
|
||||
"implement `hyperopt_loss_function`.")
|
||||
|
||||
def _load_hyperoptloss(
|
||||
self, hyper_loss_name: str, config: Dict,
|
||||
extra_dir: Optional[str] = None) -> IHyperOptLoss:
|
||||
"""
|
||||
Search and loads the specified hyperopt loss class.
|
||||
:param hyper_loss_name: name of the module to import
|
||||
:param config: configuration dictionary
|
||||
:param extra_dir: additional directory to search for the given hyperopt
|
||||
:return: HyperOptLoss instance or None
|
||||
"""
|
||||
current_path = Path(__file__).parent.parent.joinpath('optimize').resolve()
|
||||
|
||||
abs_paths = self.build_search_paths(config, current_path=current_path,
|
||||
user_subdir=USERPATH_HYPEROPTS, extra_dir=extra_dir)
|
||||
|
||||
hyperoptloss = self._load_object(paths=abs_paths, object_type=IHyperOptLoss,
|
||||
object_name=hyper_loss_name)
|
||||
if hyperoptloss:
|
||||
return hyperoptloss
|
||||
|
||||
raise OperationalException(
|
||||
f"Impossible to load HyperoptLoss '{hyper_loss_name}'. This class does not exist "
|
||||
"or contains Python code errors."
|
||||
)
|
||||
|
@@ -7,7 +7,9 @@ import importlib.util
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Optional, Tuple, Union, Generator
|
||||
from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -16,11 +18,19 @@ class IResolver:
|
||||
"""
|
||||
This class contains all the logic to load custom classes
|
||||
"""
|
||||
# Childclasses need to override this
|
||||
object_type: Type[Any]
|
||||
object_type_str: str
|
||||
user_subdir: Optional[str] = None
|
||||
initial_search_path: Optional[Path]
|
||||
|
||||
def build_search_paths(self, config, current_path: Path, user_subdir: Optional[str] = None,
|
||||
@classmethod
|
||||
def build_search_paths(cls, config: Dict[str, Any], user_subdir: Optional[str] = None,
|
||||
extra_dir: Optional[str] = None) -> List[Path]:
|
||||
|
||||
abs_paths: List[Path] = [current_path]
|
||||
abs_paths: List[Path] = []
|
||||
if cls.initial_search_path:
|
||||
abs_paths.append(cls.initial_search_path)
|
||||
|
||||
if user_subdir:
|
||||
abs_paths.insert(0, config['user_data_dir'].joinpath(user_subdir))
|
||||
@@ -31,42 +41,47 @@ class IResolver:
|
||||
|
||||
return abs_paths
|
||||
|
||||
@staticmethod
|
||||
def _get_valid_object(object_type, module_path: Path,
|
||||
object_name: str) -> Generator[Any, None, None]:
|
||||
@classmethod
|
||||
def _get_valid_object(cls, module_path: Path, object_name: Optional[str],
|
||||
enum_failed: bool = False) -> Iterator[Any]:
|
||||
"""
|
||||
Generator returning objects with matching object_type and object_name in the path given.
|
||||
:param object_type: object_type (class)
|
||||
:param module_path: absolute path to the module
|
||||
:param object_name: Class name of the object
|
||||
:param enum_failed: If True, will return None for modules which fail.
|
||||
Otherwise, failing modules are skipped.
|
||||
:return: generator containing matching objects
|
||||
"""
|
||||
|
||||
# Generate spec based on absolute path
|
||||
# Pass object_name as first argument to have logging print a reasonable name.
|
||||
spec = importlib.util.spec_from_file_location(object_name, str(module_path))
|
||||
spec = importlib.util.spec_from_file_location(object_name or "", str(module_path))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
try:
|
||||
spec.loader.exec_module(module) # type: ignore # importlib does not use typehints
|
||||
except (ModuleNotFoundError, SyntaxError) as err:
|
||||
# Catch errors in case a specific module is not installed
|
||||
logger.warning(f"Could not import {module_path} due to '{err}'")
|
||||
if enum_failed:
|
||||
return iter([None])
|
||||
|
||||
valid_objects_gen = (
|
||||
obj for name, obj in inspect.getmembers(module, inspect.isclass)
|
||||
if object_name == name and object_type in obj.__bases__
|
||||
if ((object_name is None or object_name == name) and
|
||||
issubclass(obj, cls.object_type) and obj is not cls.object_type)
|
||||
)
|
||||
return valid_objects_gen
|
||||
|
||||
@staticmethod
|
||||
def _search_object(directory: Path, object_type, object_name: str,
|
||||
kwargs: dict = {}) -> Union[Tuple[Any, Path], Tuple[None, None]]:
|
||||
@classmethod
|
||||
def _search_object(cls, directory: Path, object_name: str
|
||||
) -> Union[Tuple[Any, Path], Tuple[None, None]]:
|
||||
"""
|
||||
Search for the objectname in the given directory
|
||||
:param directory: relative or absolute directory path
|
||||
:return: object instance
|
||||
:param object_name: ClassName of the object to load
|
||||
:return: object class
|
||||
"""
|
||||
logger.debug("Searching for %s %s in '%s'", object_type.__name__, object_name, directory)
|
||||
logger.debug(f"Searching for {cls.object_type.__name__} {object_name} in '{directory}'")
|
||||
for entry in directory.iterdir():
|
||||
# Only consider python files
|
||||
if not str(entry).endswith('.py'):
|
||||
@@ -74,14 +89,14 @@ class IResolver:
|
||||
continue
|
||||
module_path = entry.resolve()
|
||||
|
||||
obj = next(IResolver._get_valid_object(object_type, module_path, object_name), None)
|
||||
obj = next(cls._get_valid_object(module_path, object_name), None)
|
||||
|
||||
if obj:
|
||||
return (obj(**kwargs), module_path)
|
||||
return (obj, module_path)
|
||||
return (None, None)
|
||||
|
||||
@staticmethod
|
||||
def _load_object(paths: List[Path], object_type, object_name: str,
|
||||
@classmethod
|
||||
def _load_object(cls, paths: List[Path], object_name: str,
|
||||
kwargs: dict = {}) -> Optional[Any]:
|
||||
"""
|
||||
Try to load object from path list.
|
||||
@@ -89,16 +104,67 @@ class IResolver:
|
||||
|
||||
for _path in paths:
|
||||
try:
|
||||
(module, module_path) = IResolver._search_object(directory=_path,
|
||||
object_type=object_type,
|
||||
object_name=object_name,
|
||||
kwargs=kwargs)
|
||||
(module, module_path) = cls._search_object(directory=_path,
|
||||
object_name=object_name)
|
||||
if module:
|
||||
logger.info(
|
||||
f"Using resolved {object_type.__name__.lower()[1:]} {object_name} "
|
||||
f"Using resolved {cls.object_type.__name__.lower()[1:]} {object_name} "
|
||||
f"from '{module_path}'...")
|
||||
return module
|
||||
return module(**kwargs)
|
||||
except FileNotFoundError:
|
||||
logger.warning('Path "%s" does not exist.', _path.resolve())
|
||||
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def load_object(cls, object_name: str, config: dict, kwargs: dict,
|
||||
extra_dir: Optional[str] = None) -> Any:
|
||||
"""
|
||||
Search and loads the specified object as configured in hte child class.
|
||||
:param objectname: name of the module to import
|
||||
:param config: configuration dictionary
|
||||
:param extra_dir: additional directory to search for the given pairlist
|
||||
:raises: OperationalException if the class is invalid or does not exist.
|
||||
:return: Object instance or None
|
||||
"""
|
||||
|
||||
abs_paths = cls.build_search_paths(config,
|
||||
user_subdir=cls.user_subdir,
|
||||
extra_dir=extra_dir)
|
||||
|
||||
pairlist = cls._load_object(paths=abs_paths, object_name=object_name,
|
||||
kwargs=kwargs)
|
||||
if pairlist:
|
||||
return pairlist
|
||||
raise OperationalException(
|
||||
f"Impossible to load {cls.object_type_str} '{object_name}'. This class does not exist "
|
||||
"or contains Python code errors."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def search_all_objects(cls, directory: Path,
|
||||
enum_failed: bool) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Searches a directory for valid objects
|
||||
:param directory: Path to search
|
||||
:param enum_failed: If True, will return None for modules which fail.
|
||||
Otherwise, failing modules are skipped.
|
||||
:return: List of dicts containing 'name', 'class' and 'location' entires
|
||||
"""
|
||||
logger.debug(f"Searching for {cls.object_type.__name__} '{directory}'")
|
||||
objects = []
|
||||
for entry in directory.iterdir():
|
||||
# Only consider python files
|
||||
if not str(entry).endswith('.py'):
|
||||
logger.debug('Ignoring %s', entry)
|
||||
continue
|
||||
module_path = entry.resolve()
|
||||
logger.debug(f"Path {module_path}")
|
||||
for obj in cls._get_valid_object(module_path, object_name=None,
|
||||
enum_failed=enum_failed):
|
||||
objects.append(
|
||||
{'name': obj.__name__ if obj is not None else '',
|
||||
'class': obj,
|
||||
'location': entry,
|
||||
})
|
||||
return objects
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user